solrJ管理索引库(单机版)实例

来源:互联网 发布:阳江网络问政平台举报 编辑:程序博客网 时间:2024/05/16 12:38

solr测试
使用SolrJ实现索引库的增删查操作。
增:

@Test    public void addDocument() throws Exception {        // 第一步:把solrJ的jar包添加到工程中。        // 第二步:创建一个SolrServer,使用HttpSolrServer创建对象。        SolrServer solrServer = new HttpSolrServer("http://虚拟机地址:端口/solr");        // 第三步:创建一个文档对象SolrInputDocument对象。        SolrInputDocument document = new SolrInputDocument();        // 第四步:向文档中添加域。必须有id域,域的名称必须在schema.xml中定义。        document.addField("id", "test001");        document.addField("item_title", "测试商品");        // 第五步:把文档添加到索引库中。        solrServer.add(document);        // 第六步:提交。        solrServer.commit();    }

删:

@Test    public void deleteDocumentById() throws Exception {        // 第一步:创建一个SolrServer对象。        SolrServer solrServer = new HttpSolrServer("http://虚拟机地址:端口/solr");        // 第二步:调用SolrServer对象的根据id删除的方法。        solrServer.deleteById("1");        // 第三步:提交。        solrServer.commit();    }@Test    public void deleteDocumentByQuery() throws Exception {        SolrServer solrServer = new HttpSolrServer("http://虚拟机地址:端口/solr");        //根据查询删除        solrServer.deleteByQuery("title:change.me");        solrServer.commit();    }

查:

@Test    public void queryDocumentWithHighLighting() throws Exception {        // 第一步:创建一个SolrServer对象        SolrServer solrServer = new HttpSolrServer("http://虚拟机地址:端口/solr");        // 第二步:创建一个SolrQuery对象。        SolrQuery query = new SolrQuery();        // 第三步:向SolrQuery中添加查询条件、过滤条件。。。        query.setQuery("测试");        //指定默认搜索域        query.set("df", "item_keywords");        //需要高亮时,可开启高亮显示        query.setHighlight(true);        //高亮显示的域        query.addHighlightField("item_title");        query.setHighlightSimplePre("<em>");        query.setHighlightSimplePost("</em>");        // 第四步:执行查询。得到一个Response对象。        QueryResponse response = solrServer.query(query);        // 第五步:取查询结果。        SolrDocumentList solrDocumentList = response.getResults();        System.out.println("查询结果的总记录数:" + solrDocumentList.getNumFound());        // 第六步:遍历结果并打印。        for (SolrDocument solrDocument : solrDocumentList) {            System.out.println(solrDocument.get("id"));            //取高亮显示            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();            List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");            String itemTitle = null;            if (list != null && list.size() > 0) {                itemTitle = list.get(0);            } else {                itemTitle = (String) solrDocument.get("item_title");            }            System.out.println(itemTitle);            System.out.println(solrDocument.get("item_price"));        }    }

SolrServer的配置

<bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">        <constructor-arg index="0" value="http://虚拟机地址:端口/solr"/>    </bean>


ok!!!结束!! 希望给各位猿友带来帮助吧!!! 偷偷告诉你们!!!这是我刚写的日记!!