首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何基于子桶聚合文档计数过滤桶聚合结果?

如何基于子桶聚合文档计数过滤桶聚合结果?
EN

Stack Overflow用户
提问于 2022-08-13 16:52:22
回答 1查看 123关注 0票数 2

我需要一个查询,如果结果至少有一个文档,并将userId设置为“排除”列表中的值,即TAG ATAG B,则结果将排除任何will文档。

我有一个数据索引,如下所示:

代码语言:javascript
复制
{
  "_index": "tags-3",
  "_type": "_doc",
  "_id": "YYYYYYY",
  "_score": 10.272416,
  "_source": {
    "id": "YYYYYYY",
    "userId": "User1",
    "tag": "TAG A"
  }
},
{
  "_index": "tags-3",
  "_type": "_doc",
  "_id": "ZZZZZZ",
  "_score": 10.272416,
  "_source": {
    "id": "ZZZZZZ",
    "userId": "User1",
    "tag": "TAG B"
  },
{
  "_index": "tags-3",
  "_type": "_doc",
  "_id": "ZZZZZZ",
  "_score": 10.272416,
  "_source": {
    "id": "ZZZZZZ",
    "userId": "User2",
    "tag": "TAG A"
},
{
  "_index": "tags-3",
  "_type": "_doc",
  "_id": "ZZZZZZ",
  "_score": 10.272416,
  "_source": {
    "id": "ZZZZZZ",
    "userId": "User2",
    "tag": "TAG D"
},
{
  "_index": "tags-3",
  "_type": "_doc",
  "_id": "ZZZZZZ",
  "_score": 10.272416,
  "_source": {
    "id": "ZZZZZZ",
    "userId": "User4",
    "tag": "TAG D"
}

对于上面的输入,我希望输出如下:

代码语言:javascript
复制
{
  "_index": "tags-3",
  "_type": "_doc",
  "_id": "ZZZZZZ",
  "_source": {
    "userId": "User4"
  }

因为User4没有将tag设置为TAG ATAG B的文档。

User4是唯一一个将标记设置为TAG D的文档的其他用户,但是由于它有另一个带有TAG B的文档,所以它被排除在外。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-13 19:28:33

这样做的一种方法是:

用户ID上的

  1. 聚合(组)--这将为您提供所有用户ID(
  2. ),然后,使用要排除的多个(或单个)标记值的筛选器来聚合每个用户ID(嵌套聚合)的文档,这将为您提供文档的总总和,该标记设置为每个用户ID
  3. 的排除标记。最后,执行桶选择器聚合,只包括对任何排除的文档计数为0的用户ID;这将使没有任何文档的文档具有任何排除的标记值(

)。

对于A、B&C的排除标记列表,此查询应该有效:

代码语言:javascript
复制
{
  "aggs": {
    "user-ids": {
      "terms": {
        "field": "userId.keyword",
        "size": 10000
      },
      "aggs": {
        "excluded_tags_agg": {
          "filter": {
            "bool": {
              "should": [
                {
                  "match_phrase": {
                    "tag.keyword": "TAG A"
                  }
                },
                {
                  "match_phrase": {
                    "tag.keyword": "TAG B"
                  }
                },
                {
                  "match_phrase": {
                    "tag.keyword": "TAG C"
                  }
                }
              ],
              "minimum_should_match": 1
            }
          }
        },
        "filter_userids_which_do_not_have_any_docs_with_excluded_tags": {
          "bucket_selector": {
            "buckets_path": {
              "doc_count": "excluded_tags_agg > _count"
            },
            "script": "params.doc_count == 0"
          }
        }
      }
    }
  },
  "size": 0
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73346125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档