04_solr7.3之solrJ7.3的使用

04_solr7.3之solrJ7.3的使用

SolrJ is an API that makes it easy for Java applications to talk to Solr. SolrJ hides a lot of the details of connecting to Solr and allows your application to interact with Solr with simple high-level methods.

The center of SolrJ is the org.apache.solr.client.solrj package, which contains just five main classes. Begin by creating a SolrClient, which represents the Solr instance you want to use. Then send SolrRequests or SolrQuerys and get back SolrResponses.

SolrClient is abstract, so to connect to a remote Solr instance, you’ll actually create an instance of either HttpSolrClient, or CloudSolrClient. Both communicate with Solr via HTTP, the difference is that HttpSolrClient is configured using an explicit Solr URL, while CloudSolrClient is configured using the zkHost String for a SolrCloud cluster.

Single node Solr client

String urlString = "http://localhost:8983/solr/techproducts";
SolrClient solr = new HttpSolrClient.Builder(urlString).build();

SolrCloud client

// Using a ZK Host String
String zkHostString = "zkServerA:2181,zkServerB:2181,zkServerC:2181/solr";
SolrClient solr = new CloudSolrClient.Builder().withZkHost(zkHostString).build();

// Using already running Solr nodes
SolrClient solr = new CloudSolrClient.Builder().withSolrUrl("http://localhost:8983/solr").build();

以上内容来自solr官网。

一、构建和运行SolrJ应用程序

    对于用Maven构建的项目, 
pom.xml配置:

<dependency>
  <groupId>org.apache.solr</groupId>
  <artifactId>solr-solrj</artifactId>
  <version>7.3.1</version>
</dependency>

如果不用maven构建项目,只需要将
solr-solrj-7.3.1.jar 和 dist/solrj-lib目录中的依赖包加入到项目中即可

04_solr7.3之solrJ7.3的使用

