搜索关键字高亮显示

搜索关键字高亮显示

spring data solr 搜索关键字高亮显示

public Map<String, Object> highSearch(Map searchMap) {
        Map map = new HashMap<>();
        SimpleHighlightQuery query = new SimpleHighlightQuery();

        HighlightOptions highlightOptions = new HighlightOptions().addField("item_title");//设置高亮域
        highlightOptions.setSimplePrefix("<em style='color:red'>");         //设置高亮前缀
        highlightOptions.setSimplePostfix("</em>");                           //设置高亮后缀
        query.setHighlightOptions(highlightOptions);                           //设置高亮显示

        //1.按照关键字查询
        Criteria criteria = new Criteria("item_keywords").is(searchMap.get("keywords"));
        query.addCriteria(criteria);
        //2.按分类筛选
        if(!"".equals(searchMap.get("category"))){
            Criteria filterCriteria = new Criteria("item_category").is(searchMap.get("category"));
            FilterQuery filterQuery = new SimpleFilterQuery(filterCriteria);
            query.addFilterQuery(filterQuery);
        }
        //3.按品牌筛选
        if(!"".equals(searchMap.get("brand"))){
            Criteria filterCriteria = new Criteria("item_brand").is(searchMap.get("brand"));
            FilterQuery filterQuery = new SimpleFilterQuery(filterCriteria);
            query.addFilterQuery(filterQuery);
        }
        //4.按规格筛选
        if (searchMap.get("spec") != null){
            Map<String,String> specMap = (Map<String, String>) searchMap.get("spec");
            for (String key : specMap.keySet()) {
                Criteria filtercriteria = new Criteria("item_spec_" + key).is(specMap.get(key));
                FilterQuery filterQuery = new SimpleFilterQuery(filtercriteria);
                query.addFilterQuery(filterQuery);
            }
        }

        //设置查询条件
        Integer pageNo = (Integer) searchMap.get("pageNo");     //获取页数
        Integer pageSize = (Integer) searchMap.get("pageSize"); //获取每页记录数
        query.setOffset((pageNo-1) * pageSize);                 //设置开始查找的索引
        query.setRows(pageSize);                                //设置每页记录数

        //用于存储修改高亮显示后的记录
        List<Item> list = new ArrayList<>();

        HighlightPage<Item> page = solrTemplate.queryForHighlightPage(query, Item.class);
        for (HighlightEntry<Item> highlightEntry : page.getHighlighted()) {
            Item item = highlightEntry.getEntity();
            List<HighlightEntry.Highlight> highlights = highlightEntry.getHighlights();
            if(highlights != null && highlights.size() > 0){
                //获取高亮的标题集合
                List<String> titles = highlights.get(0).getSnipplets();
                if(titles !=null && titles.size() > 0){
                    //获取高亮的标题
                    item.setTitle(titles.get(0));
                }
            }
            list.add(item);
        }

        map.put("rows", list );
        map.put("total", page.getTotalElements());
        map.put("totalPages", page.getTotalPages());

        return map;
    }
12-27 17:23