elasticsearch高亮显示查询结果
//高亮显示查询结果
@Test
public void demo9() throws Exception{
//创建连接搜索服务器的对象
Client client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));
ObjectMapper objectMapper = new ObjectMapper();
//搜索 数据
SearchRequestBuilder searchRequestBuilder = client.prepareSearch("blog2").setTypes("article").setQuery(QueryBuilders.termQuery("title","搜索 "));
//高亮定义
searchRequestBuilder.addHighlightedField("title");//对title字段进行高亮显示
searchRequestBuilder.setHighlighterPreTags("<em>");//前置元素
searchRequestBuilder.setHighlighterPostTags("</em>");//后置元素
SearchResponse searchResponse = searchRequestBuilder.get();
SearchHits hits = searchResponse.getHits();//获取命中次数,查询结果有多少对象
System.out.println("查询结果有:"+hits.getTotalHits()+"条");
Iterator<SearchHit> iterator = hits.iterator();
while(iterator.hasNext()){
SearchHit searchHit = iterator.next();//每个查询对象
//将高亮处理后的内容,替换原有内容(原有内容,可能会出现显示不全)
Map<String,HighlightField> hightlightFields = searchHit.getHighlightFields();
HighlightField titleField = hightlightFields.get("title");
//获取到原有内容中 每个高亮显示 集中位置fragment就是高亮片段
Text[] fragments = titleField.fragments();
String title = "";
for(Text text:fragments){
title += text;
}
//将查询结果转换为对象
Article article = objectMapper.readValue(searchHit.getSourceAsstring(),Article.class);
//用高亮后的内容,替换原有内容
article.setTitle(title);
System.out.println(article);
}
//关闭连接
client.close();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。