Tutorial for SolrCloud with Java
SolrCloud is an extension for Solr and through Java API it lets you not only add/update/delete documents in collections, but also create collection, and also manage schema and configuration for concrete collection.
Start SolrCloud locally
To start extension locally it’s enough to switch on cloud mode and accept all prompts:
solr -e cloud
By default, it will create two nodes: on 8983 and 7574 ports, and also Zookeeper on the port 9983
To create SolrCloudClient, it needs to define zkHost and zkChRoot:
String zkHost = "localhost:9983";
List<String> zkHosts = Collections.singletonList(zkHost);
Optional<String> zkChRoot = Optional.of("/");
CloudSolrClient cloudSolrClient = new CloudSolrClient.Builder(zkHosts, zkChRoot)
.withConnectionTimeout(30000)
.withSocketTimeout(30000)
.build();
To update configuration, you need to create Zookeeper client, define path to files with your schema.xml and solrconfig.xml configuration files and use method uploadConfig
:
ZkClientClusterStateProvider zkClientCluster = new ZkClientClusterStateProvider(zkHost);
Path configPath = getFile(System.getProperty("user.dir")).toPath().resolve("conf");
String configName = "testconfig";
zkClientCluster.uploadConfig(configPath, configName);
To create the collection, we need to define the name of collection, provide configuration that we saved in Zookeeper, and define the number of shard and replica:
String collectionName = "newCollection";
int numShards = 1;
int numReplicas = 1;
CollectionAdminResponse rsp = CollectionAdminRequest.createCollection(collectionName, configName, numShards, numReplicas)
.process(cloudSolrClient);
System.out.println(rsp.isSuccess());
Rules of thumb for number of shards and replicas: the number of shards should be greater then zero and the number of NRT (near real time) replicasu plus TLog replicas should be also greater then zero:
numShards must be > 0
nrtReplicas + tlogReplicas must be > 0
It also possible to check if collection already exist:
ClusterState.CollectionRef state = zkClientCluster.getState(collectionName);
System.out.println(state);
If collection doesn’t exist, the values of state is null
, otherwise it will bring something like this: LazyCollectionRef(newCollection)
It also possible to delete collection:
CollectionAdminRequest.deleteCollection(collectionName).process(cloudSolrClient);
To check that collection was successfully created, it possible to execute simple request:
QueryRequest req = new QueryRequest(new SolrQuery("*:*"));
QueryResponse queryResponse = req.process(cloudSolrClient, collectionName);
System.out.println(queryResponse.getStatus());
I hope this guide was useful. Happy coding with Java!