【问题标题】:ElasticSearch aggregate nested fields as part of parent documentElasticSearch 将嵌套字段聚合为父文档的一部分
【发布时间】:2016-01-07 13:03:19
【问题描述】:

我有Product 实体和嵌套Variation 实体的索引。 Product 实体由 IdTitle 和嵌套变体组成。 Variation 实体由 ColorSizePrice 字段组成。我需要通过ColorSizePrice 字段聚合搜索结果,以获取每种颜色、尺寸和价格组的产品数量。如果我对这些字段使用嵌套聚合,我会得到正确的数据,但存储桶中的文档数量是每个存储桶的 Variation 实体数。但我需要获取每个存储桶的 Product 实体(根文档)的数量。

例如,第一个产品有变体(红色,小,10 美元),(绿色,小,10 美元),(红色,中,11 美元),第二个产品有变体(绿色,中,15 美元)。嵌套聚合为 red 返回 2,为 small 返回 2,因为 2 个变体具有 red 颜色和 small 大小。但是我需要每个存储桶的产品(根实体)数量,red 应该是 1,small 应该是 1。

由于其他要求,我也不能使用子文档代替嵌套文档。

如何编写查询以获得此结果?

这是映射:

{
  "product": {
    "properties": {
      "id": {
        "type": "long"
      },
      "title": {
        "type": "string"
      },
      "brand": {
        "type": "string"
      },
      "variations": {
        "type": "nested",
        "properties": {
          "id": {
            "type": "long"
          },
          "colour": {
            "type": "string"
          },
          "size": {
            "type": "string"
          },
          "price": {
            "type": "double"
          }
        }
      },
      "location": {
        "type": "geo_point"
      }
    }
  }
}

这是一个查询

{
  "aggs": {
    "Variations": {
      "nested": {
        "path": "variations"
      },
      "aggs": {
        "Colous": {
          "terms": {
            "field": "variations.colour"
          }
        },
        "Sizes": {
          "terms": {
            "field": "variations.size"
          }
        }
      }
    },
    "Brands": {
      "terms": {
        "field": "brand"
      }
    }
  },
  "query": {
    "match_all": {}
  }
}

Brand 聚合运行良好,因为它获取每个组的根文档数,但嵌套聚合返回嵌套文档数而不是根文档数。

【问题讨论】:

  • 您能否在您的问题中包含您的映射以及您正在尝试的查询?这将帮助人们重现问题并找到解决方案。
  • 当然。添加了映射和查询。

标签: elasticsearch aggregation


【解决方案1】:

您以正确的方式解决了问题。现在您可以简单地使用reverse_nested aggregation 来“加入”到根产品,并为您的变体获取每个匹配产品的数量。

{
  "aggs": {
    "Variations": {
      "nested": {
        "path": "variations"
      },
      "aggs": {
        "Colous": {
          "terms": {
            "field": "variations.colour"
          },
          "aggs": {
            "product_count": {            <--- add this reverse nested agg
              "reverse_nested": {}
            }
          }
        },
        "Sizes": {
          "terms": {
            "field": "variations.size"
          },
          "aggs": {
            "product_count": {            <--- add this reverse nested agg
              "reverse_nested": {}
            }
          }
        }
      }
    },
    "Brands": {
      "terms": {
        "field": "brand"
      }
    }
  },
  "query": {
    "match_all": {}
  }
}

在响应中,您会看到:

  • 有2个产品匹配colour: green
  • 1 个产品匹配colour: red
  • 有2个产品匹配size: medium
  • 1 个产品匹配size: small

【讨论】:

    猜你喜欢
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2023-04-03
    • 2018-07-14
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多