1. 程式人生 > >使用SolrJ代碼導入,發布搜索服務

使用SolrJ代碼導入,發布搜索服務

manage == portal clas red pos @override -m urn

搭建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);
    }
}

使用SolrJ代碼導入,發布搜索服務