作者:jzcoijawlkmlzkm_307 | 来源:互联网 | 2023-05-18 23:01
solr添加文档非常方便,不用像Lucene那样一个一个添加Field,省去了很多的麻烦下面看操作方法一:privatestaticStringURI"http:localh
solr添加文档非常方便,不用像Lucene那样一个一个添加Field,省去了很多的麻烦下面看操作
方法一:
private static String URI = "http://localhost:8080/solr/";
private CommonsHttpSolrServer httpSolrServer = null;
@Before
public void init() {
try {
httpSolrServer = new CommonsHttpSolrServer(URI);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
@Test
public void test1() {
try {
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "1");
document.addField("news_title", "这是我的第一个solr程序");
document.addField("news_content", "希望能够运行起来");
httpSolrServer.add(document);
httpSolrServer.commit();
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Note:id为唯一,不可重复,如果重复,solr会自动将索引中id相同的元素更新为现在的属性
域的名称可以在schema.xml的Field中设置,默认的有很多Field,我们也可以使用默认的
<field name="news_title" type="textComplex" indexed="true" stored="true" />
<field name="news_content" type="textComplex" indexed="true" sotred="true" />
方法2:直接添加对象
2.1 定义对象
package com.solr.entity;
import org.apache.solr.client.solrj.beans.Field;
public class News {
private String id;
private String title;
private String content;
public News(){}
public News(String id, String title, String content) {
this.id = id;
this.title = title;
this.cOntent= content;
}
public String getId() {
return id;
}
@Field
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
@Field("news_title")
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
@Field("news_content")
public void setContent(String content) {
this.cOntent= content;
}
}
2.2 添加对象到索引
@Test
public void test2() {
try {
List list = new ArrayList();
News news1 = new News("2", "title2", "content2");
list.add(news1);
News news2 = new News("3", "title3", "content3");
list.add(news2);
httpSolrServer.addBeans(list);
httpSolrServer.commit();
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Note:如果对象的某个域里面的属性为数组,我们需要在schema.xml的Field中设置 multiValued="true"