• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • Maven
  • About
Apache Solr | SolrJ: Add documents using the request handler /update (binary)
  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" and "field1" 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 the request handler /update (binary):
    final String UPDATE_REQUEST_PATH = "/update";
    
    final String[] solrUrl = { "http://localhost:8983/solr" };
    
    final String collectionName = "collection1";
    
    // org.apache.solr.common.params.CollectionAdminParams.COLLECTION = "collection";
    
    final CloudSolrClient cloudSolrClient = new CloudSolrClient.Builder(Arrays.asList(solrUrl)).build();
    
    cloudSolrClient.setDefaultCollection(collectionName);
    
    // adding documents [/update] [ContentStreamUpdateRequest::addContentStream]
    {
        final String contentStream = "<add><doc><field name=\"id\">4</field><field name=\"dynamicField1_s\">dynamic_field1 1</field><field name=\"field1\">field1 1</field></doc></add>";
        final String contentType = "application/xml;charset=UTF-8";
    
        final ByteArrayStream byteArrayStream = new ByteArrayStream(contentStream.getBytes(StandardCharsets.UTF_8), null);
        byteArrayStream.setContentType(contentType);
    
        final ModifiableSolrParams modifiableSolrParams = new ModifiableSolrParams();
    
        modifiableSolrParams.add(CollectionAdminParams.COLLECTION, collectionName);
    
        final ContentStreamUpdateRequest contentStreamUpdateRequest = new ContentStreamUpdateRequest(UPDATE_REQUEST_PATH);
    
        contentStreamUpdateRequest.addContentStream(byteArrayStream);
        contentStreamUpdateRequest.setParams(modifiableSolrParams);
        contentStreamUpdateRequest.setMethod(METHOD.POST);
    
        final NamedList<Object> response = cloudSolrClient.request(contentStreamUpdateRequest);
    
        System.out.println(response);
    }
    
    cloudSolrClient.close();
© 2025  mtitek