如何将父字段值与 Elasticsearch 中嵌套对象的聚合值进行比较?

How to compare parent field value with aggregated values from nested objects in Elasticsearch?

我的索引中有这样的文档:

  {
    "Pieces": 5,
    "parts": [
      {
        "Quantity": 1,
        "PartID": 1,
      },
      {
        "Quantity": 1,
        "PartID": 2
      },
      {
        "Quantity": 1,
        "PartID": 3
      },
      {
        "Quantity": 1,
        "PartID": 4
      }
    ]
  }

我想准备一个查询,列出所有 Pieces 值不等于所有 partsQuantity 的总和的文档。我有这样的东西:

GET /_search
{
  "size": 0,
  "aggs": {
    "group_by_id": {
      "terms": {
        "field": "_id",
        "size": 1000000000
      },
      "aggs": {
        "sum_of_parts": {
          "nested": {
            "path": "parts"
          },
          "aggs": {
            "sum_of_quantity": {
              "sum": {
                "field": "parts.Quantity"
              }
            }
          }
        },
        "sum_of_parts_vs_pieces": {
          "bucket_selector": {
            "buckets_path": {
              "sumOfPart": "sum_of_parts>sum_of_quantity"
            },
            "script": "params.sumOfPart != HOW_TO_PUT_Pieces_VALUE_HERE???"
          }
        }
      }
    }
  }
}

这几乎可以工作(计算所有部分的 Quantity 的总和)......但是......我不知道如何将 Pieces 值传递给 bucket_selector

你知道怎么做吗?或者您可能知道如何以其他方式完成此任务?

你可以这样做,通过添加 Pieces 字段的平均值(使用 reverse_nested 返回一级):

GET pieces/_search
{
  "size": 0,
  "aggs": {
    "group_by_id": {
      "terms": {
        "field": "_id",
        "size": 1000000000
      },
      "aggs": {
        "sum_of_parts": {
          "nested": {
            "path": "parts"
          },
          "aggs": {
            "avg_of_pieces": {
              "reverse_nested": {},
              "aggs": {
                "avg_of_pieces": {
                  "avg": {
                    "field": "Pieces"
                  }
                }
              }
            },
            "sum_of_quantity": {
              "sum": {
                "field": "parts.Quantity"
              }
            }
          }
        },
        "sum_of_parts_vs_pieces": {
          "bucket_selector": {
            "buckets_path": {
              "sumOfPart": "sum_of_parts>sum_of_quantity",
              "nbPieces": "sum_of_parts>avg_of_pieces>avg_of_pieces"
            },
            "script": "params.sumOfPart != params.nbPieces"
          }
        }
      }
    }
  }
}