【Solr】SolrJ使用

测试Demo

1.添加Document Demo

public void addDocument() throws Exception {
    //创建一个SolrServer对象,创建一个连接。参数solr服务的url
    SolrServer solrServer = new HttpSolrServer("http://192.168.21.80:8080/solr/collection1");
    //创建一个文档对象SolrInputDocument
    SolrInputDocument document = new SolrInputDocument();
    //向文档对象中添加域。文档中必须包含一个id域,所有的域的名称必须在schema.xml中定义。
    document.addField("id", "doc01");
    document.addField("item_title", "测试商品01");
    document.addField("item_price", 1000);
    //把文档写入索引库
    solrServer.add(document);
    //提交
    solrServer.commit();
}

2.删除Document Demo

public void deleteDocument() throws Exception {
    SolrServer solrServer = new HttpSolrServer("http://192.168.21.80:8080/solr/collection1");
    //删除文档
    //solrServer.deleteById("doc01");
    solrServer.deleteByQuery("id:doc01");
    //提交
    solrServer.commit();
}

3.简单查询 Demo

public void queryIndexSimple() throws Exception {
    //创建一个SolrServer对象。
    SolrServer solrServer = new HttpSolrServer("http://192.168.21.80:8080/solr/collection1");
    //创建一个SolrQuery对象。
    SolrQuery query = new SolrQuery();
    //设置查询条件。
    //query.setQuery("*:*");
    query.set("q", "*:*");
    //执行查询,QueryResponse对象。
    QueryResponse queryResponse = solrServer.query(query);
    //取文档列表。取查询结果的总记录数
    SolrDocumentList solrDocumentList = queryResponse.getResults();
    System.out.println("查询结果总记录数:" + solrDocumentList.getNumFound());
    //遍历文档列表,从取域的内容。
    for (SolrDocument solrDocument : solrDocumentList) {
        System.out.println(solrDocument.get("id"));
        System.out.println(solrDocument.get("item_title"));
        System.out.println(solrDocument.get("item_sell_point"));
        System.out.println(solrDocument.get("item_price"));
        System.out.println(solrDocument.get("item_image"));
        System.out.println(solrDocument.get("item_category_name"));
    }
}

4.复杂查询 Demo

public void queryIndexDifficult() throws Exception {
        SolrServer solrServer = new HttpSolrServer("http://192.168.21.80:8080/solr/collection1");
        //创建一个查询对象
        SolrQuery query = new SolrQuery();
        //查询条件
        query.setQuery("手机");
        query.setStart(0);
        query.setRows(20);
        query.set("df", "item_title");
        query.setHighlight(true);
        query.addHighlightField("item_title");
        query.setHighlightSimplePre("");
        query.setHighlightSimplePost("");
        //执行查询
        QueryResponse queryResponse = solrServer.query(query);
        //取文档列表。取查询结果的总记录数
        SolrDocumentList solrDocumentList = queryResponse.getResults();
        System.out.println("查询结果总记录数:" + solrDocumentList.getNumFound());
        //遍历文档列表,从取域的内容。
        Map>> highlighting = queryResponse.getHighlighting();
        for (SolrDocument solrDocument : solrDocumentList) {
            System.out.println(solrDocument.get("id"));
            //取高亮显示
            List list = highlighting.get(solrDocument.get("id")).get("item_title");
            String title = "";
            if (list !=null && list.size() > 0 ) {
                title = list.get(0);
            } else {
                title = (String) solrDocument.get("item_title");
            }
            System.out.println(title);
            System.out.println(solrDocument.get("item_sell_point"));
            System.out.println(solrDocument.get("item_price"));
            System.out.println(solrDocument.get("item_image"));
            System.out.println(solrDocument.get("item_category_name"));
        }
    }

 

数据导入索引库

1.添加pom依赖


<dependency>
    <groupId>org.apache.solrgroupId>
    <artifactId>solr-solrjartifactId>
dependency>

2.配置applicationContext-solr.xml

<bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
        <constructor-arg index="0" value="http://192.168.21.80:8080/solr/collection1"/>
bean>

3.配置web.xml


<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring/applicationContext-*.xmlparam-value>
context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>

4.导入数据代码

@Autowired
private ItemMapper itemMapper;
@Autowired
private SolrServer solrServer;

