首页 > 解决方案 > 带有条件的 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 的企业。

我不确定如何进一步汇总这一点。

谢谢!

标签: elasticsearchelasticsearch-aggregation

解决方案


让我们假设您的License #字段的定义就像Biz Name 并且具有.keyword映射


现在,声明:

查找拥有... 3 个或更多许可证 #s 的企业

可以改写为:

在分桶的不同值的数量大于或等于 3business 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"
          }
        }
      }
    }
  }
}

仅此而已!


推荐阅读