Spring集成solr

1. Solr环境搭建


第一步:solr下载

下面以window solr-4.10.3为例:

第二步:解压 solr-4.10.3.zip ,拷贝D:\server\solr-4.10.3\example\webapps\solr.war 到tomcat webapps下:

第三步:把solr-4.10.3\example\lib\ext下的lib都拷贝到apache-tomcat-7.0.86\webapps\solr\WEB-INF\lib下。

第四步:在D:/下新建solr-home文件夹,将solr-4.10.3\example\solr下的文件都拷贝到solr-home下:

第五步:关联solr及solrhome。需要修改solr工程的web.xml 文件

   <env-entry>
       <env-entry-name>solr/home</env-entry-name>
       <env-entry-value>d:/solr-home</env-entry-value>
       <env-entry-type>java.lang.String</env-entry-type>
    </env-entry>

第六步:启动tomcat:http://localhost:8080/solr/, 和linux配置是一样的。

2. 配置业务域


schema.xml中定义

      1、商品Id
      2、商品标题
      3、商品卖点
      4、商品价格
      5、商品图片
      6、分类名称
      7、商品描述

IK中文分词器下载

创建步骤:

第一步:把中文分析器添加到工程中。
1. 将IKAnalyzer2012FF_u1.jar拷贝到 apache-tomcat-7.0.86\webapps\solr\WEB-INF\lib 下。
2.将ext_stopword.dicIKAnalyzer.cfg.xmlmydict.dic拷贝到apache-tomcat-7.0.86\webapps\solr\WEB-INF\classes下 ,如果没有classes文件夹,则新建一个文件夹。
第二步:配置一个FieldType,制定使用IKAnalyzer
修改schema.xml文件
修改Solr的D:\solr-home\collection1\conf\schema.xml文件,添加FieldType:

<fieldType name="text_ik" class="solr.TextField">
  <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
</fieldType>

第三步:配置业务域,type制定使用自定义的FieldType。
设置业务系统Field

<field name="item_title" type="text_ik" indexed="true" stored="true"/>
<field name="item_sell_point" type="text_ik" indexed="true" stored="true"/>
<field name="item_price"  type="long" indexed="true" stored="true"/>
<field name="item_image" type="string" indexed="false" stored="true" />
<field name="item_category_name" type="string" indexed="true" stored="true" />
<field name="item_desc" type="text_ik" indexed="true" stored="false" />

<field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/>
<copyField source="item_title" dest="item_keywords"/>
<copyField source="item_sell_point" dest="item_keywords"/>
<copyField source="item_category_name" dest="item_keywords"/>
<copyField source="item_desc" dest="item_keywords"/>

第四步:重启tomcat

3. Spring 集成 Solr

3.1 添加所需的jar包

        <!-- 添加solrJ的依赖 -->
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
        </dependency>

3.2 Solr测试类

public class TestSolrJ {

    @Test
    public void testAddDocument() throws Exception {
        // 创建一个SolrServer对象。创建一个HttpSolrServer对象
        // 需要指定solr服务的url
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/collection1");
        // 创建一个文档对象SolrInputDocument
        SolrInputDocument document = new SolrInputDocument();
        // 向文档中添加域,必须有id域,域的名称必须在schema.xml中定义
        document.addField("id", "123");
        document.addField("item_title", "测试商品3");
        document.addField("item_price", 1000);
        // 把文档对象写入索引库
        solrServer.add(document);
        // 提交
        solrServer.commit();
    }

    @Test
    public void deleteDocumentById() throws Exception {
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/collection1");
        solrServer.deleteById("test001");
        // 提交
        solrServer.commit();
    }

    @Test
    public void deleteDocumentByQuery() throws Exception {
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/collection1");
        solrServer.deleteByQuery("item_title:测试商品3");
        solrServer.commit();
    }

    @Test
    public void searchDocumet() throws Exception {
        // 创建一个SolrServer对象
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/collection1");
        // 创建一个SolrQuery对象
        SolrQuery query = new SolrQuery();
        // 设置查询条件、过滤条件、分页条件、排序条件、高亮
        // query.set("q", "*:*");
        query.setQuery("手机");
        // 分页条件
        query.setStart(0);
        query.setRows(10);
        // 设置默认搜索域
        query.set("df", "item_keywords");
        // 设置高亮
        query.setHighlight(true);
        // 高亮显示的域
        query.addHighlightField("item_title");
        query.setHighlightSimplePre("<div>");
        query.setHighlightSimplePost("</div>");
        // 执行查询,得到一个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 = "";
            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_sell_point"));
            System.out.println(solrDocument.get("item_price"));
            System.out.println(solrDocument.get("item_image"));
            System.out.println(solrDocument.get("item_category_name"));
            System.out.println("=============================================");
        }

    }
}

3.3 applicationContext-solr.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/util
     http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    <!-- 单机版solr的连接 -->
    <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
        <constructor-arg name="baseURL" value="http://locahost:8080/solr/collection1"/>
    </bean>
        <!-- 集群版solr服务 -->
    <bean id="cloudSolrServer" class="org.apache.solr.client.solrj.impl.CloudSolrServer">
        <constructor-arg name="zkHost" value="192.168.25.154:2181,192.168.25.154:2182,192.168.25.154:2183"></constructor-arg>   
        <property name="defaultCollection" value="collection2"></property>
    </bean> 
</beans>

3.4 业务处理


    @Autowired
    private SolrServer solrServer;

    @Override
    public TaotaoResult importItemsToIndex() {
        try {
            //1、先查询所有商品数据

            //2、遍历商品数据添加到索引库
            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());
                document.addField("item_desc", searchItem.getItem_desc());
                //把文档写入索引库
                solrServer.add(document);
            }
            //3、提交
            solrServer.commit();
        } catch (Exception e) {
            e.printStackTrace();
            return TaotaoResult.build(500, "数据导入失败");
        }

    }

}

猜你喜欢

转载自blog.csdn.net/fd2025/article/details/80406228
今日推荐