美文网首页
使用Solrj 来管理solr服务

使用Solrj 来管理solr服务

作者: 泛空秋慕 | 来源:发表于2018-06-03 21:58 被阅读0次

1. 使用solrj来管理索引库

  使用SolrJ可以实现索引库的增删改查操作。

1.1 添加文档

  第一步:把solrJ的jar包添加到工程中。
  第二步:创建一个SolrServer,使用HttpSolrServer创建对象。
  第三步:创建一个文档对象SolrInputDocument对象。
  第四步:向文档中添加域。必须有id域,域的名称必须在schema.xml中定义。
  第五步:把文档添加到索引库中。
  第六步:提交。

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

1.2. 删除文档

1.2.1. 根据id删除

  第一步:创建一个SolrServer对象。
  第二步:调用SolrServer对象的根据id删除的方法。
  第三步:提交。

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

1.3. 查询索引库

查询步骤:
  第一步:创建一个SolrServer对象
  第二步:创建一个SolrQuery对象。
  第三步:向SolrQuery中添加查询条件、过滤条件。。。
  第四步:执行查询。得到一个Response对象。
  第五步:取查询结果。
  第六步:遍历结果并打印。

1.3.1. 简单查询
   @Test
    public void queryDocument() throws Exception {
        // 第一步:创建一个SolrServer对象
        SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/solr");
        // 第二步:创建一个SolrQuery对象。
        SolrQuery query = new SolrQuery();
        // 第三步:向SolrQuery中添加查询条件、过滤条件。。。
        query.setQuery("*:*");
        // 第四步:执行查询。得到一个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"));
            System.out.println(solrDocument.get("item_title"));
            System.out.println(solrDocument.get("item_price"));
        }
    }
1.3.2. 带高亮显示
    @Test
    public void queryDocumentWithHighLighting() throws Exception {
        // 第一步:创建一个SolrServer对象
        SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/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"));
        }
    }

2. 把数据导入到索引库中

2.1. 功能分析

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

2.2 数据来自数据库,查询SQL如下

SELECT
    a.id,
    a.title,
    a.sell_point,
    a.price,
    a.image,
    b. NAME category_name,
    c.item_desc
FROM
    tb_item a
JOIN tb_item_cat b ON a.cid = b.id
JOIN tb_item_desc c ON a.id = c.item_id
WHERE
    a.`status` = 1

2.2 pojo 对应SQL字段和solr中定义的域

public class SearchItem implements Serializable{

    private String id;
    private String title;
    private String sell_point;
    private long price;
    private String image;
    private String category_name;
    private String item_desc;
}

2.3 Dao

接口定义:

public interface SearchItemMapper {

    List<SearchItem> getItemList();
}

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.SearchItemMapper" >

    <select id="getItemList" resultType="com.hsun.common.pojo.SearchItem">
        SELECT
            a.id,
            a.title,
            a.sell_point,
            a.price,
            a.image,
            b. NAME category_name,
            c.item_desc
        FROM
            tb_item a
        JOIN tb_item_cat b ON a.cid = b.id
        JOIN tb_item_desc c ON a.id = c.item_id
        WHERE
            a.status = 1
    </select>
</mapper>

2.4 Service

在 applicationContext-solr.xml中配置SolrServer对象:


applicationContext-solr.xml

Service代码编写:

@Service
public class SearchItemServiceImpl implements SearchItemService {

    @Autowired
    private SearchItemMapper searchItemMapper;
    @Autowired
    private SolrServer solrServer;
    
    @Override
    public Msg importAllItems() throws Exception{
        // 1、查询所有商品数据。
        List<SearchItem> itemList = searchItemMapper.getItemList();
        // 2、创建一个SolrServer对象。
        // 3、为每个商品创建一个SolrInputDocument对象。
        for (SearchItem searchItem : itemList) {
            SolrInputDocument document = new SolrInputDocument();
            // 4、为文档添加域
            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());
            // 5、向索引库中添加文档。
            solrServer.add(document);
        }
        //提交修改
        solrServer.commit();
        // 6、返回Msg。
        return Msg.ok();
    }

}

2.5 使用Dubbo发布服务

<?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:dubbo="http://code.alibabatech.com/schema/dubbo" 
    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/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
    
    <!-- 配置包扫描器,扫描所有带@Service注解的类 -->
    <context:component-scan base-package="com.hsun.search.service"/>
    
    <!-- 发布dubbo服务 -->
    <!-- 提供方应用信息,用于计算依赖关系 -->
    <dubbo:application name="jd-search" />
    <!-- 注册中心的地址 -->
    <dubbo:registry protocol="zookeeper" address="192.168.25.167:2181" />
    <!-- 用dubbo协议在20880端口暴露服务 -->
    <dubbo:protocol name="dubbo" port="20882" />
    <!-- 声明需要暴露的服务接口 -->
    <dubbo:service interface="com.hsun.search.service.SearchItemService" ref="searchItemServiceImpl" timeout="300000"/>
</beans>

pom文件中添加的依赖如下:

        <!-- dubbo相关的jar包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>netty</artifactId>
                    <groupId>org.jboss.netty</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
        </dependency>
        <!-- 添加solrJ的依赖 -->
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
        </dependency>
    </dependencies>
        
    <!-- 避免maven打包时,将配置文件漏掉 -->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

2.6 在表现层工程中引入dubbo服务来实现web界面操作将数据从数据库导入solr索引库

2.6.1 表现层 pom文件
<!-- dubbo相关的jar包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>netty</artifactId>
                    <groupId>org.jboss.netty</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <path>/</path>
                    <port>8085</port>
                </configuration>
            </plugin>
        </plugins>
    </build>
2.6.2 引用服务

springmvc.xml

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

    <!-- 加载属性文件 -->
    <context:property-placeholder location="classpath:resource/resource.properties"/>
    <!-- 配置注解驱动 -->
    <mvc:annotation-driven />
    <!-- 视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 配置包扫描器,扫描@Controller注解的类 -->
    <context:component-scan base-package="com.jd.search.controller"/>
    
    <!-- 引用dubbo服务 -->
    <dubbo:application name="jd-search-web"/>
    <dubbo:registry protocol="zookeeper" address="192.168.25.167:2181"/>    
    <dubbo:reference interface="com.hsun.search.service.SearchItemService" id="searchItemService" /> 
</beans>      

2.6.3. Controller

请求的url:/index/importall
参数:无
返回值:json数据。Msg

@Controller
public class SearchItemController {

    @Autowired
    private SearchItemService searchItemService;
    
    @RequestMapping("/index/importall")
    @ResponseBody
    public Msg importAllItems() {
        try {
            Msg result = searchItemService.importAllItems();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.build(500, "导入数据失败");
        }
    }
}

2.6.4 页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<div>
    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="importAll()">一键导入商品数据到索引库</a>
</div>
<script type="text/javascript">

function importAll() {
    $.post("/index/importall",null,function(data){
        if (data.status==200) {
            $.messager.alert('提示','商品数据导入成功!');
        } else {
            
            $.messager.alert('提示','商品数据导入失败!');
        }
        
    }); 
}
</script>

相关文章

网友评论

      本文标题:使用Solrj 来管理solr服务

      本文链接:https://www.haomeiwen.com/subject/fhxssftx.html