elasticsearch - ElasticSearch 聚合与数组项上的过滤器
问题描述
我想用一些额外的逻辑来做一个聚合请求,但我不确定它是否可能以及如何去做。当我有以下文档时,如何请求数组中没有定义“类型”的位置?我尝试在类型上发送子聚合过滤器,但随后位置“20”在该聚合上获取 doc_count 1。
在这种情况下,如何对匹配的聚合项进行一些逻辑处理?
文件:
//document1
{
"locations": [{
"code": "20",
"names": [{
"languageCode": "en-GB",
"value": "Amsterdam"
}
]
}, {
"type": {
"id": 25,
"names": [{
"languageCode": "en-GB",
"value": "area"
}
]
},
"code": "21",
"names": [{
"languageCode": "en-GB",
"value": "Amsterdam-South"
}
]
}
]
}
//Document 2
{
"locations": [{
"code": "22",
"names": [{
"languageCode": "en-GB",
"value": "DenHague"
}, {
"languageCode": "nl-NL",
"value": "DenHaag"
}
]
}
]
}
要求:
{
"aggs": {
"Filter_Location": {
"aggs": {
"SubType": {
"filter": {
"exists": {
"field": "locations.type"
}
}
} },
"terms": {
"field": "locations.code.keyword"
}
}
},
"size": 0
}
结果:
{
"aggregations": {
"Filter_Location": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": "20",
"doc_count": 1,
"SubType": {
"doc_count": 1
},
"groupByAccoId": {
"value": 1
}
}, {
"key": "21",
"doc_count": 1,
"SubType": {
"doc_count": 1
},
"groupByAccoId": {
"value": 1
}
}, {
"key": "22",
"doc_count": 1,
"SubType": {
"doc_count": 0
},
"groupByAccoId": {
"value": 1
}
}
]
}
}
}
预期结果:
{
"aggregations": {
"Filter_Location": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": "20",
"doc_count": 1,
"SubType": {
"doc_count": 0
}
}, {
"key": "21",
"doc_count": 1,
"SubType": {
"doc_count": 1
}
}, {
"key": "22",
"doc_count": 1,
"SubType": {
"doc_count": 0
}
}
]
}
}
}
解决方案
为了防止locations
数组变平,您需要将索引映射设置为nested
:
PUT ind
{
"mappings": {
"properties": {
"locations": {
"type": "nested"
}
}
}
}
摄取文档后,此查询将为您获取所需的结果:
GET ind/_search
{
"size": 0,
"aggs": {
"Filter_Location_parent": {
"nested": {
"path": "locations"
},
"aggs": {
"Filter_Location": {
"terms": {
"field": "locations.code.keyword"
},
"aggs": {
"SubType": {
"filter": {
"exists": {
"field": "locations.type"
}
}
}
}
}
}
}
}
}
推荐阅读
- javascript - 如何在 MySQL 中存储数据?
- java - 如何用hibernate将中文字符写入mysql?
- c# - 如何使用 .Net WebProxy 类
- c++ - 将c ++崩溃重定向到stderr
- python - request.POST 在 ajax 调用中的 django 1.11 gae 应用程序中为空
- identityserver4 - Identity Server 4 - 更新外部提供者提供的声明
- python - 无法使用 PyPi 正确发布模块
- javascript - 实施测试后的节点调度程序错误
- javascript - 如何使用 react-native-fs?
- php - Woocommerce 更新订单挂钩“save_post”不允许文件保存