Dynamic elasticsearch query - add another field to each returned document

I need it very simply, but I cannot find how to do this in Elasticsearch, possibly due to the complexity of what needs to be done.

Input (two sample JSON documents)

{ "car" : 150, "bike" : 300 }

{ "car" : 100, "bike" : 200}

What I want in return is that when I run a search query, it returns documents to me with an additional field inventory, which is defined as the sum of the number of cars and bicycles. And in sorted order.

Output Example:

hits: [
   { "car" : 150, "bike" : 300, "inventory": 450},
   { "car" : 100, "bike" : 200, "inventory": 300}
]

Is it possible to do something like this in elasticsearch? (I assume the use of dynamic scripts)

+4
1

, script. .

http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-script-fields.html

:

query: {
...
},
script_fields: {
  inventory: {
     script: "doc['car'].value + doc['bike'].value"
  }
}

:

fields: {
    inventory: [450]
}

, , , :

query: {
...
},
sort: {
    _script: {
        script: "doc['car'].value + doc['bike'].value",
        type: "number",
        order: "desc"
    }
}

, :

sort: [450]
+4

All Articles