导包
导包可以根据 文档 里导入依赖
这里就不写依赖了
代码
- from:开始位置
- size:每页大小
import com.google.gson.Gson;
import com.leyou.pojo.Item;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsdemoFindHighlight {
private RestHighLevelClient client;
private Gson gson = new Gson();
/**
* 先执行
*/
@Before
public void init (){
// 初始化HighLevel客户端
client = new RestHighLevelClient(
RestClient.builder(
HttpHost.create("http://127.0.0.1:9201"),
HttpHost.create("http://127.0.0.1:9202"),
HttpHost.create("http://127.0.0.1:9203")
)
);
}
/**
* 高亮
*/
@Test
public void findSource() throws IOException {
//创建搜索对象
SearchRequest searchRequest = new SearchRequest();
// 构建查询对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//查询条件
searchSourceBuilder.query(QueryBuilders.termQuery("字段名1", "字段中的内容"));
//高亮对象
HighlightBuilder highlightBuilder = new HighlightBuilder();
//设置高亮参数
highlightBuilder.field("字段名1"); //参数要和查询条件字段名一样
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
searchRequest.source(searchSourceBuilder);
//搜索
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
//解析
SearchHits hits = search.getHits();
SearchHit[] hitsHits = hits.getHits();
for (SearchHit hit : hits) {
//获取数据
String jsonStr = hit.getSourceAsString();
//反序列化
Item item = gson.fromJson(jsonStr, Item.class);
//获得返回的高亮数据
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
//是否为空
if(highlightFields!=null){
//参数要和查询的参数一致
HighlightField highlightField = highlightFields.get("字段名1");
//判断是否为空
if(highlightField.fragments()!=null&&highlightField.fragments().length>0){
String title = highlightField.fragments()[0].toString();
//设置参数将高亮的内容,替换原来的内容
item.setTitle(title);
}
}
//打印结果
System.out.println("结果:" item);
}
}
/**
* 后执行
*/
@After
public void close(){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}