Elasticsearch 基础教程

Elasticsearch 高级教程

Elasticsearch 插件

Elasticsearch 笔记

es(elasticsearch)count 查询 api 及 ElasticsearchTemplate 条数接口使用

Elasticsearch 笔记 Elasticsearch 笔记


es 除了获取匹配的文档具体信息外,也可以只获取匹配的文档条数(count),对此 elasticsearch 提供了单独的 count 接口,count 查询 api 指定的操作以 _count 收尾。

_count 示例

下面通过 kibana 给出示例:

GET qa/_count
{
  "query": {
    "multi_match": {
      "query": "elasticsearch",
      "fields": ["question","answer"]
    }
  }
}

返回数据结果如下:

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

ElasticsearchTemplate _count

如果项目中,使用 java spring-data-elasticsearch 的 ElasticsearchTemplate 操作 es,可以进行如下操作:

String[] count_match_field = new String[]{"question", "answer"};

MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders
        .multiMatchQuery(keyword, count_match_field)
        .minimumShouldMatch("100%");

SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withIndices(INDEX)
        .withQuery(multiMatchQueryBuilder)
        .build();

try {
    long count = elasticsearchTemplate.count(searchQuery);
    searchContext.getCommonSearchResultDTOWrapper().setTotal((int) count);
} catch (Throwable throwable) {
    log.error("qa count es error", throwable);
}