elasticsearch动态查询-向返回的每个文档中添加另一个字段 [英] elasticsearch dynamic query - Add another field to each document returned

本文介绍了elasticsearch动态查询-向返回的每个文档中添加另一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所需要的非常简单,但是我可能无法在Elasticsearch中找到方法,这可能是因为需要完成的工作很复杂.

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.

输入(两个示例JSON文档)

Input (two sample JSON documents)

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

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

我想要返回的是,当我触发搜索查询时,它会向我返回带有额外字段 inventory 的文档,该字段定义为汽车和自行车的总数.并按排序顺序.

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.

示例输出:

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

是否可以在elasticsearch中做类似的事情?(我假设使用动态脚本)

Is it possible to do something like this in elasticsearch? (I assume using dynamic scripting)

推荐答案

我使用脚本字段进行了此操作.参考:

I did this using script fields. Refer:

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"
  }
}

这将导致一个单独的字段列,每个匹配项为:

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]

这篇关于elasticsearch动态查询-向返回的每个文档中添加另一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