Search code examples
elasticsearchelasticsearch-7

Elasticsearch _count query request cache


Taken from docs: 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.

However how does this play with _count queries? _count queries behave almost exactly the same as _search queries with size=0?

I'd expect request cache to cache count queries as well, but couldn't find any information about it.


Solution

  • Whenever the documentation doesn't tell, go to the source ;-)

    In this case, if we look at the source of RestCountAction (i.e. the class handling the _count endpoint), we can see that what it actually does is creating a SearchRequest with size: 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
    

    Furthermore, when building the response we can see that the count value is actually the value of hits.total from the SearchResponse:

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

    So, from that, we can deduce that count queries are de facto cached as well.