elasticsearch dynamic query - Add another field to each document returned

谁都会走 提交于 2021-02-06 09:26:07

问题


What I need is very simple, but I am unable to find how to do it in Elasticsearch, possibly because of the complexity of what is required 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 fire a search query it returns me the documents with an extra field inventory which is defined as the sum of number of cars and bikes. And in the sorted order.

Sample Output:

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 using dynamic scripting)


回答1:


I did this using script fields. Refer:

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

sample query:

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

This would result in a separate fields column with each hit as:

fields: {
    inventory: [450]
}

But, since I also wanted this to be sorted, I ended up using the sort:

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

which returned me a sort field with each hit, such as:

sort: [450]


来源:https://stackoverflow.com/questions/26221274/elasticsearch-dynamic-query-add-another-field-to-each-document-returned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!