mrinalsh
mrinalsh

Reputation: 31

How to limit and then sort in Elastic Search

I want to first limit the results returned by elastic search(sorted by _score) to 1000 and then sort those 1000 results by a specific field.

An example in SQL would be -

select name,count,score 
from 
  (select name,count,score from users order by score limit 1000) A 
order by count

How can I do this in elastic search?

Upvotes: 3

Views: 1395

Answers (2)

Arun Prakash
Arun Prakash

Reputation: 1727

You can use the secondary sort option to achieve this. Sort by the following order

  1. _score (elasticsearch score)
  2. sort_field (count as per your Q)

Bellow query will search the documents and sort first using the elasticsearch calculated score value then the second level sorting will apply for the field count and the size(limit) will be 1000 so only the 1000 documents return to you.

Sample

{
  "size": 1000,
  "query": {
    "match_all": {}
  },
  "sort": [
    "_score",
    {
      "count": {
        "order": "asc"
      }
    }
  ],
  "fields": [
    "name",
    "count",
    "score"
  ]
}

Upvotes: 1

vinod_vh
vinod_vh

Reputation: 1061

Try below query

{
"filtered" : {
    "filter" : {
         "limit" : {"value" : 100}
     },
    "sort" : [
        {"score " : {"order" : "asc"}}
    ]
    "query" : {
        "term" : { "name" : "shay" }
    }
  }
}

Upvotes: 0

Related Questions