既然你点到这里了,那你也有一定es的基础了,关于es的配置和依赖我也不多说了,直接上代码
controller层
@GetMapping("eskeyword")
public R mohu(@RequestParam(value = "ename",defaultValue = "")String ename
,@RequestParam(value = "page",defaultValue = "1")int page
,@RequestParam(value = "size",defaultValue = "3")int size) throws IOException {
//这个pageutils是我自动生成的你们另选其他
PageUtils mohues = stuService.mohues(ename, page, size);
return R.ok().put("page",mohues);
}
serviceimp
@Override
public PageUtils mohues(String ename, int page, int size) throws IOException {
SearchRequest searchRequest = new SearchRequest("week2");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
System.out.println(ename);
//判断是否存在
if (ename.equals("")){
//不存在查全部
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
}else {
//存在查条件 //多条件用,分隔
MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(ename, "ename", "sex");
searchSourceBuilder.query(queryBuilder);
}
//分页
searchSourceBuilder.from((page-1)*size);
searchSourceBuilder.size(size);
//高亮
if (!ename.equals("")){
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("ename").field("sex");
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
}
//sex
searchRequest.source(searchSourceBuilder);
//执行
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//处理结果
SearchHits hits = search.getHits();
TotalHits totalHits = hits.getTotalHits();
//所有数量
long aa= totalHits.value;
SearchHit[] hits1 = hits.getHits();
ArrayList<StuEntity> arr = new ArrayList<>();
for (SearchHit hit : hits1) {
String index = hit.getIndex();
String id = hit.getId();
float score = hit.getScore();
//拿到json字符串
String string = hit.getSourceAsString();
//json转对象
StuEntity stuEntity = JSON.parseObject(string, StuEntity.class);
stuEntity.setEid(Integer.valueOf(id));
if(ename.equals("")){
}else {
//处理高亮====================================
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
//获取ename的值
HighlightField highlight = highlightFields.get("ename");
if (highlight!=null){
//官方粘的,别问我什么意思
Text[] fragments = highlight.fragments();
String fragmentString = fragments[0].string();
stuEntity.setEname(fragmentString);
}
HighlightField sexhighlight = highlightFields.get("sex");
if (sexhighlight!=null){
//和上同理sexhighlight是上面返回的值
Text[] fragments = sexhighlight.fragments();
String fragmentString = fragments[0].string();
stuEntity.setSex(fragmentString);
}
}
arr.add(stuEntity);
}
//分页
PageUtils stuEntityPageUtil = new PageUtils(arr, Math.toIntExact(aa),size,page);
return stuEntityPageUtil;
}
外加SQL写法
GET week2/_search
{
"query": {
"multi_match": {
"query": "张",
"fields": ["ename","sex"]
}
},
"highlight": {
"fields": {"ename":{}},
"pre_tags": "<span style='color:red'>",
"post_tags": "</span>"
}
}
另外小提示
前台es想要 高亮必须加
想要详细查看官网
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.x/java-rest-high-search.html