How to Sort a Query by a Numeric Field in Elasticsearch 6

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

When you search for data in Elasticsearch, you often want your results to come back in a certain order. Perhaps you want to see students’ grades sorted from the highest to the lowest, or you’d like to have your inventory listed from the least number of units to the highest for re-ordering purposes. Fortunately, Elasticsearch makes it easy to sort your data in either ascending or descending order. In this tutorial, we’ll show you how to sort a query by a numeric field in Elasticsearch 6. If you’re already familiar with searching and sorting in Elasticsearch, you can skip ahead to Just the Code.

Sort ascending using the sort parameter

Let’s begin our tutorial with an example that shows how to sort data in ascending order. We’ll create a sample index called store, which represents a small grocery store. Our store index contains the type products which lists all of the store’s products. We’ll keep our dataset simple by including just a handful of products with a small number of fields: id, price, quantity, and department. The JSON shown below can be used to create our dataset:

idnamepricequantitydepartment
1Multi-Grain Cereal4.994Packaged Foods
21lb Ground Beef3.9929Meat and Seafood
3Dozen Apples2.4912Produce
4Chocolate Bar1.292Packaged Foods, Checkout
51 Gallon Milk3.2916Dairy
60.5lb Jumbo Shrimp5.2912Meat and Seafood
7Wheat Bread1.295Bakery
8Pepperoni Pizza2.995Frozen
912 Pack Cola5.296Packaged Foods
10Lime Juice0.9920Produce
1112 Pack Cherry Cola5.5995Packaged Foods
121 Gallon Soy Milk3.3910Dairy
131 Gallon Vanilla SoyMilk3.499Dairy
141 Gallon Orange Juice3.294Juice

For our example, let’s imagine we want to determine which items our store is running low on. We’d accomplish this by querying the database and having our results sorted in ascending order by quantity. Since our dataset is small, we can glance at our data and see that the “Chocolate Bar” would appear first because it’s the lowest in quantity. The following curl command has the query set to match_all, which will return all documents. Note that the query is set to sort on the quantity field in ascending order with "quantity":"asc".

Note: In this example, we’re running Elasticsearch locally and using the default port, so our curl request takes the form: "127.0.0.1:9200". Depending on which server and port your installation of Elasticsearch is running on, your curl may have a slightly different format: "YOURDOMAIN.com:9200".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
$ curl -H "Content-Type: application/json" -XGET "127.0.0.1:9200/store/_search?pretty" -d '
> {
> "query":
> {
> "match_all": {}
> },
> "sort":
> [
> {
> "quantity": "asc"
> }
> ]
> }
> '

{
"took" : 5,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 14,
"max_score" : null,
"hits" : [
{
"_index" : "store",
"_type" : "products",
"_id" : "4",
"_score" : null,
"_source" : {
"id" : "4",
"name" : "Chocolate Bar",
"price" : 1.29,
"quantity" : 2,
"department" : [
"Packaged Foods",
"Checkout"
]
},
"sort" : [
2
]
},

Although this output is trimmed down a bit for size, you can see that 14 results are returned and that “Chocolate Bar” was indeed the first result because it has the smallest quantity.

Sort descending using the sort parameter

Now that we’ve seen how to sort in ascending order, let’s look at the same query in reverse order simply by changing the sort to "quantity": "desc". For this query, the first result shown should be “1lb Ground Beef” because it has the highest quantity. Let’s run this query and see if it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
$ curl -H "Content-Type: application/json" -XGET "127.0.0.1:9200/store/_search?pretty" -d '
> {
> "query":
> {
> "match_all": {}
> },
> "sort":
> [
> {
> "quantity": "desc"
> }
> ]
> }
> '

{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 14,
"max_score" : null,
"hits" : [
{
"_index" : "store",
"_type" : "products",
"_id" : "2",
"_score" : null,
"_source" : {
"id" : "2",
"name" : "1lb Ground Beef",
"price" : 3.99,
"quantity" : 29,
"department" : [
"Meat and Seafood"
]
},
"sort" : [
29
]
},

We can confirm that this query sorts the results correctly since the first item returned is indeed the “1lb Ground Beef”.

Conclusion

When you’re searching for data, you often want your results to be returned in a particular order. Elasticsearch makes this task simple with its sorting functionality, allowing you to sort a field in either ascending or descending order. With the step-by-step instructions included in this tutorial, you’ll have no trouble sorting a query by a numeric field in Elasticsearch 6.

Just the Code

If you’re already familiar with basic searching and sorting principles, here’s all the code you need to sort a query by a numeric field in Elasticsearch 6: `js $ curl -H “Content-Type: application/json” -XGET “127.0.0.1:9200/store/_search?pretty” -d ‘ > { > “query”: > { > “match_all”: {} > }, > “sort”: > [ > { > “quantity”: “asc” > } > ] > } > ‘ ```js
$ curl -H "Content-Type: application/json" -XGET "127.0.0.1:9200/store/_search?pretty" -d '
> {
> "query":
> {
> "match_all": {}
> },
> "sort":
> [
> {
> "quantity": "desc"
> }
> ]
> }
> '

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.