【问题标题】:Getting first entry of each unique combination of fields from elasticsearch从弹性搜索中获取每个唯一字段组合的第一个条目
【发布时间】:2020-10-21 07:58:58
【问题描述】:

我有一个弹性搜索数据库,我上传这样的条目:

{"s_food": "bread", "s_store": "Safeway", "s_date" : "2020-06-30", "l_run" : 28900, "l_covered": 1}

当我将它上传到 elasticsearch 时,它会添加一个 _id_type@timestamp_index 字段。所以条目看起来像这样:

{"s_food": "bread", "s_store": "Safeway", "s_date" : "2020-06-30", "l_run" : 28900, "l_covered": 1, "_type": "_doc", "_index": "my_index", "_id": pe39u5hs874kee}

我使用 elasticsearch 数据库的方式导致相同的原始条目被多次上传。在此示例中,我只关心 s_foods_datel_run 字段是唯一的组合。由于我有这么多条目,我想使用 elasticsearch 滚动工具来浏览所有匹配项。到目前为止,在弹性搜索中,我只看到人们使用聚合来获取每个术语的存储桶,然后他们遍历每个分区。我想使用聚合之类的东西来为我关心的三个字段(食物、日期、跑步)的每个独特组合获取整个条目(只有 1 个)。现在我用这样的滚动聚合:

GET /my-index/_search?scroll=25m
{
 size: 10000,
 aggs: {
  foods: {
   terms: {
    field: s_food
   },
    aggs: {
      dates: {
        terms: {
          field: s_date
        },
        aggs: {
          runs: {
            terms: {
              field: l_run
            }
          }
        }
      }
    }
  }
}

不幸的是,这只是给了我我不想要的通常的分桶结构。还有什么我应该尝试的吗?

【问题讨论】:

    标签: python elasticsearch aggregation


    【解决方案1】:

    您只需要使用带有size: 1 的热门聚合。阅读更多关于热门聚合here

    查询将如下所示:

    {
      "size": 10000,
      "aggs": {
        "foods": {
          "terms": {
            "field": "s_food"
          },
          "aggs": {
            "dates": {
              "terms": {
                "field": "s_date"
              },
              "aggs": {
                "runs": {
                  "terms": {
                    "field": "l_run"
                  },
                  "aggs": {
                    "topOne": {
                      "top_hits": {
                        "size": 1
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    

    【讨论】:

    • 谢谢!这适用于滚动功能吗?我需要获得超过 10,000 个条目,这对聚合造成了问题。
    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多