分享知识-快乐自己:java代码 操作 solr

POM 文件:

<!-- solr客户端 -->
<dependency>
        <groupId>org.apache.solr</groupId>
        <artifactId>solr-solrj</artifactId>
        <version>4.10.3</version>
</dependency> 

JAVA 代码:

package com.gdbd.solrj;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * @Description: SolrJ 添加数据测试类
 * @Author: DGBD
 * @CreateDate: 2018/12/31 15:57
 * @UpdateUser: yc
 * @UpdateDate: 2018/12/31 15:57
 * @UpdateRemark: 修改内容
 * @博客地址: https://www.cnblogs.com/mlq2017/
 * @Version: 1.0
 */
public class TestSolrJ {

    public static void main(String[] args) {
        try {
            do {
                System.out.println("....请选择你的操作....");
                System.out.println("1):向 solr 索引库添加数据");
                System.out.println("2):查询 solr 索引库数据");
                System.out.println("3):修改 solr 索引库数据");
                System.out.println("4):删除 solr 索引库数据");
                System.out.println("5):根据 查询 删除 solr 索引库数据");
                System.out.println("请输入....");
                Scanner input = new Scanner(System.in);
                int num = input.nextInt();
                switch (num) {
                    case 1:
                        testAddDocument();
                        break;
                    case 2:
                        testselDocument();
                        break;
                    case 3:
                        break;
                    case 4:
                        testdelDocument();
                        break;
                    case 5:
                        testdelQueryDocument();
                        break;
                }
            } while (true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 向 solr 索引库添加数据
     * @throws Exception
     */
    public static void testAddDocument() throws Exception {
        //01、创建一个 SolrServer 对象。创建一个 HTTPSolrServer对象。需要指定 solr 服务的 url
        SolrServer solrServer = new HttpSolrServer("http://192.168.31.206:8080/solr/collection1");
        //02、创建一个文档对象SolrInputDocument
        SolrInputDocument document = new SolrInputDocument();
        //03、向文档中添加域,必须有 id 域,域的名称必须在 schema.xml
        document.addField("id", "123");
        document.addField("item_title", "测试商品标题2");
        document.addField("item_sell_point", "测试商品买点2");
        document.addField("item_price", 1000);
        document.addField("item_image", "测试商品图片2");
        document.addField("item_category_name", "测试商品分类名称2");
        document.addField("item_desc", "测试商品描述2");
        SolrInputDocument document1 = new SolrInputDocument();
        //03、向文档中添加域,必须有 id 域,域的名称必须在 schema.xml
        document1.addField("id", "test001");
        document1.addField("item_title", "测试商品标题1");
        document1.addField("item_sell_point", "测试商品买点1");
        document1.addField("item_price", 1000);
        document1.addField("item_image", "测试商品图片1");
        document1.addField("item_category_name", "测试商品分类名称1");
        document1.addField("item_desc", "测试商品描述1");
        //04、把文档对象写入索引库
        solrServer.add(document);
        solrServer.add(document1);
        solrServer.commit();
        System.out.println("成功插入...............................");
    }

    /***
     * 查询 solr 索引库数据
     *
     * 提示:查询所有(*:*)不能设置高亮显示
     *       分页不设置默认为(0-10)
     *       如果查询条件上没有指定在哪一个 业务域上搜索 则在默认搜索域中搜索
     *
     * @throws Exception
     */
    public static void testselDocument() throws Exception {
        //01、创建一个 SolrServer 对象。创建一个 HTTPSolrServer对象。需要指定 solr 服务的 url
        SolrServer solrServer = new HttpSolrServer("http://192.168.31.206:8080/solr/collection1");
        //02、创建一个 solrQuery 查询对象
        SolrQuery solrQuery = new SolrQuery();
        //设置查询条件:过滤条件、分页条件...
        solrQuery.set("q", "手机");
        //solrQuery.setQuery("*:*");

        //分页条件(从第 30 条开始查询,每页显示10 条)
        solrQuery.set("start", 0);//solrQuery.setStart();
        solrQuery.set("rows", 5);//solrQuery.setRows();

        //默认搜索域
        solrQuery.set("df", "item_keywords");

        //设置高亮
        solrQuery.set("hl", true);//solrQuery.setHighlight(true);

        //设置高亮显示域(对哪一个域进行 高亮显示:这里设置标题域为高亮)
        solrQuery.set("hl.fl", "item_title");//solrQuery.addHighlightField("item_title");

        //高亮显示前缀后缀
        solrQuery.set("hl.simple.pre", "<em>");//solrQuery.setHighlightSimplePre("<em>");
        solrQuery.set("hl.simple.post", "</em>");//solrQuery.setHighlightSimplePost("</em>");

        //03、执行查询(得到一个 Response 对象)
        QueryResponse response = solrServer.query(solrQuery);
        //04、取查询结果
        SolrDocumentList results = response.getResults();
        //05、取查询总记录数
        System.out.println("取查询总记录数:>>>>" + results.getNumFound());
        for (SolrDocument item : results) {
            System.out.println(item.get("id"));
            //06、取高亮显示
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            List<String> list = highlighting.get(item.get("id")).get("item_title");
            String title = "";
            if (list != null && list.size() > 0) {
                title = list.get(0);//获取高亮的信息
            } else {
                title = (String) item.get("item_title");//没有高亮信息 则显示默认的
            }
            System.out.println(title);
            System.out.println(item.get("item_sell_point"));
            System.out.println(item.get("item_price"));
            System.out.println(item.get("item_image"));
            System.out.println(item.get("item_category_name"));
            System.out.println(item.get("item_desc"));
            System.out.println("===========================================");
        }


    }

    /***
     * 修改 solr 索引库数据
     * @throws Exception
     */
    public static void testmodfyDocument() throws Exception {

    }

    /***
     * 根据 Id 删除 solr 索引库数据
     * @throws Exception
     */
    public static void testdelDocument() throws Exception {
        //01、创建一个 SolrServer 对象。创建一个 HTTPSolrServer对象。需要指定 solr 服务的 url
        SolrServer solrServer = new HttpSolrServer("http://192.168.31.206:8080/solr/collection1");
        //根据 Id 删除 solr 中的数据
        solrServer.deleteById("test001");
        solrServer.commit();
    }

    /***
     * 根据 查询 删除 solr 索引库数据
     * @throws Exception
     */
    public static void testdelQueryDocument() throws Exception {
        //01、创建一个 SolrServer 对象。创建一个 HTTPSolrServer对象。需要指定 solr 服务的 url
        SolrServer solrServer = new HttpSolrServer("http://192.168.31.206:8080/solr/collection1");
        //根据 Id 删除 solr 中的数据
        solrServer.deleteByQuery("*:*");
        solrServer.commit();
    }
}

===========配置文件:

<?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:context="http://www.springframework.org/schema/context"
       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
">

    <!--扫描-->
    <context:component-scan base-package="com.gdbd"/>

    <!--配置单机版solr的连接-->
    <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrClient">
        <constructor-arg name="baseURL" value="http://192.168.31.212:8080/solr/collection1"/>
    </bean>

    <!--配置集群版solr的连接-->
    <bean id="cloudSolrServer" class="org.apache.solr.client.solrj.impl.CloudSolrClient">
        <constructor-arg name="zkHost" value="192.168.31.209:2181,192.168.209:2182,192.168.31.209:2183"/>
        <property name="defaultCollection" value="collection2"/>
    </bean>

</beans>

pojo: 

package com.gdbd.pojo;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import org.apache.solr.client.solrj.beans.Field;

/**
 * @Description: 测试类
 * @Author: DGBD
 * @CreateDate: 2019/1/10 10:04
 * @UpdateUser: yc
 * @UpdateDate: 2019/1/10 10:04
 * @UpdateRemark: 修改内容
 * @博客地址: https://www.cnblogs.com/mlq2017/
 * @Version: 1.0
 */
public class Passage {

    // 用于标明solr索引的id,需要放在字段上
    @Field("id")
    private String id;
    @Field("content")
    private String content;
    @Field("name")
    private String name;
    @Field("title")
    private String title;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    .......
}

注解单机版操作:

package com.gdbd.solr;

import com.gdbd.pojo.Passage;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description: solr 单机测试类
 * @Author: DGBD
 * @CreateDate: 2019/1/10 10:14
 * @UpdateUser: yc
 * @UpdateDate: 2019/1/10 10:14
 * @UpdateRemark: 修改内容
 * @博客地址: https://www.cnblogs.com/mlq2017/
 * @Version: 1.0
 */
public class SolrTest {

    private HttpSolrClient solrServer = null;

    @Before
    public void before() {
        //加载配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-solr.xml");
        //获取对象
        solrServer = (HttpSolrClient) context.getBean("httpSolrServer");
    }

    /***
     * 添加信息
     * @throws IOException
     * @throws SolrServerException
     */
    @Test
    public void demo() throws IOException, SolrServerException {
        for (int i = 0; i < 5; i++) {
            //伪造添加的信息
            Passage passage = new Passage("456" + i, "测试数据" + i, "MLQ" + i, "你好不好" + i);
            //向solr中添加数据
            solrServer.addBean(passage);
        }
        //提交
        solrServer.commit();
    }

    /***
     * 查询数据
     */
    @Test
    public void sel() throws IOException, SolrServerException {
        //创建一个 solrQuery 查询对象
        SolrQuery solrQuery = new SolrQuery();
        //设置查询条件:过滤条件、分页条件...
        solrQuery.setQuery("name:MLQ");
        /***
         * 分页条件(从第 30 条开始查询,每页显示10 条)
         * solrQuery.setStart();olrQuery.setRows();
         */
        solrQuery.set("start", 0);
        solrQuery.set("rows", 5);
        //默认搜索域
        solrQuery.set("df", "name");
        /***
         * 设置开启高亮
         * solrQuery.setHighlight(true);
         */
        solrQuery.set("hl", true);
        /***
         * 设置高亮显示域(对哪一个域进行 高亮显示:这里设置标题域为高亮)
         * solrQuery.addHighlightField("item_title");
         */
        solrQuery.set("hl.fl", "name");

        /***
         * 高亮显示前缀后缀
         * solrQuery.setHighlightSimplePre("<em>");
         * solrQuery.setHighlightSimplePost("</em>");
         */
        solrQuery.set("hl.simple.pre", "<em>");
        solrQuery.set("hl.simple.post", "</em>");

        //执行查询(得到一个 Response 对象)
        QueryResponse response = solrServer.query(solrQuery);
        //取查询结果
        SolrDocumentList results = response.getResults();
        //取查询总记录数
        System.out.println("取查询总记录数:>>>>" + results.getNumFound());
        for (SolrDocument item : results) {
            System.out.println("id--->" + item.get("id"));
            //06、取高亮显示
            String name = null;
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            List<String> list = highlighting.get(item.get("id")).get("name");
            if (list != null && list.size() > 0) {
                name = list.get(0);//获取高亮的信息
            } else {
                name = (String) item.get("name");//没有高亮信息 则显示默认的
            }
            System.out.println("name--->" +name);
            System.out.println("content--->" + item.get("content"));
            System.out.println("title--->" + item.get("title"));
            System.out.println("===========================================");
        }
    }
    /***
     * 删除所有数据
     * @throws Exception
     */
    @Test
    public void testdelQueryDocument() throws Exception {
        solrServer.deleteByQuery("*:*");
        solrServer.commit();
    }
    @After
    public void after() throws IOException {
        solrServer.close();
    }
}

注解集群版操作:

package com.gdbd.solr;

import com.gdbd.pojo.Passage;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

/**
 * @Description: solr 集群测试
 * @Author: DGBD
 * @CreateDate: 2019/1/11 8:45
 * @UpdateUser: yc
 * @UpdateDate: 2019/1/11 8:45
 * @UpdateRemark: 修改内容
 * @博客地址: https://www.cnblogs.com/mlq2017/
 * @Version: 1.0
 */
public class SolrCloudTest {

    private CloudSolrClient solrServer = null;

    @Before
    public void before() {
        //加载配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-solr.xml");
        //获取对象
        solrServer = (CloudSolrClient) context.getBean("cloudSolrServer");
    }
    @Test
    public void demo() throws IOException, SolrServerException {
        /***
         * 创建cloudSolrServer,构造方法中指定zookeeper的地址列表
         * CloudSolrServer solrServer = new CloudSolrServer("192.168.55.3:2181,192.168.55.3:2182,192.168.55.3:2183");
         * 需要设置默认collection
         * solrServer.setDefaultCollection("collection2");
         */
        //伪造添加的信息
        for (int i = 0; i < 5; i++) {
            //伪造添加的信息
            Passage passage = new Passage("456" + i, "测试数据" + i, "MLQ" + i, "你好不好" + i);
            //向solr中添加数据
            solrServer.addBean(passage);
        }
        //提交
        solrServer.commit();
    }

    /***
     * 删除所有数据
     * @throws Exception
     */
    @Test
    public void testdelQueryDocument() throws Exception {
        solrServer.deleteByQuery("*:*");
        solrServer.commit();
    }

    @After
    public void after() throws IOException {
        solrServer.close();
    }
}

 

posted @ 2019-01-01 14:53  GDBD  阅读(269)  评论(0编辑  收藏  举报