使用 SolrJ 将文档添加到 Solr
如果我们有一个模式如下:
<field name="id" type="string" indexed="true" stored="true" required="true" />
<field name="name" type="string" indexed="true" stored="true" />
向 Solr 添加内容的 solrj 代码如下所示:
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;
}
}