仅对数组中的特定条目进行 Elasticsearch 聚合

Elasticsearch aggregation only on specific entries in an array

我是 Elasticsearch 的新手,不知道如何解决以下问题。 解释我的问题的最简单方法是给你看一个例子。

以下数组 "listing" 是我在 Elasticsearch 中所有文件的一部分,但条目各不相同,因此 "person" 和 "id" 42,可能占我的 50%文件。我想要做的是在我的 Elasticsearch 中的所有文件中获取所有 ID 为 42 的人的平均值 "ranking.position.standard"。

{
"listing": [
    {
        "person": {
            "id": 42
        },
        "ranking": {
            "position": {
                "standard": 2
            }
        }
    },
    {
        "person": {
            "id": 55
        },
        "ranking": {
            "position": {
                "standard": 7
            }
        }
    }
]
}

感谢您的帮助!

首先,您将列表存储为 object 还是 nested 数据类型?如果它是 object,我认为它不会起作用,所以请尝试以下示例:

PUT /test
{
  "mappings": {
    "_default_": {
      "properties": {
        "listing": {
          "type": "nested"
        }
      }
    }
  }
}

PUT /test/aa/1
{
  "listing": [
    {
      "person": {
        "id": 42
      },
      "ranking": {
        "position": {
          "standard": 2
        }
      }
    },
    {
      "person": {
        "id": 55
      },
      "ranking": {
        "position": {
          "standard": 7
        }
      }
    }
  ]
}

PUT /test/aa/2
{
  "listing": [
    {
      "person": {
        "id": 42
      },
      "ranking": {
        "position": {
          "standard": 5
        }
      }
    },
    {
      "person": {
        "id": 55
      },
      "ranking": {
        "position": {
          "standard": 6
        }
      }
    }
  ]
}  

GET test/_search
{
  "size": 0,
  "aggs": {
    "nest": {
      "nested": {
        "path": "listing"
      },
      "aggs": {
        "persons": {
          "terms": {
            "field": "listing.person.id",
            "size": 10
          },
          "aggs": {
            "avg_standard": {
              "avg": {
                "field": "listing.ranking.position.standard"
              }
            }
          }
        }
      }
    }
  }
}

这给我带来了以下结果:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "nest": {
      "doc_count": 4,
      "persons": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": 42,
            "doc_count": 2,
            "avg_standard": {
              "value": 3.5
            }
          },
          {
            "key": 55,
            "doc_count": 2,
            "avg_standard": {
              "value": 6.5
            }
          }
        ]
      }
    }
  }
}

看起来确实正确。