最新Java Elasticsearch 7.10教程(五)-高亮查询

一、高亮查询方案

  • 1、直接基于http发送请求
  • 2、基于springboot Repositories
  • 3、基于原生Rest Client(HighRestClient)

推建使用方案2

二、具体实现

1、直接基于http发送请求

参考官方:

Highlighting | Elasticsearch Reference [7.10] | Elastic​www.elastic.co最新Java Elasticsearch 7.10教程(五)-高亮查询_第1张图片

#格式为GET /index名称/_search   _search固定 
# contents为字段名称,kimchy为输入的关键字
GET /bank/_search
{
  "query": {
    "match": { "contents": "kimchy" }
  },
  "highlight": {
    "fields": {
      "contents": {}
    }
  }
}

 

2、基于springboot Repositories

引入@Highlight 注解

    @Highlight(fields = {
            @HighlightField(name = "firstname")
    }, parameters = @HighlightParameters(
            preTags = "",
            postTags = ""
    ))
    List> findByFirstname(String firstname);

Test Case

    /**
     * 高亮显示
     * 使用@Highlight注解
     */
    @Test
    void queryByFirstname() {
        List> result = personRepository.findByFirstname("hanko");
        result.forEach(res-> {
            Map> highlightFields = res.getHighlightFields();
            List highlight = highlightFields.get("firstname");
            highlight.forEach(h-> System.out.println(h));
        });
    }

3、基于原生Rest Client(HighRestClient)

    /**
     * 高亮查询
     * @throws IOException
     */
    @Test
    void highlight() throws IOException {

        SearchRequest searchRequest = new SearchRequest("high-index01");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.highlighter(highlightBuilder());
        searchSourceBuilder.query(new MatchQueryBuilder("title", "你好"));

        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient
               .search(searchRequest, RequestOptions.DEFAULT);
        printHits(searchResponse);
    }

设置高量属性

   private HighlightBuilder highlightBuilder() {
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field("title");
        highlightBuilder.field(highlightTitle);
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        return highlightBuilder;
    }

 

源代码仓库:

https://gitee.com/hankzhousandyos/springboot-elasticsearch​gitee.com

最新Java Elasticsearch 7.10教程(汇总)

https://blog.csdn.net/citywu123/article/details/110240244

 

你可能感兴趣的:(最新,7.10,Elasticsearch,高亮查询,玄明hanko)