Book Image

ElasticSearch Cookbook

By : Alberto Paro
Book Image

ElasticSearch Cookbook

By: Alberto Paro

Overview of this book

Table of Contents (20 chapters)
ElasticSearch Cookbook Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Sorting data using script


ElasticSearch provides scripting support for the sorting functionality. In real world applications, there is often a need to modify the default sort by the match score using an algorithm that depends on the context and some external variables. Some common scenarios are given as follows:

  • Sorting places near a point

  • Sorting by most-read articles

  • Sorting items by custom user logic

  • Sorting items by revenue

Getting ready

You will need a working ElasticSearch cluster and an index populated with the script used in Chapter 6, Aggregations, which is available at https://github.com/aparo/elasticsearch-cookbook-second-edition.

How to do it...

In order to sort using scripting, perform the following steps:

  1. If you want to order your documents by the price field multiplied by a factor parameter (that is, sales tax), the search will be as shown in the following code:

     curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_search?&pretty=true&size=3' -d '{
      "query": {
        "match_all...