首页 > 解决方案 > Elasticsearch 中唯一值的输出列表

问题描述

我的 Elasticsearch 索引在 25 个不同的组中发布了近 700.000 条社交媒体消息。每条消息都是一个 JSON 并包含 chat.id 键。

我需要构建一个查询以在我的 Python 脚本中使用,以便仅打印一次 chat.id 值。

简单地说,我的脚本应该输出我数据库中的组。如果我参加 25 个小组,我希望看到 25 个 chat.id 被打印出来。

目前,我通过阅读每条社交媒体消息并提取每条消息的 chat.id 值来获取列表。但随着索引帖子数量的增加,它会变得更长、更耗时,并且对 CPU 的要求也更高。

我找不到如何构建查询以同时实现此结果。

我的文档的结构是这样的:

    {
      "_index": "indexname",
      "_type": "_doc",
      "_source": {
        "id": 372353,
        "audio": {},
        "author_signature": null,
        "caption": null,
        "channel_chat_created": null,
        "chat": {
           "id": 1011449296138,
           "type": "supergroup",
           "username": null,
          "first_name": null,
          "title": "chatname"

到目前为止,我使用的查询是这样的:

    query= {
      "aggs": {
        "chatids": {
          "terms": {
            "field": "chat.id"
          }
        }
     }
    }

标签: pythonelasticsearch

解决方案


您可以使用术语聚合来获取不同的值。例如:

GET messages/_search
{
 "size":"0",
 "aggs" : {
  "group_ids" : {
   "terms" : { "field" : "group_id", "size" : 1000 }
   }
  }
}

推荐阅读