ES使用RestHighLevelClient查询总记录数

一个首页看板需求,需要呈现当前的日志总数。


日志总数.png

日志存在ES里,构造一个query,用CountRequest去查总条数。

核心代码如下:

/**
 * ES Controller
 */
@RestController
@RequestMapping(value = "/elastic")
public class ElasticController extends BaseController {
    @Autowired
    private ElasticService es;

    @RequestMapping(value = "/count" , method = RequestMethod.POST)
    public AjaxJson count(@RequestBody QueryVo queryVo){
        return AjaxJson.success().put("count", es.getRecordCount(queryVo));
    }
}
/**
 * ES QueryVo
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class QueryVo {

    /**
     * 索引名
     */
    private String idxName;
    /**
     * 需要反射的实体类型,用于对查询结果的封装
     */
    private String className;
    /**
     * 具体条件
     */
    private Map> query;
}
/**
 * ES Service
 */
@Slf4j
@Component
public class ElasticService extends BaseElasticService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    public long getRecordCount(@RequestBody QueryVo queryVo) {
        try {
            Map params = queryVo.getQuery().get("term");
            Set keys = params.keySet();
            TermQueryBuilder queryBuilders = null;
            for(String ke : keys){
                queryBuilders = QueryBuilders.termQuery(ke, params.get(ke));
            }
            if(null != queryBuilders){
                // 通过CountRequest查询获得count
                CountRequest countRequest = new CountRequest();
                // 绑定索引名
                countRequest.indices(queryVo.getIdxName());
                countRequest.query(queryBuilders);
                try {
                    CountResponse response = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
                    return response.getCount();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}

测试数据:

POST /v1/elastic/count
{
  "idxName": "*",
  "query": {
    "term" : { "_type" : "_doc" }
  }
}

你可能感兴趣的:(ES使用RestHighLevelClient查询总记录数)