关于Solr6.0中solrj使用简单例子

solr6.0的solrJ接口有部分变化,下面列出了简单的使用实例,有需要的朋友可以参考下。

package com.ailk.solr6;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

//import org.apache.log4j.Logger;
//import org.apache.log4j.PropertyConfigurator;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
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;

public class SimpleSorl {
    private String solrUrl;
    private SolrClient client;
    private int num = 10;
    private String zkUrl;
    private String collectionName;

    private SolrClient createNewSolrClient() {
        try {
            System.out.println("server address:" + solrUrl);
            HttpSolrClient client = new HttpSolrClient(solrUrl);
            client.setConnectionTimeout(30000);
            client.setDefaultMaxConnectionsPerHost(100);
            client.setMaxTotalConnections(100);
            client.setSoTimeout(30000);
            return client;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    private SolrClient createCouldSolrClient() {
        CloudSolrClient client = new CloudSolrClient(zkUrl);
        client.setZkClientTimeout(30000);
        client.setZkConnectTimeout(50000);
        client.setDefaultCollection(collectionName);
        return client;
    }

    public void close() {
        try {
            client.close();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public SimpleSorl(String solrUrl, int num) {
        this.solrUrl = solrUrl;
        this.client = createNewSolrClient();
        this.num = num;
    }

    public SimpleSorl(String zkUrl, int num, String collection) {
        this.zkUrl = zkUrl;
        this.num = num;
        collectionName = collection;
        this.client = createCouldSolrClient();
    }

    public void createDocs() {
        System.out.println("======================add doc ===================");
        Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
        for (int i = 1; i <= num; i++) {
            SolrInputDocument doc1 = new SolrInputDocument();
            doc1.addField("id", UUID.randomUUID().toString(), 1.0f);
            doc1.addField("name", "bean");
            doc1.addField("equIP_s", "192.168.2.104");
            doc1.addField("level_s", "4");
            doc1.addField("collectPro_s", "ffffffffffffffffffffjajajajajajdddddddddd");
            doc1.addField("sourceType_s", "miaohqaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            doc1.addField("filePath_s", "/home/xxxx/test");
            doc1.addField("filename_s", "zhonggggmaiaiadadadddddddddddddddddddddddddd");//            doc1.addField("_route_", "shard1");
            docs.add(doc1);
        }
        try {
            UpdateResponse rsp = client.add(docs);
            System.out
                    .println("Add doc size" + docs.size() + " result:" + rsp.getStatus() + " Qtime:" + rsp.getQTime());

            UpdateResponse rspcommit = client.commit();
            System.out.println("commit doc to index" + " result:" + rsp.getStatus() + " Qtime:" + rsp.getQTime());

        } catch (SolrServerException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void queryDocs() {
        SolrQuery params = new SolrQuery();
        System.out.println("======================query===================");
        params.set("q", "addparam_s:*");
        params.set("start", 0);
        params.set("rows", 5);
        params.set("sort", "accesstime_s desc");

        try {
            QueryResponse rsp = client.query(params);
            SolrDocumentList docs = rsp.getResults();
            System.out.println("查询内容:" + params);
            System.out.println("文档数量:" + docs.getNumFound());
            System.out.println("查询花费时间:" + rsp.getQTime());

            System.out.println("------query data:------");
            for (SolrDocument doc : docs) {
                // 多值查询
                @SuppressWarnings("unchecked")
                List<String> collectTime = (List<String>) doc.getFieldValue("collectTime");
                String clientmac_s = (String) doc.getFieldValue("clientmac_s");
                System.out.println("collectTime:" + collectTime + "\t clientmac_s:" + clientmac_s);
            }
            System.out.println("-----------------------");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void deleteById(String id) {
        System.out.println("======================deleteById ===================");
        try {
            UpdateResponse rsp = client.deleteById(id);
            client.commit();
            System.out.println("delete id:" + id + " result:" + rsp.getStatus() + " Qtime:" + rsp.getQTime());
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
    }

    public void deleteByQuery(String queryCon) {
        System.out.println("======================deleteByQuery ===================");
        UpdateResponse rsp;

        try {
            UpdateRequest commit = new UpdateRequest();
            commit.deleteByQuery(queryCon);
            commit.setCommitWithin(5000);
            commit.process(client);
            System.out.println("url:"+commit.getPath()+"\t xml:"+commit.getXML()+" method:"+commit.getMethod());
//            rsp = client.deleteByQuery(queryCon);
//            client.commit();
//            System.out.println("delete query:" + queryCon + " result:" + rsp.getStatus() + " Qtime:" + rsp.getQTime());
        } catch (SolrServerException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void updateField(String id,String fieldName, Object fieldValue) {
        System.out.println("======================updateField ===================");
        HashMap<String, Object> oper = new HashMap<String, Object>();
//        多值更新方法
//        List<String> mulitValues = new ArrayList<String>();
//        mulitValues.add(fieldName);
//        mulitValues.add((String)fieldValue);
        oper.put("set", fieldValue);

        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id", id);
        doc.addField(fieldName, oper);
        try {
            UpdateResponse rsp = client.add(doc);
            System.out.println("update doc id" + id + " result:" + rsp.getStatus() + " Qtime:" + rsp.getQTime());
            UpdateResponse rspCommit = client.commit();
            System.out.println("commit doc to index" + " result:" + rspCommit.getStatus() + " Qtime:" + rspCommit.getQTime());

        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String args[]) {
        String url = "http://127.0.0.1:8983/solr/test201606";
        String zkUrl = "127.0.0.1:9983";
//        PropertyConfigurator.configure("./etc/log4j.properties");
        SimpleSorl ss = new SimpleSorl(url, 2);
        SimpleSorl sc = new SimpleSorl(zkUrl, 2, "test201607");
        // 添加文档
        sc.createDocs();

        // 删除文档
//        sc.deleteById("00cda454-bd3d-4945-814f-afa7110dcd21");
         sc.deleteByQuery("name:bean");

        //更新文档
        sc.updateField("bd67564f-4939-4de1-9a83-3483ebbbbbee", "name", "1233313131313");

        sc.close();

        // 查询文档
        ss.queryDocs();
        ss.close();

    }

}
时间: 2024-10-10 01:11:20

关于Solr6.0中solrj使用简单例子的相关文章

Oracle中的存储过程简单例子

---创建表 create table TESTTABLE ( id1  VARCHAR2(12), name VARCHAR2(32) ) select t.id1,t.name from TESTTABLE t insert into TESTTABLE (ID1, NAME) values ('1', 'zhangsan'); insert into TESTTABLE (ID1, NAME) values ('2', 'lisi'); insert into TESTTABLE (ID1

Java中死锁的简单例子及其避免

死锁:当一个线程永远地持有一个锁,并且其他线程都尝试获得这个锁时,那么它们将永远被阻塞.比如,线程1已经持有了A锁并想要获得B锁的同时,线程2持有B锁并尝试获取A锁,那么这两个线程将永远地等待下去. 我们来看一个死锁的简单例子: 1 public class DeadLockTest 2 { 3 private static Object A = new Object(), B = new Object(); 4 5 public static void main(String[] args)

jsp中使用javabean简单例子

在JSP中使用JavaBean以后,可以实现HTML代码和Java代码的分离,是JSp更易于开发和维护.因此JavaBean成了JSP程序员必备的利器.虽然javaBean是java类,但是它也有自己的一些特性(1)JavaBean是一个public类(2)JavaBean 有一个不带参数的构造方法(3)JavaBean中的属性通过get和set方法进行操作 例如:定义个CircleArea的JavaBean用于封装圆面积的计算逻辑,以后凡是用到圆面积的计算方法均可使用该JavaBean来完成,

Visual C++ 6.0中if的简单用法

1 # include<stdio.h> 2 int main (void) 3 { 4 if (3 > 2) 5 printf("AAAA"); 6 printf("BBBB"); 7 return 0; 8 } 9 //此时结果是,输出AAAA 和 BBBB,因为if只能控制一个语句 上面的第4行和第五行是一个语句,if只能控制一个语句,所以后面的BBBB不归if管,所以BBBB要输出来 1 # include<stdio.h> 2

数据库中算式的简单例子

后缀表达式是遇到符号时,取栈顶元素进行计算,并将结果再次压入栈顶.9 2 3 + - 10 2 / - 计算过程如下:9 2 3 入栈遇到 + 号,取出 2 3 相加,并将结果入栈,结果为9 5又遇到 - 号,同理,此时的栈为:4再入 10 2, 栈为:4 10 2遇到 / 号,栈变更为:4 5再遇到 - 号,栈变更为:-1后缀表达式结束,所以最终结果为 -1该后缀表达式还原成中缀表达式为:9 - (2 + 3) - 10 / 2

我与solr(六)--solr6.0配置中文分词器IK Analyzer

转自:http://blog.csdn.net/linzhiqiang0316/article/details/51554217,表示感谢. 由于前面没有设置分词器,以至于查询的结果出入比较大,并且无法进行正确的高亮显示.现在配置一下分词器来解决相关问题. solr6.0中进行中文分词器IK Analyzer的配置和solr低版本中最大不同点在于IK Analyzer中jar包的引用.一般的IK分词jar包都是不能用的,因为IK分词中传统的jar不支持solr6.0这个高版本的,所以就会发送运行

Socket的简单例子

服务器端 using System;using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets;//Socket相关的类 namespace ChatServer { class Program { static void Main(string[] args) { /

C语言去除数组中重复的字符简单例子

#include <stdio.h> int main(void){ int a[10]={1,2,3,3,4,5,1,3,5,6}; int i,j; int zieo=0; for(i=0;i<10;i++) for(j=i+1;j<10;j++) { if(a[i]==a[j]) { a[j]=0; } } for(i=0;i<10;i++) { if(a[i]!=zieo) { printf("%d\t",a[i]); } } printf(&qu

gtk+3.0的环境配置及基于gtk+3.0的python简单例子

/*********************************************************************  * Author  : Samson  * Date    : 06/25/2014  * Test platform:  *              Mint 15  *              GNU bash, version 4.2.45  * *************************************************