Jack Pilowsky
Jack Pilowsky

Reputation: 2303

Elastic Search sort by field defined in another field

I have two fields: count (object) and countyby (text). The count object has several nested properties of type number:

"count" : {
    "properties" : 
     "value1" : {
         "type" : "long"
     },
     "value2" : {
         "type" : "long"
     },
     "value3" : {
         "type" : "long"
     },
     "value4" : {
         "type" : "long"
     },
     "value5" : {
         "type" : "long"
     }
 },
 "countBy": {
     type: "keyword"
 }

I need to do a search that will sort the documents according to the value of count's nested property that is specified in the countBy property

Upvotes: 0

Views: 257

Answers (1)

Val
Val

Reputation: 217304

You can achieve this with script-based sorting:

"sort" : {
    "_script" : {
        "type" : "number",
        "script" : {
            "lang": "painless",
            "source": "doc['countBy'].value != null ? doc['count.'+doc['countBy'].value].value : 0"
        },
        "order" : "desc"
    }
}

Upvotes: 1

Related Questions