我想使用SearchHits.getTotalHits()来获取匹配请求的文档总数。但是,我发现SearchHits.getTotalHits()获得的值不等于SearchHits.getHits().length的总和。正常吗

SearchHits searchHits = response.getHits();
int total = (int)searchHits.getTotalHits();
int k = 0;
do {
    for (SearchHit hit : searchHits.getHits()) {
        k++;
    }
    response = esClient.prepareSearchScroll(response.getScrollId())
            .setScroll(scrollKeepAliveTime)
            .get();
} while (response.getHits().getHits().length != 0);
Assert.assertEquals(total, k);

  • 输出
  • java.lang.AssertionError: expected:<515> but was:<600>
    

    最佳答案

    一个问题是您总是迭代searchHits,即第一个查询的结果。

    您需要在每个滚动请求之后将searchHits重新分配给response.getHits(),如下所示:

    SearchHits searchHits = response.getHits();
    int total = (int)searchHits.getTotalHits();
    int k = 0;
    do {
        for (SearchHit hit : searchHits.getHits()) {
            k++;
        }
        response = esClient.prepareSearchScroll(response.getScrollId())
                .setScroll(scrollKeepAliveTime)
                .get();
        searchHits = response.getHits();               <-- add this line
    } while (searchHits.getHits().length != 0);        <-- modify this line
    Assert.assertEquals(total, k);
    

    07-24 13:14