[Solr] 教程2: solr的Java操作、查询例子

Solr版本:solr-5.5.4、JDK1.7

Java代码如下,以 ${SOLR_HOME}/server/solr/configsets/sample_techproducts_configs的配置为基础来进行操作。

需要的solr的jar包:solr-core、solr_solrj、httpclient、httpcore


package services.sorl_basic;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
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.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.CollectionAdminResponse;
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 org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.ZkStateReader;

public class TestSample {
    private int zkClientTimeout;
    private int zkConnectTimeout;
    private String ZK_URL;
    private String COLLECTION_NAME;
    private String DEFAULT_CONFIG_NAME;
    private int shardNum;
    private int replicaNum;

    private void initProperties() throws SolrException {
        zkClientTimeout = 20000;
        zkConnectTimeout = 30000;
        ZK_URL = "192.168.111.140:2181,192.168.111.141:2181,192.168.111.142:2181/solr";
        COLLECTION_NAME = "students";
        DEFAULT_CONFIG_NAME = "students";
        shardNum = 3;
        replicaNum = 3;
    }

    private CloudSolrClient getCloudSolrClient(String zkHost) throws SolrException {

        CloudSolrClient cloudSolrClient = new CloudSolrClient(zkHost);
        cloudSolrClient.setZkClientTimeout(zkClientTimeout);
        cloudSolrClient.setZkConnectTimeout(zkConnectTimeout);
        cloudSolrClient.connect();
        System.out.println("The cloud Server has been connected !!!!");

        ZkStateReader zkStateReader = cloudSolrClient.getZkStateReader();
        ClusterState cloudState = zkStateReader.getClusterState();
        System.out.println("The zookeeper state is : {}"+ cloudState);

        return cloudSolrClient;
    }

    private void queryIndex(CloudSolrClient cloudSolrClient) throws SolrException {
        SolrQuery query = new SolrQuery();
        query.setQuery("name:zacks*");

        try {
            QueryResponse response = cloudSolrClient.query(query);
            SolrDocumentList docs = response.getResults();
            System.out.println("Query wasted time : {}ms"+ response.getQTime());

            System.out.println("Total doc num : {}"+ docs.getNumFound());
            for (SolrDocument doc : docs) {
                System.out.println("doc detail : " + doc.getFieldValueMap());
            }
        }  catch (Exception e) {
            System.out.println("Failed to query document"+ e);
            throw new SolrException("unknown exception");
        }
    }

    private void removeIndex(CloudSolrClient cloudSolrClient) throws SolrException {
        try {
            cloudSolrClient.deleteByQuery("*:*");
            cloudSolrClient.commit();
            System.out.println("Success to delete index");
        } catch (SolrServerException e) {
            System.out.println("Failed to remove document"+ e);
            throw new SolrException("Failed to remove document");
        } catch (IOException e){
            System.out.println("Failed to remove document"+ e);
            throw new SolrException("Failed to remove document");
        }
    }

    private void addDocs(CloudSolrClient cloudSolrClient) throws SolrException {
        Collection<SolrInputDocument> documents = new ArrayList<SolrInputDocument>();
        for (Integer i = 0; i < 5; i++) {
            SolrInputDocument doc = new SolrInputDocument();
            doc.addField("id", i.toString());
            doc.addField("name", "zacks" + i);
            doc.addField("features", "test" + i);
            doc.addField("price", (float) i * 1.01);
            documents.add(doc);
        }
        try {
            cloudSolrClient.add(documents);
            cloudSolrClient.commit();
            System.out.println("success to add index");
        }catch (Exception e) {
            System.out.println("Failed to add document to collection"+ e);
            throw new SolrException("unknown exception");
        }
    }

    private void addDocs2(CloudSolrClient cloudSolrClient) throws SolrException {
        UpdateRequest request = new UpdateRequest();
        Collection<SolrInputDocument> documents = new ArrayList<SolrInputDocument>();
        for (Integer i = 5; i < 10; i++) {
            SolrInputDocument doc = new SolrInputDocument();
            doc.addField("id", i.toString());
            doc.addField("name", "zacks" + i);
            doc.addField("features", "test" + i);
            doc.addField("price", (float) i * 1.01);
            documents.add(doc);
        }
        request.add(documents);
        try {
            cloudSolrClient.request(request);
            cloudSolrClient.commit();
        } catch (SolrServerException e) {
            System.out.println("Failed to add document to collection"+ e);
            throw new SolrException("Failed to add document to collection");
        } catch (IOException e){
            System.out.println("Failed to add document to collection"+ e);
            throw new SolrException("Failed to add document to collection");
        }
    }


