我可以计算 Elasticsearch 中 _id 字段的基数吗?

Can I calculate the cardinality of the _id field in Elasticsearch?

我有多个 Elasticsearch 1.3.2 索引,并且我正在使用自定义文档 ID。我想在我的索引中找到不同 ID 的数量。有些文档具有相同的 ID 但在不同的索引中,因此这与仅计算文档不同。所以我想对 _id 字段进行基数聚合。所以我将其发布到 http://localhost:9200/*my_indices*/_search:

{ "from": 0, "size": 0, "aggregations": { "_count": { "cardinality": { "script": "doc['_id'].value", "lang": "groovy" } } } }

但是 Elasticsearch 刚刚发回了这个:

{ "took": 60, "timed_out": false, "_shards": { "total": 175, "successful": 175, "failed": 0 }, "hits": { "total": 310714, "max_score": 0, "hits": [] }, "aggregations": { "_count": { "value": 0 } } 

我很确定里面有 0 个以上的 ID!怎么回事,有没有可能得到我想要的?

_id 字段是 not analyzed and not stored, by default。而且我认为它也没有存储在 _source 中。您不能按原样将其与聚合一起使用。

对于您的索引,您需要更改它,以便将 _id 编入索引:

  "_id": {
    "index": "not_analyzed"
  }

还有另一种不需要重新索引所有内容的解决方案,即改用 _uid 字段:

{
  "from": 0,
  "size": 0,
  "aggregations": {
    "_count": {
      "cardinality": {
        "field": "_uid"
      }
    }
  }
}