二、solr7 API

 在solr5系之后跟solr4最大的区别是被发布成了一个独立的应用。而不再需要tomcat等容器。在其内部集成了jetty服务器,他可以通过bin目录的脚本直接运行启动。solr5有两种运行模式,独立模式和云模式,独立模式是以core来管理,云模式是以collection来管理。

  SolrClient是一个抽象类,下边有很多被实现的子类,

        HttpSolrClient是通用客户端。 可以与一个Solr节点直接通信。),  

        LBHttpSolrClient,CloudSolrClient,ConcurrentUpdateSolrClient

 HttpSolrClient的创建需要用户指定一个或多个Solr基础URL,然后客户端使用Solr发送HTTP请求。

  1. 一个URL的路径指向一个特定的core/collection(例如, http://host:8983/solr/core1 )

  2. 一个URL指向根Solr路径(例如, http://host:8983/solr )。 当没有指定core/collection的基URL,可以请求任何core/collection,但受影响的core/collection必须指定collection的所有请求。

一般来说,如果你的 SolrClient 只会被用在一个core/collection,包括实体的路径是最方便的。

三、创建工程

创建个maven工程(普通的java工程都可以不过需要自己导包),添加依赖如下:



创建Test类,测试SolrJ相关API

1. 添加\修改索引

/*
    根据id(唯一约束)域来更新Document的内容,如果根据id值搜索不到id域则会执行添加操作,如果找到则更新。
     */
    @Test
    public void addDocument() throws IOException, SolrServerException {
        /*
        步骤
        1、创建	HttpSolrClient对象,通过它和Solr服务器建立连接。
        2、	创建SolrInputDocument对象,然后通过它来添加域。
        3、	通过HttpSolrClient对象将SolrInputDocument添加到索引库。
        4、	提交。
         */
        final String solrUrl = "http://localhost:8983/solr/test_Core";
        //创建solrClient同时指定超时时间,不指定走默认配置
        HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
                .withConnectionTimeout(10000)
                .withSocketTimeout(60000)
                .build();
        // 2、 创建SolrInputDocument对象,然后通过它来添加域。
        SolrInputDocument document = new SolrInputDocument();
        // 第一个参数:域的名称,域的名称必须是在schema.xml中定义的
        // 第二个参数:域的值
        // 注意:id的域不能少
        document.addField("id", "c0001");
        document.addField("title_ik", "使用solrJ添加的文档");
        document.addField("content_ik", "文档的内容");
        document.addField("product_name", "商品名称");
        // 3、 通过HttpSolrServer对象将SolrInputDocument添加到索引库。
        solrServer.add(document);
        // 4、 提交。
        solrServer.commit();
    }

不同solr版本solrj 的创建方式有所不同

//solr4创建方式
//SolrServer solrServer = new HttpSolrServer("http://127.0.0.1:8983/solr");  
//solr5创建方式,在url中指定core名称:core1
//HttpSolrClient solrServer=new HttpSolrClient("http://127.0.0.1:8983/solr/core1");
//solr7创建方式,在url中指定core名称:core1
HttpSolrClient solrServer= new HttpSolrClient.Builder("http://127.0.0.1:8983/solr/core1").build();

查询测试

04_solr7.3之solrJ7.3的使用

删除索引( 根据ID删除)

  //根据ID删除索引
    @ Test
    public void deleteDocument() throws IOException, SolrServerException {
        final String solrUrl = "http://localhost:8983/solr/test_Core";
        //创建solrClient同时指定超时时间,不指定走默认配置
        HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
                .withConnectionTimeout(10000)
                .withSocketTimeout(60000)
                .build();
        //根据ID删除
        solrServer.deleteById("c0001");
        //提交
        solrServer.commit();
    }
 查询测试

04_solr7.3之solrJ7.3的使用

根据条件删除

//根据条件删除
    @Test
    public void deleteDocumentByQuery() throws Exception {

        final String solrUrl = "http://localhost:8983/solr/test_Core";
        //创建solrClient同时指定超时时间,不指定走默认配置
        // 1、 创建HttpSolrClient对象,通过它和Solr服务器建立连接。
        // 参数:solrUrl服务器的访问地址
        HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
                .withConnectionTimeout(10000)
                .withSocketTimeout(60000)
                .build();
        // 根据ID删除
        solrServer.deleteByQuery("id:c0001");
        // 全部删除
        // server.deleteByQuery("*:*");
        // 提交
        solrServer.commit();
    }

 简单查询

/**
     * 简单查询
     * @throws Exception
     */
    @Test
    public void queryIndex() throws Exception {
        final String solrUrl = "http://localhost:8983/solr/test_Core";
        //创建solrClient同时指定超时时间,不指定走默认配置
        // 1、 创建HttpSolrClient对象,通过它和Solr服务器建立连接。
        // 参数:solrUrl服务器的访问地址
        HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
                .withConnectionTimeout(10000)
                .withSocketTimeout(60000)
                .build();

        // 创建SolrQuery对象
        SolrQuery query = new SolrQuery();
        // 设置查询条件,名称“q”是固定的且必须 的
        query.set("q", "id:2");

        // 调用server的查询方法,查询索引库
        QueryResponse response = solrServer.query(query);

        // 查询结果
        SolrDocumentList results = response.getResults();

        // 查询结果总数
        long cnt = results.getNumFound();
        System.out.println("查询结果总数:" + cnt);

        for (SolrDocument solrDocument : results) {
            System.out.println(solrDocument.get("id"));
            System.out.println(solrDocument.get("product_name"));
            System.out.println(solrDocument.get("product_sale_price"));
            System.out.println(solrDocument.get("product_sort_name"));
            System.out.println(solrDocument.get("product_pic"));

        }
    }

复杂查询

复杂查询中包括高亮的处理

/**
     * 复杂查询  包括高亮显示
     * @throws Exception
     */
    @Test
    public void queryIndex2() throws Exception {
        final String solrUrl = "http://localhost:8983/solr/test_Core";
        //创建solrClient同时指定超时时间,不指定走默认配置
        // 1、 创建HttpSolrClient对象,通过它和Solr服务器建立连接。
        // 参数:solrUrl服务器的访问地址
        HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
                .withConnectionTimeout(10000)
                .withSocketTimeout(60000)
                .build();
        // 创建SolrQuery对象
        SolrQuery query = new SolrQuery();

        // 设置查询条件
        query.setQuery("钻石");
        // 设置过滤条件
        query.setFilterQueries("product_sort_name:幽默杂货");
        // 设置排序
        query.setSort("product_sale_price",SolrQuery.ORDER.desc);
        // 设置分页信息
        query.setStart(0);
        query.setRows(10);

        // 设置显得的域的列表
        query.setFields("id", "product_name", "product_sale_price",
                "product_sort_name", "product_pic");

        // 设置默认搜索域
        query.set("df", "product_name");

        // 设置高亮
        query.setHighlight(true);
        query.addHighlightField("product_name");
        query.setHighlightSimplePre("<em>");
        query.setHighlightSimplePost("</em>");

        // 调用server的查询方法,查询索引库
        QueryResponse response = solrServer.query(query);

        // 查询结果
        SolrDocumentList results = response.getResults();

        // 查询结果总数
        long cnt = results.getNumFound();
        System.out.println("查询结果总数:" + cnt);

        for (SolrDocument solrDocument : results) {
            System.out.println(solrDocument.get("id"));

            String productName = (String) solrDocument.get("product_name");

            //获取高亮列表
            Map<String, Map<String, List<String>>> highlighting = response
                    .getHighlighting();
            //获得本文档的高亮信息
            List<String> list = highlighting.get(solrDocument.get("id")).get(
                    "product_name");
            //如果有高亮,则把商品名称赋值为有高亮的那个名称
            if (list != null) {
                productName = list.get(0);
            }

            System.out.println(productName);
            System.out.println(solrDocument.get("product_sale_price"));
            System.out.println(solrDocument.get("product_sort_name"));
            System.out.println(solrDocument.get("product_pic"));

        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/111280.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • AppFabric 版本区分

    AppFabric 版本区分目前CSDN上可以下载到的AppFabric有两个版本:1,WindowsServerAppFabricSetup_x64_6.1.exe,2010/12/3发布的,不推荐使用,Win10安装后IIS启动失败,网址:https://www.microsoft.com/zh-cn/download/details.aspx?id=158482,Microsoft…

    2022年10月16日
    5
  • 软件著作权源代码要求_安卓著作权源码格式要求

    软件著作权源代码要求_安卓著作权源码格式要求摘要:对软件著作权申请都要提供软件60页的源代码,超出60页的应至少提交最前和最后的各连续30页源程序文本,不足60页的,应当将所有的源程序文本全部提交,程序要有比较鲜明的开始段落1.代码语法要求对软件著作权提交源代码是提供原始的代码(不是关键代码)语法上要求代码具备完整性。而且要求提交者提供的源代码是对应的代码文件的最原始文本信息。例如:C++代码应该是以include之类作为开头,而不能以函数…

    2022年9月22日
    3
  • Eclipse汉化教程详细[通俗易懂]

    Eclipse汉化教程详细[通俗易懂]eclipse汉化包下载建议从:www.vipkes.cn或www.tkres.cn(恬恪学习网)下载,与此教程配套的资料。或从其它渠道下载。 下载完成后,解压压缩包: 打开压缩包后,可看到里面有个“eclipse”的文件夹,再进入该文件夹,可以看到如下两个文件夹:4.复制这两个文件夹,并找到eclipse安装根目录,如果不知道在哪里,请在桌面鼠标右键—》属性—》快捷方式—》打开文件所在位置即可。在eclipse安装目录下,找到以下dropins文件,双…

    2022年6月6日
    50
  • 什么是UDP攻击_机器人打电话营销效果

    什么是UDP攻击_机器人打电话营销效果UDP协议UDP是一个简单的面向数据报的运输层协议,也是最常见的作为流量攻击最多的一种协议,需要用到UDP的主要都是视频通讯,枪战类实时通讯的游戏类。UDP不提供可靠性,它只是把应用程序传给IP层的数据报发送出去,但并不保证它们能到达目的地。由于UDP传输数据前传输数据之前源端和终端不建立连接,且没有超时重发等机制,故而传输速度很快。UDP攻击UDP攻击是DDoS攻击的一种,是典型的流量型攻击。就好比学校中午放学时的食堂,学生大量飞奔食堂,但食堂窗口就那么多,学生数量太多,就只能挤在窗口前等待。

    2022年10月2日
    5
  • GO分析-GOseq的使用教程[通俗易懂]

    GO分析-GOseq的使用教程[通俗易懂]GOseq的介绍GOseq是一个R包,用于寻找GOterms,即基因富集分析。此方法基于Walleniusnon-centralhyper-geometricdistribution。相对

    2022年8月6日
    10
  • 时限调度算法给出的调度顺序_时间片轮转法进行进程调度

    时限调度算法给出的调度顺序_时间片轮转法进行进程调度调度算法-时间轮一.背景在我们的业务场景中,经常会使用到定时任务功能,比如定时发送消息,定时执行数据同步,比如之前的文章介绍的分布式事务中的本地事务表方式的解决方案等等,特别是在现在大数据量和分布式服务环境下,定时任务调度越来越频繁,所以对应的定时任务调度的算法实现也越来越完善。在之前的单机环境下,我们可以使用ScheduledThreadPool起一个延迟任务线程池,定时的执行任务,又或者使用spring提供的@Schedule注解配合上cron表达式开启一个定时任务,又或者是lin

    2022年9月28日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号