hit

使用hit作为查询的计数是错误的。

当我们执行一个查询,比如下面的查询

GET /my-index-000001/_search
{
"query": {
"term": {
"user.id": "kimchy"
}
}
}

可能得到以下结果

{
"took": 5,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.3862942,
"hits": [
{
"_index": "my-index-000001",
"_type" : "_doc",
"_id": "0",
"_score": 1.3862942,
"_source": {
"@timestamp": "2099-11-15T14:12:12",
"http": {
"request": {
"method": "get"
},
"response": {
"status_code": 200,
"bytes": 1070000
},
"version": "1.1"
},
"source": {
"ip": "127.0.0.1"
},
"message": "GET /search HTTP/1.1 200 1070000",
"user": {
"id": "kimchy"
}
}
}
]
}
}

通过结果我们可以发现,如果按照​​hits->total->value​​​,可以拿到结果是​​1​​的个数数据,如果我们没有仔细查看文档,那么就会以为这个就是结果的个数,实际上不是的。


By default, you cannot page through more than 10,000 hits using the from and size parameters. To page through more hits, use the search_after parameter.
默认情况下,使用from和size参数不能翻阅超过10,000个匹配。 要翻阅更多匹配,请使用search_after参数。


也就是说


  • ​_search​​的搜索分页最多只能到一万条数据,如果需要修改就要调整其他参数
  • ​hits​​​最多返回​​10000​

如果根据条件查询的数据总数是超过一万条,那么这个查询就是不对的了。

_count

使用​​_count​​可以查询条件对应数据的总数,并且不会出现hit的一万条限制。

GET /my-index-000001/_count
{
"query" : {
"term" : { "user.id" : "kimchy" }
}
}

对应结果为

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

参考资料