Solr-4-SolrJ

Posted 健哥说编程

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Solr-4-SolrJ相关的知识,希望对你有一定的参考价值。

使用Java代码SolrJ快速实现索引的增删改查:

1、SolrJ

通过SolrJ可以实现对SolrCURD,但一般情况下,下进行更新,而是删除以后更插入。

 

1、导入SolrJ的依赖

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

 

 

 

2、保存、删除、查询功能

package cn.solr;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
/**
 * Solr7.5最新API
 */
public class Demo01_Solr {
    /**
     * 执行查询测试成功
     * 更多查询:
     * http://localhost:8983/solr/core1/select?fq=addr:%E5%B1%B1%E4%B8%9C%E4%B8%8A%E6%B5%B7&fq=id:*&q=*:*&rows=10&sort=id%20asc&start=10
     */
    @Test
    public void query() throws Exception {
        //创建SolrClient
        HttpSolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr")
                .withConnectionTimeout(3000)
                .withSocketTimeout(6000)
                .build();
        Map<String, String> params = new HashMap<>();
        params.put("q", "name:张三同学和赵五");
        SolrParams sp = new MapSolrParams(params);
        QueryResponse resp = client.query("core1", sp);
        SolrDocumentList results = resp.getResults();
        for (SolrDocument sd : results) {
            System.out.println(sd);
        }
        client.close();
    }

    /**
     * 保存一行数据
     */
    @Test
    public void insertDocument() throws Exception {
        HttpSolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr")
                .withConnectionTimeout(3000)
                .withSocketTimeout(6000)
                .build();
        //声明Input对象
        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id", "S001");
        doc.addField("name", "Jack");
        doc.addField("addr", "北京西城");
        //保存
        client.add("core1", doc);//指定core1CollectionDocument
        client.commit("core1");//提交生效
        client.close();
    }

    /**
     * 删除
     */
    @Test
    public void deleteById() throws Exception {
        HttpSolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr")
                .withConnectionTimeout(3000)
                .withSocketTimeout(6000)
                .build();
        UpdateResponse response = client.deleteById("core1", "eaf5c5cdc58211e8bbf674e543c746c3");
        int time = response.getQTime();
        long time2 = response.getElapsedTime();
        int status = response.getStatus();
        System.out.println("time:" + time + ",time2:" + time2 + ",status:" + status);
        client.commit("core1");
        client.close();
    }

    /**
     * deleteByQury
     * 根据某个删除删除数据
     * 以下只会删除第一页的数据
     */
    @Test
    public void deleteByQuery() throws Exception {
        HttpSolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr")
                .withConnectionTimeout(3000)
                .withSocketTimeout(6000)
                .build();
        //以下是删除所有姓张的记录
        UpdateResponse response = client.deleteByQuery("core1", "name:");
        NamedList<Object> namedList = response.getResponse();
        System.out.println("结果:\n" + namedList);

        response = client.commit("core1");
        System.out.println("结果2\n" + response);
        client.close();
    }

    /**
     * 另一种删除方式
     */
    @Test
    public void deleteByQuery2() throws Exception {
        HttpSolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr")
                .withConnectionTimeout(3000)
                .withSocketTimeout(6000)
                .build();
        UpdateRequest commit = new UpdateRequest();
        commit.deleteByQuery("name:");
        commit.setCommitWithin(1000);//i秒内提交
        UpdateResponse response = commit.process(client, "core1");
        System.out.println(">:"+response);
        client.close();
    }
}

3、高亮查询

package cn.solr;

import org.apache.solr.client.solrj.SolrQuery;
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.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
/**
 * 使用Solr进行高亮查询
 */
public class Demo02_SolrHightLight {
    private String url = "http://localhost:8983/solr";
    @Test
    public void queryHightLight() throws Exception {
        HttpSolrClient.Builder builder =
                new HttpSolrClient.Builder(url)
                        .withConnectionTimeout(1000)//创建连接超时时间
                        .withSocketTimeout(6000);//操作超时时间
        HttpSolrClient client = builder.build();
        //查询
        SolrQuery query = new SolrQuery("name:马六的同学是张三 and addr:中国泰安");
        query.addField("id");//?
        query.addField("name");
        query.addField("addr");
        query.setHighlight(true)//设置可以高亮
                .setHighlightSimplePre("<b>")
                .setHighlightSimplePost("</b>");
        query.setParam("hl.fl", "name,addr");//设置哪两个字段中的数据需要高亮
        //
        QueryResponse respose = client.query("core1", query);
        //获取高亮信息的结果,其中IDkey
        Map<String, Map<String, List<String>>> map = respose.getHighlighting();
        SolrDocumentList docs = respose.getResults();
        for (SolrDocument doc : docs) {
            String id = doc.get("id").toString();
            System.out.println("id>:" + id);
            Map<String,List<String>> mm = map.get(id);//根据id查询是否有高亮
            if(mm!=null){//说明有高亮信息
                if(mm.get("name")!=null){
                    String str =  mm.get("name").get(0);
                    System.out.println("name:"+str);
                }else{
                    System.out.println(doc.get("name"));
                }
                if(mm.get("addr")!=null){
                    String str = mm.get("addr").get(0);
                    System.out.println("addr:"+str);
                }else{
                    System.out.println(doc.get("addr"));
                }
            }else{
                System.out.println(doc.get("name"));
                System.out.println(doc.get("addr"));
            }
            System.out.println("---------------------------------");
        }
        client.close();
    }
}

结果:

id>:f538bf9dc58a11e8bbf674e543c746c3

name:<b></b><b>同学</b>的朋友

addr:<b>中国</b>山东省济南市<b>泰安</b>788

---------------------------------

id>:5e6fd515c4b511e8b27774e543c746c3

name:<b>张三同学</b>

山东济南

---------------------------------

id>:5e71c555c4b511e8b27774e543c746c3

name:张四<b>同学</b>

北京

---------------------------------

 

 


以上是关于Solr-4-SolrJ的主要内容,如果未能解决你的问题,请参考以下文章