1

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

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

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 中提供答案,那就太好了。

4

1 回答 1

2

您可以简单地在字段上使用terms聚合tags和另一个嵌套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, ...
于 2016-01-05T19:24:51.683 回答