1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| //高亮 @Test void testHighlight() throws IOException { //1.准备Request SearchRequest request = new SearchRequest("hotel"); //2.准备DSL //2.1 query request.source().query(QueryBuilders.matchQuery("all","如家")); //2.2 高亮 request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
//3.发送请求 SearchResponse response = client.search(request,RequestOptions.DEFAULT);
handleResponce1(response);
System.out.println(response); }
private void handleResponce1(SearchResponse response) { //4.解析响应 SearchHits searchHits = response.getHits(); //4.1获取总条数 long total = searchHits.getTotalHits().value; System.out.println("共搜索到"+total+"条数据"); //4.2文档数组 SearchHit[] hits = searchHits.getHits(); //4.3遍历 for(SearchHit hit : hits){ //获取文档source String json = hit.getSourceAsString(); //反序列化 HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
//获取高亮结果 Map<String, HighlightField> highlightFields = hit.getHighlightFields(); if(!CollectionUtils.isEmpty(highlightFields)){ //根据各字段名获取高亮结果 HighlightField highlightField = highlightFields.get("name"); if(highlightField != null){ //获取高亮 String name = highlightField.getFragments()[0].string(); //覆盖非高亮结果 hotelDoc.setName(name); } }
System.out.println("hotelDoc = "+hotelDoc); } }
|