co.elastic.clients 查询 Query 的组装

依赖引入

<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>7.17.11</version>
</dependency>

查询语句

List<Query> queryList = new ArrayList<>();
// 填充 Query
SearchRequest.Builder searchBuilder = new SearchRequest.Builder();
searchBuilder.index(indexName);
searchBuilder.size(10000);
searchBuilder.query(q -> q.bool(b -> b.filter(queryList)));
SearchRequest searchRequest = searchBuilder.build();
log.info("[indexName]{}[query]{}", indexName, searchRequest.toString());
SearchResponse<Information> employee = elasticsearchClient.search(searchRequest, Information.class);

Query 查询

时间查询

最近两小时:

Query timeQuery = Query.of(q1 -> q1.bool(b -> b
        .filter(f -> f.range(r2 -> r2.field("uploadtime").gte(JsonData.of(OffsetDateTime.now(ZoneId.of("Asia/Shanghai")).minusHours(2).toString()))))));

字段包含

不包含某字段

Query folderQuery = Query.of(q3 -> q3.bool(b -> b.mustNot(m -> m.exists(e -> e.field("folder")))));

包含某字段

字段相等匹配

Query query = Query.of(f -> f.term(m -> m.field("feedbackResult.keyword").value(FieldValue.of("verifySuccess"))));

复杂嵌套查询

嵌套字段包含某个 key

Query boolQuery = Query.of(q2 -> q2.bool(b -> b
        .filter(f -> f.term(t -> t.field("properties.key.keyword").value("head")))
));
Query nestedQuery = Query.of(q -> q.nested(NestedQuery.of(n -> n.path("properties").query(boolQuery))));

嵌套字段不包含某个 key

Query boolQuery = Query.of(q2 -> q2.bool(b -> b
                    .filter(f -> f.term(t -> t.field("properties.key").value("mailInfoEsId")))
            ));
Query nestedQuery = Query.of(q1 -> q1.bool(b -> b.mustNot(q -> q.nested(NestedQuery.of(n -> n.path("properties").query(boolQuery))))));

嵌套字段某个 key 与 值匹配

Query boolQuery = Query.of(q2 -> q2.bool(b -> b
        .filter(f -> f.term(t -> t.field("properties.key.keyword").value("searchkey")))
        .filter(f -> f.matchPhrase(m -> m.field("properties.value").query("searchvalue")))
));
Query nestedQuery = Query.of(q -> q.nested(NestedQuery.of(n -> n.path("properties").query(boolQuery))));

多值匹配

List<Query> should = new ArrayList<>();
FeedbackConstants.FEEDBACKTYPE_MAILIN.forEach(feedbackType ->
should.add(TermQuery.of(m -> m.field("feedbackType").value(feedbackType))._toQuery()));
Query boolQuery = Query.of(q1 -> q1.bool(sb -> sb.should(should)));