SpringBoot中进行elasticSearch查询,使用QueryBuilders构建各类条件查询

2023-07-21 19:17:18 浏览数 (1)

查询所有

代码语言:javascript复制
//搜索全部文档
QueryBuilder queryBuilder =
QueryBuilders.matchAllQuery();

查询单个,等于/eq

代码语言:javascript复制
//单个匹配,搜索name为li的文档
QueryBuilder queryBuilder =
QueryBuilders.matchQuery("name", "li");

查询多个字段匹配某一个值

代码语言:javascript复制
//搜索name中或nickname中包含有li的文档(必须与li一致)
QueryBuilder queryBuilder =
QueryBuilders.multiMatchQuery("li","name", "nickname");

模糊匹配

代码语言:javascript复制
//搜索名字中含有li文档(name中只要包含li即可)
WildcardQueryBuilder queryBuilder =
QueryBuilders.wildcardQuery("name","*li*");

BoolQueryBuilder复合查询

BoolQueryBuilder对象使用must方法build,多个and使用多个must

代码语言:javascript复制
WildcardQueryBuilder queryBuilder1 = QueryBuilders.matchQuery("name", "li");
WildcardQueryBuilder queryBuilder2 = QueryBuilders.matchQuery("id", "1");

BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//查询名字是LI和id是1的所有数据
boolQueryBuilder.must(queryBuilder1);
boolQueryBuilder.must(queryBuilder2);

BoolQueryBuilder对象使用should方法build,多个or使用多个should使用

代码语言:javascript复制
WildcardQueryBuilder queryBuilder1 = QueryBuilders.matchQuery("name", "li");
WildcardQueryBuilder queryBuilder2 = QueryBuilders.matchQuery("id", "1");

BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//查询名字是LI或id是1的所有数据
boolQueryBuilder.should(queryBuilder1);
boolQueryBuilder.should(queryBuilder2);
代码语言:javascript复制
must:必须满足的条件

should:非必须满足的条件

minimumShouldMatch(1):至少要满足一个 should 条件

等值查询

代码语言:javascript复制
BoolQueryBuilder queryBuilder =
QueryBuilders.boolQuery().must(QueryBuilders.termQuery("name", "小李"));

范围查询

代码语言:javascript复制
BoolQueryBuilder queryBuilder =
QueryBuilders.rangeQuery("age").gte(18).lte(50);

判空查询

代码语言:javascript复制
BoolQueryBuilder queryBuilder =
QueryBuilders.boolQuery()
.must(QueryBuilders.existsQuery("name"))
.mustNot(QueryBuilders.existsQuery("tag"));
//查询name有值,tag不存在值

分页查询

代码语言:javascript复制
SearchResponse response =
this.transportClient
.prepareSearch(index)
.setTypes(type)
.setQuery(queryBuilder)
.setFrom(offset)
.setSize(rows)
.setExplain(false)
.execute()
.actionGet();

本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。

首发链接:https://cloud.tencent.com/developer/article/2304044

0 人点赞