elasticsearch - 带有条件的 Elasticsearch 子聚合
问题描述
我有数据库表列,如:
身份证 | 企业名称 | 许可证 # | 违规 | ...
我需要找出那些违规超过 5 次的企业。
我有以下内容:
{
"query": {
"bool": {
"must": {
"match": {
"violations": {
"query": "MICE DROPPINGS were OBSERVED",
"operator": "and"
}
}
},
"must_not": {
"match": {
"violations": {
"query": "NO MICE DROPPINGS were OBSERVED",
"operator": "and"
}
}
}
}
}
},
"aggs" : {
"selected_bizs" :{
"terms" : {
"field" : "Biz Name.keyword",
"min_doc_count": 5,
"size" :1000
},
"aggs": {
"top_biz_hits": {
"top_hits": {
"size": 10
}
}
}
}
}
}
它似乎工作。
现在我需要找出那些有 5 个或更多违规行为(如上)并且还有 3 个或更多许可证#s 的企业。
我不确定如何进一步汇总这一点。
谢谢!
解决方案
让我们假设您的License #
字段的定义就像Biz Name
并且具有.keyword
映射。
现在,声明:
查找拥有... 3 个或更多许可证 #s 的企业
可以改写为:
在分桶的不同值的数量大于或等于 3
business name
的条件下聚合。license IDs
话虽如此,您可以使用聚合cardinality
来获取不同的许可证 ID。
其次,“条件聚合”的机制是方便的bucket_script
聚合,它执行一个脚本来确定当前迭代的桶是否会保留在最终的聚合中。
同时利用这两者意味着:
POST your-index/_search
{
"size": 0,
"query": {
"bool": {
"must": {
"match": {
"violations": {
"query": "MICE DROPPINGS were OBSERVED",
"operator": "and"
}
}
},
"must_not": {
"match": {
"violations": {
"query": "NO MICE DROPPINGS were OBSERVED",
"operator": "and"
}
}
}
}
},
"aggs": {
"selected_bizs": {
"terms": {
"field": "Biz Name.keyword",
"min_doc_count": 5,
"size": 1000
},
"aggs": {
"top_biz_hits": {
"top_hits": {
"size": 10
}
},
"unique_license_ids": {
"cardinality": {
"field": "License #.keyword"
}
},
"must_have_min_3_License #s": {
"bucket_selector": {
"buckets_path": {
"unique_license_ids": "unique_license_ids"
},
"script": "params.unique_license_ids >= 3"
}
}
}
}
}
}
仅此而已!
推荐阅读
- python - 如何使用 matlplotlib 将 x 轴上的秒数转换为小时数?
- python - 梯度下降权重/偏差更新如何在这里工作?
- c# - 来自 SqlConnectionBuilder 的异常
- mysql - Grouping rows via two different columns in MYSQL
- scala - MLlib MatrixFactorizationModel RecommendationProducts(user, num) 还返回训练数据产品项
- javascript - Double rendering in React with asynchronous call in componentDidMount causing error
- html - Angular generated css breaks child combinator
- git - Git添加预提交钩子而不是暂存文件以进行提交
- asp.net-web-api2 - Swagger ui 无法在服务器中加载 json 规范文件
- javascript - 从另一个组件更改组件的属性并在 html 中以角度 2 呈现它