如何获取 ElasticSearch 中每种映射类型的文档(记录)计数?

Inf*_*ogy 5 aggregate count command-line-interface elasticsearch

我有一个名为“myindex”的 ElasticSearch 索引,我将三种不同映射类型(人员、事件和供应商)的文档加载到其中...

curl -XPOST localhost:9200/myindex/person/_bulk --data-binary  @../JSON_DATA/persons.json
curl -XPOST localhost:9200/myindex/event/_bulk --data-binary  @../JSON_DATA/events.json
curl -XPOST localhost:9200/myindex/vendor/_bulk --data-binary  @../JSON_DATA/vendors.json
Run Code Online (Sandbox Code Playgroud)

使用以下命令可以看到索引创建成功:

curl 'localhost:9200/_cat/indices?v'
Run Code Online (Sandbox Code Playgroud)

我可以使用以下命令成功列出所有映射类型:

curl -s -XGET 'http://localhost:9200/myindex/_mapping/?pretty'
Run Code Online (Sandbox Code Playgroud)

我的问题 - A 部分:如何获取显式命名索引(“myindex”)中每种映射类型的文档聚合/总数?换句话说,我想知道每种映射类型的文档数量。

注意:我尝试过curl -s -XGET 'http://localhost:9200/myindex/_count/?pretty',但它只返回所有映射类型的总计数,而不是每种映射类型的总计数。换句话说,它并没有细分县城海滩测绘类型。

我的问题 - B 部分:鉴于能够获取每种映射类型的文档聚合/总数,如何获取存储在显式命名索引(“myindex”)中的任何一种特定映射类型的聚合计数?换句话说,我想知道索引“myindex”下一种显式命名的映射类型(例如“事件”)的文档数量。

Yei*_*kel 5

您使用什么版本的 Elastic 搜索?

在 2.x 下,您的查询应该同样正常工作,您需要添加的只是查询中的文档类型,以便您可以获得每种类型的特定计数。

例如,看一下这个完整的示例:

DELETE testindex
PUT testindex
PUT testindex/_mapping/users
{
  "properties": {
    "name": {
      "type": "string",
      "analyzer": "standard"
    }
  }
}

PUT testindex/_mapping/users2
{
  "properties": {
    "name": {
      "type": "string",
      "analyzer": "standard"
    }
  }
}

PUT testindex/users/1
{
  "name" : "Albert"
}

PUT testindex/user2/1
{
  "name" : "Albert"
}

GET testindex/_count 

{
  "count": 2,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  }
}

GET testindex/users/_count 

{
  "count": 1,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  }
}



GET testindex/users2/_count 

{
  "count": 1,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑

为了根据 @IanGabes 评论和 B 部分的回答更正我的评论,您可以通过以下方式获取每个映射的计数:

GET /testindex/_search
{
  "size": 0, 
  "aggs": {
    "countPerMapping": {
      "terms": {
        "field": "_type"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,大小 0是为了避免在查询中显示结果,而仅关注聚合。其中每个存储桶的键是映射的名称,doc_count 是文档的数量。

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "countPerMapping": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "user2",
          "doc_count": 1
        },
        {
          "key": "users",
          "doc_count": 1
        }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

或者使用卷曲

curl -XGET "http://localhost:9200/testindex/_search" -d'
{
  "size": 0, 
  "aggs": {
    "countPerMapping": {
      "terms": {
        "field": "_type"
      }
    }
  }
}'
Run Code Online (Sandbox Code Playgroud)