elasticsearch条件查询高亮实现restful api以及java代码实现
restful api实现:
post http://192.168.1.111:9200/film/dongzuo/_search/
{
"query":{
"match":{"title":"战"}
},
"_source":{
"include":["title","price"]
},
"highlight":{
"fields":{"title":{}}
}
}
java代码实现:
/** * 条件查询高亮实现 * @throws Exception */ @Test public void searchHighlight()throws Exception{ SearchRequestBuilder srb=client.prepareSearch("film").setTypes("dongzuo"); HighlightBuilder highlightBuilder=new HighlightBuilder(); highlightBuilder.preTags("<h2>"); highlightBuilder.postTags("</h2>"); highlightBuilder.field("title"); SearchResponse sr=srb.setQuery(QueryBuilders.matchQuery("title", "战")) .highlighter(highlightBuilder) .setFetchSource(new String[]{"title","price"}, null) .execute() .actionGet(); // 分页排序所有 SearchHits hits=sr.getHits(); for(SearchHit hit:hits){ System.out.println(hit.getSourceAsString()); System.out.println(hit.getHighlightFields()); } }
运行输出:
{"price":"38","title":"战狼2"}
{title=[title], fragments[[<h2>战</h2>狼2]]}
{"price":"55","title":"星球大战8:最后的绝地武士"}
{title=[title], fragments[[星球大<h2>战</h2>8:最后的绝地武士]]}