where ((title like '%上海%' || content like '%上海%') and type like '%1%') and enabled != 0
GET _search
{
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
"match_phrase": {
"title": "上海"
}
},
{
"match_phrase": {
"content": "上海"
}
}
]
}
},
{
"match": {
"type": "1"
}
}
],
"must_not": [
{
"match": {
"enabled": 0
}
}
]
}
},
"highlight": {
"pre_tags": [
"<font color='red'>"
],
"post_tags": [
"</font>"
],
"fields": {
"title": {},
"content": {}
}
}
}
@Override
public CommonResult<?> search(String keyword, Integer type, Integer pageNum, Integer pageSize) {
// 处理分页逻辑
pageNum = Optional.ofNullable(pageNum).orElse(1);
pageSize = Optional.ofNullable(pageSize).orElse(10);
// 设置代码高亮
String preTag = "<font color='#dd4b39'>";
String postTag = "</font>";
// 创建查询语句 ES中must和should不能同时使用 同时使用should失效 嵌套多个must 将should条件拼接在一个must中即可
BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery()
.should(QueryBuilders.matchPhraseQuery("title", keyword))
.should(QueryBuilders.matchPhraseQuery("content", keyword));
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
.must(shouldQuery)
.mustNot(QueryBuilders.matchQuery("enabled", 0));
if (!ObjectUtils.isEmpty(type) && type > 0 && type < 9) {
boolQueryBuilder.must(QueryBuilders.matchQuery("type", type));
}
// 封装查询
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder()
.withQuery(boolQueryBuilder)
.withPageable(PageRequest.of(Math.max(pageNum - 1, 0), pageSize))
.withHighlightFields(new HighlightBuilder.Field("title").preTags(preTag).postTags(postTag),
new HighlightBuilder.Field("content").preTags(preTag).postTags(postTag));
// 进行查询操作
AggregatedPage<SearchMainPageEntity> pages = mRestTemplate.queryForPage(builder.build(), SearchMainPageEntity.class, new CustomEsResultMapper());
Object resultInfo = CustomEsResultMapper.inflatePageInfo(pages);
return successBody(resultInfo);
}