Elasticsearch implementing sort by field and direction

814 views Asked by At

I've been reading the documentation and other example posts since yesterday to work out how to add sort by field and the direction to my current query array here but so far no luck. I've seen examples like {"sort": {"_score": "desc"}, "query": { .... but couldn't quiet get my head around it to modify my array since this is the very first time I'm dealing with ES.

All I need is: I want to be able to sort by price or stock in asc or desc order.

Everytime I try to update my array to implement sorting, I get {"error":{"code":0,"message":"Invalid option sort"}} error.

NOTE: The query array is being passed to Pagerfanta to get results.

    $paginator = $this->productFinder->findPaginated($myArray)
        ->setMaxPerPage($limit)
        ->setCurrentPage($page);
2

There are 2 answers

0
BentCoder On BEST ANSWER

For the specific field and direction:

{
   "sort": {
      "price": "asc"
   }
   ... rest of the code
}

For no particular sorting (this is set by default):

{
   "sort": {
      "_score": "desc"
   }
   ... rest of the code
}
3
Roeland Van Heddegem On

Here's an example:

{
  "_source":true,
  "query":{
    "simple_query_string":{
      "query":"1*"
    }
  },
  "sort":[
    {
      "price":{
        "order":"desc",
        "missing":"_last"
      }
    },
    {
      "_score":{
        "order":"desc",
        "missing":"_last"
      }
    }
  ]
}