【问题标题】:Filtering aggregation results过滤聚合结果
【发布时间】:2020-10-07 13:36:20
【问题描述】:

这个问题是this question 的子问题。作为一个单独的问题发布以引起注意。

示例文档:

{
  "id":1,
  "product":"p1",
  "cat_ids":[1,2,3]
}
{
  "id":2,
  "product":"p2",
  "cat_ids":[3,4,5]
}
{
  "id":3,
  "product":"p3",
  "cat_ids":[4,5,6]
}

询问:获取属于特定类别的产品。例如 cat_id = 3

查询:

GET product/_search 
{
 "size": 0,
 "aggs": {
   "cats": {
     "terms": {
       "field": "cats",
       "size": 10
     },"aggs": {
       "products": {
         "terms": {
           "field": "name.keyword",
           "size": 10
         }
       }
     }
   }
 }
}

问题:

  1. 如何在此处过滤 cat_id = 3 的聚合结果。我也尝试了 bucket_selector,但它不起作用。

    注意:由于 cat_ids 过滤的多值,然后聚合不起作用

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    您可以filter values,根据将创建的存储桶。

    可以过滤将为其创建存储桶的值。 这可以使用 include 和 exclude 参数来完成,这些参数是 基于正则表达式字符串或精确值的数组。 此外,include 子句可以使用分区表达式进行过滤。

    添加一个包含索引数据、搜索查询和搜索结果的工作示例

    索引数据:

    {
      "id":1,
      "product":"p1",
      "cat_ids":[1,2,3]
    }
    {
      "id":2,
      "product":"p2",
      "cat_ids":[3,4,5]
    }
    {
      "id":3,
      "product":"p3",
      "cat_ids":[4,5,6]
    }
    

    搜索查询:

    {
      "size": 0,
      "aggs": {
        "cats": {
          "terms": {
            "field": "cat_ids",
            "include": [                   <-- note this
              3
            ]
          },
          "aggs": {
            "products": {
              "terms": {
                "field": "product.keyword",
                "size": 10
              }
            }
          }
        }
      }
    }
    

    搜索结果:

    "aggregations": {
        "cats": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": 3,
              "doc_count": 2,
              "products": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                  {
                    "key": "p1",
                    "doc_count": 1
                  },
                  {
                    "key": "p2",
                    "doc_count": 1
                  }
                ]
              }
            }
          ]
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-19
      • 2015-10-06
      • 2020-09-05
      • 2016-10-02
      • 2021-02-24
      • 1970-01-01
      • 2022-01-17
      • 2019-06-19
      相关资源
      最近更新 更多