2

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

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

我想准备查询,其中列出了Piecesvalue 不等于 in all 的总和的Quantity所有文档parts。我有类似的东西:

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.

你知道怎么做吗?或者,也许您知道如何以另一种方式完成这项任务?

4

1 回答 1

3

您可以这样做,通过添加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"
          }
        }
      }
    }
  }
}
于 2019-03-16T11:16:05.360 回答