Elasticsearch _count查询请求缓存

Elasticsearch _count query request cache

摘自文档:https://www.elastic.co/guide/en/elasticsearch/reference/7.9/shard-request-cache.html#shard-request-cache

By default, the requests cache will only cache the results of search requests where size=0, so it will not cache hits, but it will cache hits.total, aggregations, and suggestions.

Most queries that use now (see Date Math) cannot be cached.

Scripted queries that use the API calls which are non-deterministic, such as Math.random() or new Date() are not cached.

然而,这对 _count 查询有何影响? _count 查询的行为几乎与使用 size=0?

的 _search 查询完全相同

我希望请求缓存也能缓存计数查询,但找不到任何相关信息。

只要文档没有说明,请转到源代码;-)

在这种情况下,如果我们查看 RestCountAction 的来源(即 class 处理 _count 端点),我们可以看到它实际上所做的是创建一个SearchRequestsize: 0

    a search request
          |
          v
    SearchRequest countRequest = new SearchRequest(Strings.splitStringByCommaToArray(request.param("index")));
    countRequest.indicesOptions(IndicesOptions.fromRequest(request, countRequest.indicesOptions()));
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0).trackTotalHits(true);
                                                                          ^
                                                                          |
                                                                     with size 0

此外,当building the response时我们可以看到count的值实际上是SearchResponsehits.total的值:

    builder.field("count", response.getHits().getTotalHits().value);

因此,我们可以推断出计数查询实际上也被缓存了。