0


源码请拿走:用Elasticsearch完成视频检索(有详细注释,学习可用)

@Service
public class SearchServiceImpl implements SearchService {

@Autowired
 RestHighLevelClient restHighLevelClient;

/**
  *
  * @param q   搜索关键字
  * @param page  当前页
  * @param per_page   每页展示条数
  * @return   Map<String, Object>  total_count检索总条数  items检索列表
  */
 @Override
 public Map<String, Object> searchVideos(String q, Integer page, Integer per_page) throws IOException {
     //创建搜索请求
     SearchRequest searchRequest = new SearchRequest("yingxue");
     //创建搜索对象
     SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

    searchSourceBuilder.query(QueryBuilders.termQuery("title", q))
             .from((page - 1) * per_page)  //设置起始条数
             .size(per_page)  //设置每页展示条数
             .highlighter(new HighlightBuilder()  //设置高亮
                     .field("*")    //设置匹配字段为全部匹配
                     .requireFieldMatch(false)    //设置关闭字段匹配
                     .preTags("<span style='color:red'>")  //前置标签
                     .postTags("</span>")   //后置标签
             );
     //指定检索的类型、条件source
     searchRequest.types("video").source(searchSourceBuilder);
     //执行搜索
     SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
     ArrayList<Map<String, Object>> list = new ArrayList<>();
     for (SearchHit hit : searchResponse.getHits().getHits()){
         Map<String, Object> sourceAsMap = hit.getSourceAsMap();
         list.add(sourceAsMap);
     }
     //解析结果
     ArrayList<Map<String, Object>> list = new ArrayList<>();
     for (SearchHit hit : searchResponse.getHits().getHits()) {
         //解析高亮的字段
         Map<String, HighlightField> highlightFields = hit.getHighlightFields();
         //获取高亮字段
         HighlightField title = highlightFields.get("title");
         //原结果
         Map<String, Object> sourceAsMap = hit.getSourceAsMap();
         //将原来的字段换为我们高亮的字段
         if(title!=null){
             Text[] fragments = title.fragments();
             StringBuilder n_title= new StringBuilder();
             for (Text text:fragments){
                 n_title.append(text);
             }
             sourceAsMap.put("title", n_title.toString());//高亮字段替换原来的内容
         }
         list.add(sourceAsMap);
     }
     //返回查询总记录数
     Integer total= Math.toIntExact(searchResponse.getHits().getTotalHits());
     HashMap<String, Object> map = new HashMap<>();
     map.put("total_count", total);
     map.put("items", list);
     return map;
 }

}


本文转载自: https://blog.csdn.net/m0_66194642/article/details/122428234
版权归原作者 打工人何苦为难打工人 所有, 如有侵权,请联系我们删除。

“源码请拿走:用Elasticsearch完成视频检索(有详细注释,学习可用)”的评论:

还没有评论