Adding Data to Solr
Indexing documents is done as expected:
- Java
-
source
JavaAsyncSolrClient solr = JavaAsyncSolrClient.create("http://localhost:8983/solr/collection1"); SolrInputDocument doc1 = new SolrInputDocument(); doc1.addField("id", "id1"); doc1.addField("name", "doc1"); doc1.addField("cat", "cat1"); doc1.addField("price", 10); SolrInputDocument doc2 = new SolrInputDocument(); doc2.addField("id", "id2"); doc2.addField("name", "doc2"); doc2.addField("cat", "cat1"); doc2.addField("price", 20); solr.addDocs(asList(doc1, doc2)) .thenCompose(r -> solr.commit()) .thenAccept(r -> System.out.println("docs added"));
- Scala
-
source
val solr = AsyncSolrClient("http://localhost:8983/solr/collection1") val doc1 = new SolrInputDocument() doc1.addField("id", "id1") doc1.addField("name", "doc1") doc1.addField("cat", "cat1") doc1.addField("price", 10) val doc2 = new SolrInputDocument() doc2.addField("id", "id2") doc2.addField("name", "doc2") doc2.addField("cat", "cat1") doc2.addField("price", 20) for { _ <- solr.addDocs(docs = Iterable(doc1, doc2)) _ <- solr.commit() } yield print("docs added")
It’s also possible to directly index annotated beans:
- Java
-
source
import org.apache.solr.client.solrj.beans.Field; class Item { @Field String id; @Field String name; @Field("cat") String category; @Field float price; TestBean(String id, String name, String category, float price) { this.id = id; this.name = name; this.category = category; this.price = price; } } JavaAsyncSolrClient solr = JavaAsyncSolrClient.create("http://localhost:8983/solr/collection1"); Item item1 = new Item("id1", "doc1", "cat1", 10); Item item2 = new Item("id2", "doc2", "cat1", 20); solr.addBeans(asList(item1, item2)) .thenCompose(r -> solr.commit()) .thenAccept(r -> System.out.println("beans added"));
- Scala
-
source
import org.apache.solr.client.solrj.beans.Field import scala.annotation.meta.field case class Item(@(Field @field) id: String, @(Field @field) name: String, @(Field @field)("cat") category: String, @(Field @field) price: Float) { def this() = this(null, null, null, 0) } val solr = AsyncSolrClient("http://localhost:8983/solr/collection1") val item1 = Item("id1", "doc1", "cat1", 10) val item2 = Item("id2", "doc2", "cat1", 20) for { _ <- solr.addBeans(beans = Iterable(item1, item2)) _ <- solr.commit() } yield print("beans added")
The source code for this page can be found here.