rudak
rudak

Reputation: 389

Elasticsearch sort by nested object

i'm just discovering elasticsearch and i'm trying to make my first queries. for example in my case, each article has several prices, I would like to sort these articles by minimum price. and therefore I would not take the other ones into consideration. it is only the minimum prices that will have to sort my articles.
here are my articles :

{
           "name": "john",
           "prices": [
              {
                 "price": "22"
              },
              {
                 "price": "28"
              },
              {
                 "price": "8"
              }
           ]
        },
        {
           "name": "peter",
           "prices": [
              {
                 "price": "7"
              },
              {
                 "price": "5"
              },
              {
                 "price": "2"
              }
           ]
        },
        {
           "name": "billy",
           "prices": [
              {
                 "price": "15"
              },
              {
                 "price": "17"
              }
           ]
        }

Upvotes: 0

Views: 631

Answers (1)

smnh
smnh

Reputation: 1745

POST /_search

{
    "query" : {
        "match_all": {}
    },
    "sort" : [
        {
            "prices.price": {
                "order": "asc",
                "mode" : "min"
            }
        }
    ]
}

Note: If your prices objects are of nested type (and not object) then you also need to add the "nested_path": "prices" inside the prices.price.

More info on sorting can be found here: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html

Upvotes: 1

Related Questions