springdata elasticSearch 查询高亮显示

postman 中请求 :http://localhost:9200/document/_search

用post 请求:

{
	"query":{
		"multi_match":{
			 "query": "朗逸",
    		 "fields": ["desc"]
		}
	},
	
	"from": 0, 
	"size": 100,
	"sort": [
		{"craetetime":"asc"}
    ],
	"highlight": { 
			"require_field_match": false, 
			"fields": { 
				"title": { "pre_tags": [ "" ], "post_tags": [ "" ]} ,
				"desc": { "pre_tags": [ "" ], "post_tags": [ "" ]}
				}
		}
}

返回结果

springdata elasticSearch 查询高亮显示_第1张图片

 

springdata 操作elasticserach

//高亮显示
	@Test
	public void documentHigh(){
		Pageable pageable= PageRequest.of(0,2);
		String preTag = "";//google的色值
		String postTag = "";
		SearchQuery searchQuery=new NativeSearchQueryBuilder().
				withQuery(QueryBuilders.matchQuery("desc","朗逸")).
				withHighlightFields(new HighlightBuilder.Field("desc").preTags(preTag).postTags(postTag))
				.build();
		searchQuery.setPageable(pageable);

		Page esDocuments=elasticsearchTemplate.queryForPage(searchQuery, esDocument.class, new SearchResultMapper() {
			@Override
			public  AggregatedPage mapResults(SearchResponse response, Class aClass, Pageable pageable) {
				List chunk = new ArrayList<>();
				for (SearchHit searchHit : response.getHits()) {
					if (response.getHits().getHits().length <= 0) {
						return null;
					}
					esDocument esDocument=new esDocument();
					//name or memoe
					HighlightField itemTitle = searchHit.getHighlightFields().get("desc");
					if (itemTitle != null) {
						esDocument.setDesc(itemTitle.fragments()[0].toString());
					}
					esDocument.setCar(String.valueOf(searchHit.getSource().get("car")));
					System.out.println(String.valueOf(searchHit.getSource().get("car"))+"----");
					chunk.add(esDocument);
				}
				if (chunk.size() > 0) {
					return new AggregatedPageImpl<>((List) chunk);
				}
				return null;
			}
		});
		for(esDocument e:esDocuments){
			System.out.println(e.getDesc());
		}
	}

 

查询结果

你可能感兴趣的:(springboot学习)