• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • Maven
  • About
Apache Solr | SolrJ: Add documents using CloudSolrClient
  1. Notes
  2. Example

  1. Notes
    In order for the code bellow to work:

    ► Make sure to update the variables ("solrUrl", "collectionName", ...) with your information.

    ► Make sure to add the fields "id", "field1", and "field2" to your SchemaXml.

    To force the commit, make sure to set the property "openSearcher" to true (SolrConfigXml file -> updateHandler -> autoCommit)

    Note: You can also force the commit by running the URL: http://localhost:8983/solr/COLLECTION-NAME/update?commit=true
  2. Example
    Add documents using CloudSolrClient:
    final String[] solrUrl = { "http://localhost:8983/solr" };
    
    final String collectionName = "collection1";
    
    final String SOLR_UNIQUE_KEY = "id";
    
    final String FIELD_1 = "field1"; // multiValued=true
    final String FIELD_2 = "field2";
    
    final String DYNAMIC_FIELD_1 = "dynamicField1_s";
    final String DYNAMIC_FIELD_2 = "dynamicField2_s";
    
    final CloudSolrClient cloudSolrClient = new CloudSolrClient.Builder(Arrays.asList(solrUrl)).build();
    
    cloudSolrClient.setDefaultCollection(collectionName);
    
    // adding documents [CloudSolrClient::add] [SolrInputDocument]
    {
        final SolrInputDocument solrInputDocument = new SolrInputDocument();
    
        solrInputDocument.addField(SOLR_UNIQUE_KEY, "1");
    
        solrInputDocument.addField(DYNAMIC_FIELD_1, "dynamic_field1 1");
        solrInputDocument.addField(DYNAMIC_FIELD_2, "dynamic_field2 1");
    
        solrInputDocument.addField(FIELD_1, "field1 1");
        solrInputDocument.addField(FIELD_1, "field1 2");
    
        solrInputDocument.addField(FIELD_2, "field2 1");
    
        final UpdateResponse updateResponse = cloudSolrClient.add(collectionName, solrInputDocument);
    
        System.out.println(updateResponse);
    }
    
    cloudSolrClient.close();
© 2025  mtitek