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
  }
}

参考资料

  • https://www.elastic.co/guide/en/elasticsearch/reference/7.11/search-search.html
  • https://www.elastic.co/guide/en/elasticsearch/reference/7.11/search-count.html
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