java1234开源博客系统
博客信息

elasticsearch条件查询高亮实现restful api以及java代码实现

发布时间:『 2018-01-10 15:30』  博客类别:elasticsearch  阅读(6459) 评论(0)

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":{}}

   }

}

QQ鎴浘20180109231754.jpg


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:最后的绝地武士]]}



关键字:   elasticsearch     条件查询高亮  
关注Java1234微信公众号
博主信息
Java1234_小锋
(知识改变命运,技术改变世界)
Powered by Java1234 V3.0 Copyright © 2012-2016 Java知识分享网 版权所有