query,根据查询条件,去计算文档的匹配度得到一个分数,并且根据分数进行排序,不会做缓存。【精准匹配度高】
filter,根据查询条件去查询文档,不去计算分数,而且filter会对经常被过滤的数据进行缓存。【查询效率会高】
# filter 查询 POST /sms-logs-index/_search { "query": { "bool": { "filter": [ { "term": { "corpName": "阿里3" } }, { "range": { "fee": { "gte": 20 } } } ] } } }
Java
@Test void filterQuery() throws Exception { String indexName = "sms-logs-index"; RestHighLevelClient client = ESClient.getClient(); //1. 创建SearchRequest对象 SearchRequest request = new SearchRequest(indexName); //2. 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.filter(QueryBuilders.termQuery("corpName","阿里3")); boolQuery.filter(QueryBuilders.rangeQuery("fee").gte(20)); builder.query(boolQuery); request.source(builder); //3. 执行查询 SearchResponse resp = client.search(request, RequestOptions.DEFAULT); //4. 输出返回值 for (SearchHit hit : resp.getHits().getHits()) { System.out.println(hit.getSourceAsMap()); } }