public class ItemSearchImpl implements ItemSearchService { /** * 搜索 * * @param paramMap * @return */ @Autowired private SolrTemplate solrTemplate; @Autowired private RedisTemplate redisTemplate; @Override public Map<String, Object> search(Map paramMap) { //获取关键字 String keywords = (String) paramMap.get("keywords"); //获取当前页 Integer pageNo = Integer.parseInt(String.valueOf(paramMap.get("pageNo"))); //每页查询多少条 Integer pageSize = Integer.parseInt(String.valueOf(paramMap.get("pageSize"))); //封装查询对象 HighlightQuery query = new SimpleHighlightQuery(); //查询的条件对象· Criteria criteria = new Criteria("item_keywords").is(keywords); //将查询条件放入对象 query.addCriteria(criteria); //计算从第几页开始读 if(pageNo==null || pageNo<=0){ pageNo=1; } Integer start = (pageNo-1)*pageSize; //设置从第几页查询 query.setOffset(start); //设置每页多少条 query.setRows(pageSize); //创建高亮显示对象 HighlightOptions highlightOptions = new HighlightOptions(); //设置哪个域需要高亮 highlightOptions.addField("item_title"); //高亮的前缀 highlightOptions.setSimplePrefix("<em style=" color=red ">"); //高亮的后缀 highlightOptions.setSimplePostfix("</em>"); //将高亮加入到查询对象 query.setHighlightOptions(highlightOptions); //查询并返回结果 HighlightPage<TbItem> items = solrTemplate.queryForHighlightPage(query, TbItem.class); //获取带高亮的集合 List<HighlightEntry<TbItem>> highlighted = items.getHighlighted(); List<TbItem> itemList = new ArrayList<>(); //遍历高亮集合 for (HighlightEntry<TbItem> itemHighlightEntry: highlighted) { TbItem item = itemHighlightEntry.getEntity(); List<HighlightEntry.Highlight> highlights = itemHighlightEntry.getHighlights(); if(highlights!=null && highlights.size()>0){ //获取高亮的标题集合 List<String> highlightTitle = highlights.get(0).getSnipplets(); if(highlightTitle!=null&&highlightTitle.size()>0){ // 获取高亮的标题 String title = highlightTitle.get(0); item.setTitle(title); } } itemList.add(item); } Map<String,Object> resuleMap = new HashMap<>(); //查询到的结果集 resuleMap.put("rows",itemList); //总页数 resuleMap.put("totalPage",items.getTotalPages()); //总条数 resuleMap.put("total",items.getTotalElements()); return resuleMap; } }
。