Ganesh Ganesh - 5 months ago 32
Perl Question

How to sort "sum of 3 properties" in Elasticsearch?

I want to add these 3 properties (like + comment + share) and also want to sort the sum of 3 properties.

curl -XPUT 'http://XXX.X.XX.XXX:XXXXX/stores/' -d '{
"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 1
}
},
"mappings" : {
"store" : {
"_all":{ "enabled": true },
"properties":{
"url" : { "type" : "string", "analyzer" : "simple", "boost" : 3 },
"title" : { "type" : "string", "boost" : 2 },
"description" : { "type" : "string" },
"like":{"type":"long"},
"comment":{"type":"long"},
"share":{"type":"long"},
"time_added" : { "type" : "integer", "index" : "not_analyzed", "include_in_all": true }
}
}
} }'


what is the query to do this in elasticsearch.
my elasticsearch version is 2.4.0

Answer Source

Try the below query :

GET /index/_search
{
    "query": {
        "match_all": {}
    },
    "sort": [
        {
           "_script": {
              "script": "doc['share'].value + doc['like'].value+doc['comment'].value",
              "type": "number",
              "order": "desc"
           }
        }
    ]
}

The query will fetch all data and sort them in descending order according to the total value of (share+like+comment).

If you want to sort in ascending order then change the order value to asc.

To run script query, you need to add script.engine.groovy.inline.search: on on your config/elasticsearch.yml file.