一:使用solrJ客户端进行文档操作
1、步骤分析
a、创建一个工程,添加jar包
\solr-4.10.3\dist\solrj-lib目录下的jar包
\solr-4.10.3\example\lib\ext目录下的jar包
solr-solrj-4.10.3.jar
b、创建一个SolrServer对象,相当于和服务端建立连接。需要使用HttpSolrServer类
c、创建一个文档对象SolrInputDocument
d、向文档中添加域
每个文件中必须有id域
每个域必须在schema.xml中定义
e、把文档对象写入索引库
f、提交
2、添加文档的代码实现
@Test
public void addDocument() throws Exception {
// 2)创建一个SolrServer对象,相当于和服务端建立连接。需要使用HttpSolrServer类。
//参数:solr服务器的url,默认是Collection1
SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/collection1");
// 3)创建一个文档对象SolrInputDocument
SolrInputDocument document = new SolrInputDocument();
// 4)向文档中添加域
// 每个文件中必须有id域
// 每个域必须在schema.xml中定义。
document.addField("id", "4");
document.addField("title", "新添加的文件1");
// 5)把文档对象写入索引库
solrServer.add(document);
// 6)提交
solrServer.commit();
}
3、删除文档的代码实现:可以根据id或者根据查询进行删除
@Test
public void deleteDocument() throws Exception {
SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/collection1");
//根据id删除
//solrServer.deleteById("1");
//根据查询删除,支持lucene的查询语法
solrServer.deleteByQuery("*:*");
//提交
solrServer.commit();
}