    private void createCollection(CloudSolrClient cloudSolrClient) throws SolrException {
        CollectionAdminRequest.Create create = new CollectionAdminRequest.Create();
        create.setCollectionName(COLLECTION_NAME);
        create.setConfigName(DEFAULT_CONFIG_NAME);
        create.setNumShards(shardNum);
        create.setReplicationFactor(replicaNum);
        CollectionAdminResponse response = null;
        try {
            response = create.process(cloudSolrClient);
        } catch (Exception e) {
            System.out.println("Failed to create collection"+ e);
            throw new SolrException("unknown exception");
        }
        if (response.isSuccess()) {
            System.out.println("Success to create collection[{}]"+ COLLECTION_NAME);
        } else {
            System.out.println("Failed to create collection[{}], cause : {}"+ COLLECTION_NAME+ response.getErrorMessages());
            throw new SolrException("Failed to create collection");
        }
    }

    private void deleteCollection(CloudSolrClient cloudSolrClient) throws SolrException {
        CollectionAdminRequest.Delete delete = new CollectionAdminRequest.Delete();
        delete.setCollectionName(COLLECTION_NAME);
        CollectionAdminResponse response = null;
        try {
            response = delete.process(cloudSolrClient);
        } catch (SolrServerException e) {
            System.out.println("Failed to delete collection"+e);
            throw new SolrException("Failed to create collection");
        } catch (IOException e){
            System.out.println("Failed to delete collection"+e);
            throw new SolrException("unknown exception");
        } catch (Exception e) {
            System.out.println("Failed to delete collection"+ e);
            throw new SolrException("unknown exception");
        }
        if (response.isSuccess()) {
            System.out.println("Success to delete collection[{}]"+ COLLECTION_NAME);
        } else {
        	System.out.println("Failed to delete collection[{}], cause : {}"+  COLLECTION_NAME+ response.getErrorMessages());
            throw new SolrException("Failed to delete collection");
        }
    }

    @SuppressWarnings("unchecked")
    private List<String> queryAllCollections(CloudSolrClient cloudSolrClient) throws SolrException {
        CollectionAdminRequest.List list = new CollectionAdminRequest.List();
        CollectionAdminResponse listRes = null;
        try {
            listRes = list.process(cloudSolrClient);
        } catch (SolrServerException e) {
            System.out.println("Failed to list collection"+ e);
            throw new SolrException("Failed to list collection");
        } catch (IOException e){
            System.out.println("Failed to list collection"+e);
            throw new SolrException("Failed to list collection");
        } catch (Exception e) {
            System.out.println("Failed to list collection"+ e);
            throw new SolrException("unknown exception");
        }
        List<String> collectionNames = (List<String>) listRes.getResponse().get("collections");
        System.out.println("All existed collections : {}"+ collectionNames);
        return collectionNames;
    }

    public static void main(String[] args) throws SolrException {
    	System.out.println("abcdawsd");
        TestSample testSample = new TestSample();

        testSample.initProperties();


        CloudSolrClient cloudSolrClient = null;
        try {
            cloudSolrClient = testSample.getCloudSolrClient(testSample.ZK_URL);

            List<String> collectionNames = testSample.queryAllCollections(cloudSolrClient);

            if (collectionNames.contains(testSample.COLLECTION_NAME)) {
                testSample.deleteCollection(cloudSolrClient);
            	System.out.println("Connection Found: " + testSample.COLLECTION_NAME);
            }

            testSample.createCollection(cloudSolrClient);

            cloudSolrClient.setDefaultCollection(testSample.COLLECTION_NAME);

            testSample.addDocs(cloudSolrClient);

            testSample.addDocs2(cloudSolrClient);

            testSample.queryIndex(cloudSolrClient);

            System.exit(0);
            testSample.removeIndex(cloudSolrClient);

            testSample.queryIndex(cloudSolrClient);

        } catch (SolrException e) {
            throw new SolrException(e.getMessage());
        } finally {
            if (cloudSolrClient != null) {
                try {
                    cloudSolrClient.close();
                } catch (IOException e) {
                    System.out.println("Failed to close cloudSolrClient"+ e);
                }
            }
        }

    }
}

 

 

 

 

 

分类上一篇:     分类下一篇:

Leave a Reply