首页 > 解决方案 > 对来自 elasticsearch 的分组结果进行分组

问题描述

我是弹性搜索的超级新手

我的 elasticsearch 上有很多产品。每个弹性搜索记录都有title, pid, product_group, color, size, qty...等,更多字段

现在,当我执行我的请求时,我希望它按 pid 对结果进行分组,然后在_group响应的部分中,我也希望将这些分组也按product_group.

所以换句话说,如果我有

pid: 1, product_group: 1, size: 1
pid: 1, product_group: 1, size: 2
pid: 1, product_group: 2, size: 1
pid: 1, product_group: 2, size: 2
pid: 2, product_group: 3, size: 1
pid: 2, product_group: 3, size: 2
pid: 2, product_group: 4, size: 1
pid: 2, product_group: 4, size: 2

我希望我的顶级搜索数组有 2 个结果:1 个用于 pid1,1 个用于 pid2,然后在每个结果中,在_groupjson 的部分内,我希望每个结果有 2 个:pid1 将有一个结果product_group 1 和 product_group 2,pid2 将具有 product_group 3 和 product_group 4 的 _group 结果。

这可能吗?

目前,这就是我修改查询以根据 pid 对其进行分组的方式:

group: {field: "pid", collapse: true}

我真的不知道我是否希望 collapse 是真还是假,而且我不知道如何,或者是否有可能,像我要求的那样进行第二层分组。将不胜感激任何帮助。

标签: elasticsearch

解决方案


最直接的方法是使用子termsaggs:

{
  "size": 0,
  "aggs": {
    "by_pid": {
      "terms": {
        "field": "pid"
      },
      "aggs": {
        "by_group": {
          "terms": {
            "field": "product_group"
          },
          "aggs": {
            "underlying_docs": {
              "top_hits": {}
            }
          }
        }
      }
    }
  }
}

请注意,最后一aggs组是可选的——我已经把它放在那里,以防你想知道哪些文档已经被分桶到哪个特定的乐队。


推荐阅读