最近学习了Lucene和Solr,Java操作Solr就叫SolrJ了,这是我肤浅的理解,下面记录下简单的一些操作,方面日后复习
首先导入jar包座标
<!--SolrJ-->
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>7.7.2</version>
</dependency>
然后编写测试类代码(随着Jar包版本更新,写法会不一样,注意一下):
添加:
@Test
public void testAdd() throws IOException, SolrServerException {
String solrURL="http://localhost:8080/solr/collection1";
HttpSolrClient.Builder builder = new HttpSolrClient.Builder(solrURL);
HttpSolrClient client = builder.build();
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id","123");
doc.setField("age",22);
//doc.setField("asd","nono");
/*添加一个不存在的Field数据,竟然不报错*/
client.add(doc);
client.commit();
/*记得提交,不然结果不生效*/
}
删除
@Test
public void testDelete() throws IOException, SolrServerException {
String solrURL="http://localhost:8080/solr/collection1";
HttpSolrClient.Builder builder = new HttpSolrClient.Builder(solrURL);
HttpSolrClient client = builder.build();
client.deleteById("123");
/*删除所有*/
//client.deleteByQuery("*:*");
client.commit();
}
修改
修改与添加调用的方法是一致的,都是使用add方法,当ID已经存在时,直接覆盖,这样等同于修改
查询(重点)
@Test
public void test2() throws IOException, SolrServerException {
String solrURL="http://localhost:8080/solr/collection1";
HttpSolrClient.Builder builder = new HttpSolrClient.Builder(solrURL);
HttpSolrClient client = builder.build();
SolrQuery query = new SolrQuery();
// query.setFields("id");
query.set("q","*:*");
query.set("fq","age:[1 TO 20]");
query.addSort("age", SolrQuery.ORDER.desc);
QueryResponse response = client.query(query);
SolrDocumentList results = response.getResults();
long num = results.getNumFound();
System.out.println("num "+num);
for (SolrDocument doc : results) {
System.out.printf("id:%s,name:%s age:%s\n", doc.get("id"), doc.get("name"), doc.get("age"));
}
}
修改:(api没有修改的方法,只能通过id,先获取之前的doc里面的值,然后新建一个doc,进行覆盖,id相同就可以覆盖)
SolrInputDocument document = new SolrInputDocument(); //新的文档,直接覆盖旧的
SolrDocument originalDoc = solrClient.getById(id);
Collection<String> fieldNames = originalDoc.getFieldNames();
for (String fieldName : fieldNames) {
Object value = originalDoc.getFieldValue(fieldName);
document.addField(fieldName, value);
}
solrClient.add(document);
solrClient.commit();