Search code examples
javasolrsolrj

Updating a document in Solr using SolrJ


I have following indexed data in Solr. I want to add an extra field "Location" in this indexed data using SolrJ. How can I do this?

"response":{"numFound":3061,"start":3059,"docs":[
      {
        "Id":12345,
        "Name":"Rajeev Kumar",
        "_version_":1223434645768768687},
      {
        "Id":67890,
        "Name":"Rohit Kumar",
        "_version_":1246457656544545434}]
  }}

After updating it should look like this -

"response":{"numFound":3061,"start":3059,"docs":[
      {
        "Id":12345,
        "Name":"Rajeev Kumar",
        "Location" : <some value>,
        "_version_":1223434645768768687},
      {
        "Id":67890,
        "Name":"Rohit Kumar",
        "Location": <some value>,
        "_version_":1246457656544545434}]
  }}

I tried something like this -

  public static void main(String[] args) throws SolrServerException, IOException {

            String urlString = "http://localhost:8983/solr/gettingstarted";
            HttpSolrClient solr = new HttpSolrClient.Builder(urlString).build();
            solr.setParser(new XMLResponseParser());
            SolrInputDocument document = new SolrInputDocument();
            HashMap<String, Object> value = new HashMap<String, Object>(); 
            value.put("set","Delhi"); 
            document.addField("Location", value); 
             solr.commit();
    }

But the problem is that this is creating a new document instead of updating the old document. Thanks for help in advance.


Solution

  • You have to include the id part in your document values, otherwise Solr isn't able to find the original document to update. This should be a uniqueKey field.

    document.addField("Id", 12345); 
    

    You can't perform an update against multiple documents in one request, so each document has to be updated by itself.