This topic describes how to call the API operations of open source Apache Solr to access the search engine of ApsaraDB for Lindorm and provides related examples.

Prerequisites

  • JDK 1.6 or later is installed on a host.
  • The IP address of the host is added to the whitelist of your Lindorm instance. For more information, see Configure a whitelist.

Step 1: Download solr-solrj

To obtain the Apache Solr SDK, you can add a Maven dependency or download solr-solrj.

  • Add a Maven dependency If you create a project in a Maven repository, add the solr-solrj dependency to the pom.xml file. Example:
    <dependency>
       <groupId>org.apache.solr</groupId>
       <artifactId>solr-solrj</artifactId>
       <version>7.3.1</version>
    </dependency>
  • Download solr-solrj.

Step 2: Create and initialize an instance

  • If you want to access the instance over the Internet, use the HttpSolrClient mode. Example:
        String httpUrl = "http://***:8983/solr/";
        HttpSolrClient solrClient = new HttpSolrClient.Builder(httpUrl).build();
  • If you want to access the instance over a private network, use the CloudSolrClient mode. Example:
        String zkHost = "zk1:2181,zk2:2181,zk3:2181/solr"
        CloudSolrClient solrClient = new CloudSolrClient.Builder(Collections.singletonList(zkHost), 
                                        Optional.empty()).build();
    Note CloudSolrClient ensures thread safety and allows multiple threads of an application to share the same object.

Step 3: Refer to the following sample code to access the search engine

  1. The following sample code shows how to write data:
        List docs = new ArrayList<>();
        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id", 1);
        doc.addField("name_s", "bob");
        doc.addField("age_i", 18);
        docs.add(doc);
        solrClient.add(docs);
  2. The following sample code shows how to query data:
        SolrQuery solrQuery = new SolrQuery("name_s:bob");
        QueryResponse response = solrClient.query("your_index", solrQuery);
        SolrDocumentList documentList = response.getResults();
        for(SolrDocument doc : documentList){
            String id = (String)doc.getFieldValue("id");
            //do something
        }
        solrClient.close();
    Note For more information about sample code that shows how to query data, see Sample code.