public CommonResult importAllItems() {
    try {
        //查询商品列表
        List itemList = itemMapper.getItemList();
        //遍历商品列表
        for (SearchItem searchItem : itemList) {
            //创建文档对象
            SolrInputDocument document = new SolrInputDocument();
            //向文档对象中添加域
            document.addField("id", searchItem.getId());
            document.addField("item_title", searchItem.getTitle());
            document.addField("item_sell_point", searchItem.getSell_point());
            document.addField("item_price", searchItem.getPrice());
            document.addField("item_image", searchItem.getImage());
            document.addField("item_category_name", searchItem.getCategory_name());
            //把文档对象写入索引库
            solrServer.add(document);
        }
        //提交
        solrServer.commit();
        //返回导入成功
        return CommonResult.ok();
    } catch (Exception e) {
        e.printStackTrace();
        return CommonResult.build(500, "数据导入时发生异常");

    }
}

 

查询索引库

1.Dao代码

@Autowired
private SolrServer solrServer;

public SearchResult search(SolrQuery query) throws Exception {
    //根据query查询索引库
    QueryResponse queryResponse = solrServer.query(query);
    //取查询结果。
    SolrDocumentList solrDocumentList = queryResponse.getResults();
    //取查询结果总记录数
    long numFound = solrDocumentList.getNumFound();
    SearchResult result = new SearchResult();
    result.setRecordCount(numFound);
    //取商品列表,需要取高亮显示
    Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
    List<SearchItem> itemList = new ArrayList<>();
    for (SolrDocument solrDocument : solrDocumentList) {
        SearchItem item = new SearchItem();
        item.setId((String) solrDocument.get("id"));
        item.setCategory_name((String) solrDocument.get("item_category_name"));
        item.setImage((String) solrDocument.get("item_image"));
        item.setPrice((long) solrDocument.get("item_price"));
        item.setSell_point((String) solrDocument.get("item_sell_point"));
        //取高亮显示
        List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
        String title = "";
        if (list != null && list.size() > 0) {
            title = list.get(0);
        } else {
            title = (String) solrDocument.get("item_title");
        }
        item.setTitle(title);
        //添加到商品列表
        itemList.add(item);
    }
    result.setItemList(itemList);
    //返回结果
    return result;
}

2.Service代码

@Autowired
private SearchDao searchDao;

@Override
public SearchResult search(String keyword, int page, int rows) throws Exception {
    //创建一个SolrQuery对象
    SolrQuery query = new SolrQuery();
    //设置查询条件
    query.setQuery(keyword);
    //设置分页条件
    if (page <=0 ) page =1;
    query.setStart((page - 1) * rows);
    query.setRows(rows);
    //设置默认搜索域
    query.set("df", "item_title");
    //开启高亮显示
    query.setHighlight(true);
    query.addHighlightField("item_title");
    query.setHighlightSimplePre("");
    query.setHighlightSimplePost("");
    //调用dao执行查询
    SearchResult searchResult = searchDao.search(query);
    //计算总页数
    long recordCount = searchResult.getRecordCount();
    int totalPage = (int) (recordCount / rows);
    if (recordCount % rows > 0) 
        totalPage ++;
    //添加到返回结果
    searchResult.setTotalPages(totalPage);
    //返回结果
    return searchResult;
}

3.Controller代码

@Autowired
private SearchService searchService;

@Value("${SEARCH_RESULT_ROWS}")
private Integer SEARCH_RESULT_ROWS;

@RequestMapping("/search")
public String searchItemList(String keyword, 
        @RequestParam(defaultValue="1") Integer page, Model model) throws Exception {
    keyword = new String(keyword.getBytes("iso-8859-1"), "utf-8");
    //查询商品列表
    SearchResult searchResult = searchService.search(keyword, page, SEARCH_RESULT_ROWS);
    //把结果传递给页面
    model.addAttribute("query", keyword);
    model.addAttribute("totalPages", searchResult.getTotalPages());
    model.addAttribute("page", page);
    model.addAttribute("recourdCount", searchResult.getRecordCount());
    model.addAttribute("itemList", searchResult.getItemList());

    //返回逻辑视图
    return "search";
}

你可能感兴趣的:(【,Java,】,………Solr)