Elasticsearch将范围和术语连接到同一数组项 [英] Elasticsearch connect range and term to same array item
问题描述
我有一个用户文档,其中包含一个名为 experiences 的字段,该字段是一个对象数组,例如:
I have a user document with a field called experiences which is an array of objects, like:
{
"experiences": [
{
"end_date": "2017-03-02",
"is_valid": false
},
{
"end_date": "2015-03-02",
"is_valid": true
}
]
}
使用此文档,我必须搜索结束日期为去年且is_valid为true的用户. 目前,我有一个 query-> bool ,我必须在其中添加两个,一个为 end_date range ,一个为 term 表示 is_valid .
With this document I have to search users where end date is in last year and is_valid is true. At this time I have a query -> bool and I add two must there, one range for the end_date and one term for the is_valid.
{
"query": {
"bool": {
"must": {
"term": {
"experiences.is_valid": true
},
"range": {
"experiences.end_date": {
"gte": "now-1y",
"lte": "now"
}
},
}
}
}
}
结果是选择该用户的原因是,该用户在去年(第一次体验)和另一个体验具有结束日期. is_valid true . 当然这不是我所需要的,因为我需要 end_date 和 is_valid 必须引用同一对象,但是我们如何在Elasticsearch上做到这一点?
The result is that this user is selected because he has an end_date in the last year (the first exp.) and another exp. with is_valid true. Of course this is not what I need, because I need that end_date and is_valid must be referenced to the same object, but how can we do this on Elasticsearch?
映射:
"experiences": {
"properties": {
"comment": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"end_date": {
"type": "date"
},
"id": {
"type": "long"
},
"is_valid": {
"type": "boolean"
},
"start_date": {
"type": "date"
}
}
}
推荐答案
您需要将experiences
类型更改为然后应用nested
查询:
{
"query": {
"nested": {
"path": "experiences",
"query": {
"bool": {
"must": [
{
"term": {
"experiences.is_valid": true
}
},
{
"range": {
"experiences.end_date": {
"gte": "now-1y",
"lte": "now"
}
}
}
]
}
}
}
}
}
这是由于在Elasticsearch中扁平化对象数组的方式. 在此处
This is due to the way arrays of objects are flattened in Elasticsearch. Study more here
这篇关于Elasticsearch将范围和术语连接到同一数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!