嵌套聚合elasticsearch,具有用于子聚合的访问父字段

Kri*_*thi 2 elasticsearch

我有以下映射

PUT prod_nested
{
  "mappings": {
    "default": {
      "properties": {
        "pkey": {
          "type": "keyword"
        },
        "original_price": {
          "type": "float"
        },
        "tags": {
          "type": "nested",
          "properties": {
            "category": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 30
                }
              }
            },
            "attribute": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 30
                }
              }
            },
            "original_price": {
              "type": "float"
            }
          }
        }
      }
    }
  } 
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试做类似以下 sql 聚合的事情

select tag_attribute,
       tag_category,
       avg(original_price)
FROM products
GROUP BY tag_category, tag_attribute
Run Code Online (Sandbox Code Playgroud)

我可以使用标签上的嵌套聚合来执行分组部分,但它无法访问子聚合中的original_price。一种选择可能是在标签嵌套文档中复制original_price,但我有数百万条记录需要处理。我当前的聚合是

GET prod_nested/_search?size=0
{
    "aggs": {
        "tags": {
          "nested": {
            "path": "tags"
          },
          "aggs": {
            "categories": {
              "terms": {
                "field": "tags.category.keyword",
                "size": 30
              },
              "aggs": {
                "attributes": {
                  "terms": {
                    "field": "tags.attribute.keyword",
                    "size": 30
                  },
                  "aggs": {
                    "price": {
                      "avg": {
                        "field": "original_price"
                      }
                    }
                  }
                }

              }
            }
          }
        }
      }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Kri*_*thi 5

我能够通过使用反向嵌套聚合获得所需的结果。

GET prod_nested/_search?size=0
{
  "aggs": {
    "tags": {
      "nested": {
        "path": "tags"
      },
      "aggs": {
        "categories": {
          "terms": {
            "field": "tags.category.keyword",
            "size": 10
          },
          "aggs": {
            "attributes": {
              "terms": {
                "field": "tags.attribute.keyword",
                "size": 10
              },
              "aggs": {
                "parent_doc_price": {
                  "reverse_nested": {},
                  "aggs": {
                    "avg_price": {
                      "avg": {
                        "field": "original_price"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)