Sahil Sharma
Sahil Sharma

Reputation: 4247

Elastic search : How to divide a number in the document and then sort?

We have the following document in the elastic search:

[
        {
        "price" : "95",
        "relevance" : 5
        },
        {
        "price" : "105",
        "relevance" : 7
        },
        {
        "price" : "92",
        "relevance" : 3
        },
        {
        "price" : "82",
        "relevance" : 1
        },
        {
        "price" : "89",
        "relevance" : 9
        }
    ]

We want to sort it on the basis of price (bucketed) and then on the basis of relevance inside those buckets i.e. sort price in bucket of 10s so output should be:

[
    {
    "price" : "105",
    "relevance" : 7
    },
    {
    "price" : "95",
    "relevance" : 5
    },
    {
    "price" : "92",
    "relevance" : 3
    },
    {
    "price" : "89",
    "relevance" : 9
    },
    {
    "price" : "82",
    "relevance" : 1
    }
]

First, we divide every price by 10 and create buckets by int part of the division (We will get bucket - 9, 10, 8) => after sorting buckets it would be documents with (10, 9, 8). Then sort the documents inside those buckets by relevance.

Upvotes: 2

Views: 872

Answers (1)

Val
Val

Reputation: 217554

The following query should work as you expect:

POST index/_search
{
  "size": 0,
  "aggs": {
    "prices": {
      "terms": {
        "script": "doc.price.value / 10",
        "order": {
          "max_price": "desc"
        }
      },
      "aggs": {
        "max_price": {
          "max": {
            "field": "price"
          }
        },
        "docs": {
          "top_hits": {
            "size": 5,
            "sort": {
              "relevance": "desc"
            }
          }
        }
      }
    }
  }
}

Upvotes: 1

Related Questions