ElasticSearch 高亮查询-脚本
高亮三要素:需要高亮显示的字段,前缀,后缀;
默认前后缀 :em
<em>手机</em>
GET goods/_search
{
"query": {
"match": {
"title": "电视"
}
},
"highlight": {
"fields": {
"title": {
"pre_tags": "<font color='red'>",
"post_tags": "</font>" }}}}
/* :高亮查询 : 就是将被用户搜索多的信息标题等,换颜色等来区分
* 1.设置高亮
* 要设置 需要高亮显示的字段,前缀,后缀
2. 将高亮的数据,替换原有的数据 */
@Test
public void testHighLightQuery() throws IOException {
SearchRequest searchRequest = new SearchRequest("goods");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 1.查询title标题包含手机的数据
MatchQueryBuilder query = QueryBuilders.matchQuery("titls", "手机");
sourceBuilder.query(query);
// 设置高亮对象
HighlightBuilder highlighter = new HighlightBuilder();
// 设置高亮三要素
/* 不设置前后缀 系统用默认的前后缀<em></em>*/
highlighter.field("title"); //设置高亮的字段
highlighter.preTags("<font color='red'>"); // 设置高亮前缀
highlighter.postTags("</font>"); // 设置高粱后缀
sourceBuilder.highlighter(highlighter);
// 2. 查询品牌列表
/* 参数 "goods_brands" 自定义的名称,将来用于获取数据用的
* 参数 "brandName" 分组的字段
* size(100) 的意思是设置查询100条数据
* 这个带有自动分页显示的功能*/
AggregationBuilder agg = AggregationBuilders.terms("goods_brands").field("brandName").size(100);
sourceBuilder.aggregation(agg);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits searchHits = searchResponse.getHits();
// 获取记录数
long value = searchHits.getTotalHits().value;
System.out.println("总记录数:"+value);
List<Goods> goodsList = new ArrayList<>();
SearchHit[] hits = searchHits.getHits();
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
// 转为Java
Goods goods = JSON.parseObject(sourceAsString, Goods.class);
// 获取高亮结果,在这里 替换goods中的title
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField HighlightField = highlightFields.get("title");
Text[] fragments = HighlightField.fragments();
// 替换
goods.setTitle(fragments[0].toString());
goodsList.add(goods);
}
for (Goods goods : goodsList) {
System.out.println(goods);
}
// 获取聚合结果
Aggregations aggregations = searchResponse.getAggregations();
Terms goods_brands = (Terms) aggregations.get("goods_brands");
List<? extends Terms.Bucket> buckets = goods_brands.getBuckets();
List brands = new ArrayList();
for (Terms.Bucket bucket : buckets) {
Object key = bucket.getKey();
brands.add(key);
}
for (Object brand : brands) {
System.out.println(brand);
}
}