elasticsearch高亮显示查询结果

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("");//前置元素
    searchRequestBuilder.setHighlighterPostTags("");//后置元素
    SearchResponse searchResponse = searchRequestBuilder.get();
    SearchHits hits = searchResponse.getHits();//获取命中次数,查询结果有多少对象
    System.out.println("查询结果有:"+hits.getTotalHits()+"条");
    Iterator iterator = hits.iterator();
    while(iterator.hasNext()){
        SearchHit searchHit = iterator.next();//每个查询对象
        //将高亮处理后的内容,替换原有内容(原有内容,可能会出现显示不全)
        Map 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();
}

你可能感兴趣的:(后台编程,经验分享,学亮说JAVA)