ES 高亮搜素

public List<ContentES> getAll(SearchReq req) throws IOException {


    String accountName = UserUtil.getUser().getUserName();
    SearchRequest searchRequest = new SearchRequest(SearchConstant.CONTENT_INDEX_NAME).types(SearchConstant.CONTENT_INDEX_TYPE);
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    //模糊搜索
    QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder(req.getKeyWord());
    queryBuilder.field(SearchConstant.TITLE);


    //条件筛选具体那个字段为指定值
  /*  BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
    boolBuilder.must(
            QueryBuilders.matchQuery(SearchConstant.ACCOUNTNAME, accountName)
    );*/
    //构建高亮体
    HighlightBuilder highlightBuilder = new HighlightBuilder();

    highlightBuilder.field(SearchConstant.TITLE);

    //搜索体(添加多个搜索参数)
    searchSourceBuilder.highlighter(highlightBuilder);
    searchSourceBuilder.query(queryBuilder);
    searchRequest.source(searchSourceBuilder);
    SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
    SearchHit[] hits = response.getHits().getHits();
    List<ContentES> list = new ArrayList<>();
    for (SearchHit hit : response.getHits()) {

        //将文档中的每一个对象转换json串值
        String sourceAsString = hit.getSourceAsString();
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        HighlightField titleField = highlightFields.get("title");
        if (titleField != null) {
            Text[] fragments = titleField.fragments();
            String title = "";
            for (Text text : fragments) {
                title += text;
            }
            //将json串值转换成对应的实体对象
            ContentES contentES = JSON.parseObject(sourceAsString, ContentES.class);
            contentES.setTitle(title);
            list.add(contentES);

        }
        return list;
    }
    return list;

}
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读