es 版本:7.10.1
spring-cloud版本:2.3.5.RELEASE
spring-boot-starter-data-elasticsearch 版本 2.3.12.RELEASE
spring-data-elasticsearch 版本 4.0.9.RELEASE
es查询,需求:title或者content任意一个字段能匹配到关键词即可
DSL
使用dsl查询语句如下,构建一个query ,should只要一个匹配即可
POST /article/_search
{
"query":{
"bool": {
"should": [
{"wildcard": {"title": "*路数*"}},
{"wildcard": {"content": "*路数*"}}
]
}
}
}
运行结果,可以查出数据
文章来源:https://www.toymoban.com/news/detail-506897.html
java api
翻译成java实现,首先使用的是restHighLevelClient文章来源地址https://www.toymoban.com/news/detail-506897.html
restHighLevelClient版
@Override
public <T> List<T> boolQuery(String indexName, String queryField,String queryValue, Class<T> beanClass) {
// 查询的数据列表
List<T> list = new ArrayList<>();
try {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
if (beanClass == Article.class && "title".equals(queryField) ) {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.should(new WildcardQueryBuilder("title", "*" + queryValue + "*"));
boolQueryBuilder.should(new WildcardQueryBuilder("content", "*" + queryValue + "*"));
searchSourceBuilder.query(boolQueryBuilder);
}else {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
WildcardQueryBuilder field = QueryBuilders.wildcardQuery(queryField, "*" +queryValue+ "*" );
boolQueryBuilder.should(field);
searchSourceBuilder.query(boolQueryBuilder);
}
searchSourceBuilder.size(100);
// 创建查询请求对象,将查询对象配置到其中
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.source(searchSourceBuilder);
// 执行查询,然后处理响应结果
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 根据状态和数据条数验证是否返回了数据
if (RestStatus.OK.equals(searchResponse.status()) && searchResponse.getHits().getTotalHits().value > 0) {
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
// 将 JSON 转换成对象
T bean = JSON.parseObject(hit.getSourceAsString(), beanClass);
list.add(bean);
}
}
} catch (Exception e) {
}
return list;
}
elasticsearchRestTemplate版
@GetMapping("list/like")
@SysOpLogAnnotation(content = "模糊匹配查询列表", operation = "list-like")
public ApiResult queryByManyFieldLike(String queryField, String queryValue) {
// 查询的数据列表
List<Article> list = new ArrayList<Article>();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.should(new WildcardQueryBuilder("title", "*" + queryValue + "*"));
boolQueryBuilder.should(new WildcardQueryBuilder("content", "*" + queryValue + "*"));
NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
SearchHits<Article> search = elasticsearchRestTemplate.search(query, Article.class);
List<SearchHit<Article>> searchHits = search.getSearchHits();
for (SearchHit searchHit : searchHits) {
list.add((Article) searchHit.getContent());
}
return new ApiResult().success(list);
}
到了这里,关于es多字段模糊匹配wildcardQuery,java实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!