Search code examples
solrsolrj

Update (not replace) Solr data with solrj library


Suppose, I have a Solr index with current structure:

<field name="id" type="string" indexed="true" stored="true" required="true"/>
<field name="field_1" type="string" indexed="true" stored="true"/>
<field name="field_2" type="string" indexed="true" stored="true"/>

which already has some data. I want to replace data in field "field_1" but data in field "field_2" has to be stay untouched. For a while I have been using curl whith json file for this task. The example of json file is

[
"{"id":1,"field_1":{"set":"some value"}}"
 ]

Data in this file replace value only in field "field_1".

Now I have to the same with solrj library. There are some code snippets in order explain my attempts.

SolrInputDocument doc = new SolrInputDocument();
doc.addField("field_1", "some value");
documents.add(doc);

server = new ConcurrentUpdateSolrClient(solrServerUrl, solrQueueSize, solrThreadCount);
UpdateResponse resp = server.add(documents, solrCommitTimeOut);

When I run this code value of the "field_1" became "some value", but the value of "field_2" became is null. How can avoid replacing value in field "field_2"?


Solution

  • Because you are doing a full update, what you are doing is overwriting the entire previous document with a new one, which does not have field2.

    You need to do a partial update as explained here (scroll down to SOLRJ comment): https://cwiki.apache.org/confluence/display/solr/Updating+Parts+of+Documents

      SolrJ code for Atomic Update
      String solrBaseurl = "http://hostname:port/solr";
      String collection = "mydocs";
    
      SolrClient client = new HttpSolrClient(solrBaseurl);
      SolrInputDocument doc = new SolrInputDocument();
    
      doc.addField("id", "test");
      Map<String, String> cmd1 = new HashMap<>();
      Map<String, String> cmd2 = new HashMap<>();
      cmd1.put("set", "newvalue");
      cmd2.put("add", "additionalvalue");
      doc.addField("field1", cmd1);
      doc.addField("field2", cmd2);
      client.add(collection, doc);