使用SolrJ代码导入,发布搜索服务

搭建solr服务器:http://www.cnblogs.com/liyafei/p/8005571.html

一导入要搜索的字段

1:确定发布搜索的字段,sql语句  

SELECT

a.id,

b. title

FROM

tb_item a

LEFT JOIN tb_item_cat b ON a.cid = b.id

2:创建pojo接收相应的字段

    

public class Item {
    private Long id;
    private String title;
setter and getter }


3:创建Mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.taotao.search.mapper.ItemMapper" >
    <select id="getItemList" resultType="com.taotao.search.pojo.Item">
        SELECT
            a.id,
            b.title
        FROM
            tb_item a
        LEFT JOIN tb_item_cat b ON a.cid = b.id
    </select>
</mapper>

4:创建mapper接口

public interface ItemMapper{
    public List<Item> getItemList();
}

5:配置SolrServer

    

<bean id="solrserver" class="org.apache.solr.client.solrj.SolrServer">
     <constract-arg  name="url" value="http://192.168.100.91:8080/solr"/>
</bean>

7:创建service

  

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private SolrServer solrServer;
    
    @Override
    public TaotaoResult importItemToIndex() throws Exception {
        //查询商品列表
        List<Item> itemList = itemMapper.getItemList();
        //将商品列表导入solr
        for (Item item : itemList) {
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", item.getId());
            document.addField("title", item.getTitle());
            //将文档写入索引库
            solrServer.add(document);
        }
        //提交修改
        solrServer.commit();
        return TaotaoResult.ok();
    }

}

8:创建controller

@Controller
@RequestMapping("/manager")
public class ItemController {

    @Autowired
    private ItemService itemService;
    
    @RequestMapping("/importall")
    @ResponseBody
    public TaotaoResult importAll() {
        TaotaoResult result = null;
        try {
            result = itemService.importItemToIndex();
        } catch (Exception e) {
            e.printStackTrace();
            return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }
        return result;
    }
}

   二:发布搜索服务,可以供其它客户端调用

        1:返回值pojo

            

public class SearchResult {

    private Long recordCount;
    private List<Item> itemList;
    private Integer pageCount;
    private Integer curPage;
    
}

     2:dao,从solr服务器中去查询,不用去数据库

          

@Service
public class ItemSearchDaoImpl implements ItemSearchDao {
    
    @Autowired
    private SolrServer solrServer;

    @Override
    public SearchResult searchItem(SolrQuery solrQuery) throws Exception {
        //根据查询条件搜索索引库
        QueryResponse response = solrServer.query(solrQuery);
        //取商品列表
        SolrDocumentList documentList = response.getResults();
        //商品列表
        List<Item> itemList = new ArrayList<>();
        for (SolrDocument solrDocument : documentList) {
            Item item = new Item();
            item.setId((Long) solrDocument.get("id"));
            //取高亮显示
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
            String title = "";
            if (null != list && !list.isEmpty()) {
                title = list.get(0);
            } else {
                title = (String) solrDocument.get("title");
            }
            item.setTitle(title);
            itemList.add(item);
        }
        SearchResult result = new SearchResult();
        //商品列表
        result.setItemList(itemList);
        //总记录数据
        result.setRecordCount(documentList.getNumFound());
        
        return result;
    }

}

    3:service层

         

@Service
public class ItemSearchServiceImpl implements ItemSearchService {

    @Value("${SEARCH_RESULT_PAGE_SIZE}")
    private Integer PAGE_SIZE;
    @Autowired
    private ItemSearchDao itemSearchDao;
    
    @Override
    public SearchResult searchItem(String queryString, Integer page) throws Exception {
        //创建一个查询对象
        SolrQuery solrQuery = new SolrQuery();
        //查询条件
        if (StringUtils.isBlank(queryString)) {
            solrQuery.setQuery("*:*");
        } else {
            solrQuery.setQuery(queryString);
        }
        //分页条件
        if (page == null) {
            page = 1;
        }
        solrQuery.setStart((page -1) * PAGE_SIZE);
        solrQuery.setRows(PAGE_SIZE);
        //高亮显示
        solrQuery.setHighlight(true);
        //设置高亮显示的域
        solrQuery.addHighlightField("title");
        //高亮显示前缀
        solrQuery.setHighlightSimplePre("<em style="color:red">");
        //后缀
        solrQuery.setHighlightSimplePost("</em>");
        //设置默认搜索域
        solrQuery.set("df", "item_keywords");
        
        //执行查询
        SearchResult result = itemSearchDao.searchItem(solrQuery);
        //计算分页
        Long recordCount = result.getRecordCount();
        int pageCount = (int) (recordCount / PAGE_SIZE);
        if (recordCount % PAGE_SIZE > 0) {
            pageCount++;
        }
        result.setPageCount(pageCount);
        result.setCurPage(page);
        
        return result;
    }

}


4:controller

    

@Controller
public class ItemSearchController {
    
    @Autowired
    private ItemSearchService itemSearchService;

    @RequestMapping("/q")
    @ResponseBody
    public TaotaoResult search(@RequestParam(value = "kw") String queryString,
            @RequestParam(value = "page", defaultValue = "1") Integer page) {
        
        if (StringUtils.isBlank(queryString)) {
            return TaotaoResult.build(400, "查询条件是必须的参数");
        }
        SearchResult result = null;
        try {
            result = itemSearchService.searchItem(queryString, page);
             
        } catch (Exception e) {
            e.printStackTrace();
            return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }
        
        return TaotaoResult.ok(result);
    }
}
原文地址:https://www.cnblogs.com/liyafei/p/8006718.html