【问题标题】:How to do bucket aggregation on multi value field in elasticsearch如何在elasticsearch中对多值字段进行桶聚合
【发布时间】:2016-01-05 19:13:38
【问题描述】:

假设我的弹性搜索索引中的每个文档都是一篇博客文章,它只包含两个字段,标题和标签。 title 字段只是一个字符串,而 tags 是一个多值字段。

如果我有三个这样的文件:

title      tags
"blog1"    [A,B,C]
"blog2"    [A,B]
"blog3"    [B,C]

我想按所有可能标签的唯一值进行存储,但我怎样才能得到如下结果,其中包含一个存储桶中的三个项目。或者有什么有效的替代方案?

{A: ["blog1", "blog2"]}
{B: ["blog1", "blog2", "blog3"]}
{C: ["blog1", "blog3"]}

如果有人可以在 elasticsearch python API 中提供答案,那就太好了。

【问题讨论】:

    标签: elasticsearch pyelasticsearch elasticsearch-dsl


    【解决方案1】:

    您可以简单地在 tags 字段上使用 terms 聚合和另一个嵌套的 top_hits 子聚合。通过以下查询,您将获得预期的结果。

    {
        "size": 0,
        "aggs": {
            "tags": {
                "terms": { 
                    "field": "tags" 
                },
                "aggs": {
                    "top_titles": {
                        "top_hits": {
                            "_source": ["title"]
                        }
                    }
                }
            }
        }
    }
    

    在 Python 中使用它很简单:

    from elasticsearch import Elasticsearch
    client = Elasticsearch()
    
    response = client.search(
        index="my-index",
        body= {
        "size": 0,
        "aggs": {
            "tags": {
                "terms": { 
                    "field": "tags" 
                },
                "aggs": {
                    "top_titles": {
                        "top_hits": {
                            "_source": ["title"]
                        }
                    }
                }
            }
        }
    }
    )
    
    # parse the tags
    for tag in response['aggregations']['tags']['buckets']:
        tag = tag['key'] # => A, B, C
        # parse the titles for the tag
        for hit in tag['top_titles']['hits']['hits']:
           title = hit['_source']['title'] # => blog1, blog2, ...
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2019-02-18
      • 1970-01-01
      • 2016-03-15
      • 2016-09-08
      • 2022-01-04
      • 2020-02-18
      • 1970-01-01
      • 2018-06-01
      相关资源
      最近更新 更多