If we have a schema looking like:
<field name="id" type="string" indexed="true" stored="true" required="true" />
<field name="name" type="string" indexed="true" stored="true" />
the solrj code to add content to Solr will look like:
package com.stackoverflow.solrj.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
public class SolrJIndexing {
private final static String SOLR_URL = "http://localhost:8983/solr/mycollection";
public static void main(String[] args) {
SolrClient solrClient = new HttpSolrClient.Builder(SOLR_URL).build();
SolrInputDocument document1 = getDocument(1, "Document example 1");
SolrInputDocument document2 = getDocument(2, "Document example 2");
Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
docs.add(document1);
docs.add(document2);
try {
solrClient.add(docs);
solrClient.commit();
} catch (SolrServerException | IOException e) {
e.printStackTrace();
}
}
private static SolrInputDocument getDocument(int id, String name) {
SolrInputDocument document = new SolrInputDocument();
document.addField("id", id);
document.addField("name", name);
return document;
}
}