Search code examples
solrsolrj

Update Solr document using SolrJ via for loop


I have a Solr indexed document and I want to update some field. But the issue coming is if I am updating a single document then it is updating perfectly. But the same code if I use using for loop to update multiple document together then it is throwing error.

Here is my code for updating a single document and it is working -

SolrInputDocument doc = new SolrInputDocument();
HashMap<Integer, String> Id = new HashMap<>();
HashMap<Integer, String> Title = new HashMap<>();
HashMap<Integer, String> Name = new HashMap<>();
Id.put(0, 123);
Id.put(1, 345);
Title.put(0, "Title1");
Title.put(1, "Title2");
Name.put(0, "Tony");
Name.put(1, "Scarlet");
doc.addField("Id", Id.get(0));
doc.addField("Title", Title.get(0));
doc.addField("Name", Name.get(0));
solr.add(doc);
solr.commit();

Now the same code if i run using for loop like -

SolrInputDocument doc = new SolrInputDocument();
HashMap<Integer, String> Id = new HashMap<>();
HashMap<Integer, String> Title = new HashMap<>();
HashMap<Integer, String> Name = new HashMap<>();
Id.put(0, 123);
Id.put(1, 345);
Title.put(0, "Title1");
Title.put(1, "Title2");
Name.put(0, "Tony");
Name.put(1, "Scarlet");
for (int i =0; i<2; i++) {
   doc.addField("Id", Id.get(i));
   doc.addField("Title", Title.get(i));
   doc.addField("Name", Name.get(i));
   solr.add(doc);
   solr.commit();
}

Then this is throwing error as - "Document contains multiple values for uniqueKey field: Id=[123, 345]". Note - Id is my uniquekey. What is wrong happening here?


Solution

  • You're not creating a new SolrDocument for each iteration, so you're just adding values to the old one; the next iteration of the loop will then result in two values being set for the id field, which won't work.

    Create a new InputDocument for each document you want to add, and move the commit to after both documents has been added (no need to commit for each document in a loop).

    I'd also consider rewriting my HashMap to a single object representing what you're trying to index or at least use the HashMap to describe the object with "name", "id" and "title" entries, and then store those hashmaps in a list.

    for (int i = 0; i < 2; i++) {
        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("Id", Id.get(i));
        doc.addField("Title", Title.get(i));
        doc.addField("Name", Name.get(i));
        solr.add(doc);
    }
    
    solr.commit();