本篇文章用几个简单的Java示例测试下在SolrCloud集群环境下solrj API的用法。
1、maven引入solrj
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>7.7.3</version>
</dependency>
2、CloudSolrClient增删改查
CloudSolrClient通过zookeeper获取集群中solr地址,再发起索引增删改查。
public class SolrCloudClientTest {
private CloudSolrClient cloudSolrClient = null;
@Before
public void init(){
//初始化CloudSolrClient
//zookeeper集群地址
List<String> zkHosts = new ArrayList<>();
zkHosts.add("192.168.31.200:2181");
zkHosts.add("192.168.31.201:2181");
zkHosts.add("192.168.31.202:2181");
//SolrCLoud在zookeeper中的根路径
Optional<String> zkChroot = Optional.of("/solr");
CloudSolrClient.Builder builder = new CloudSolrClient.Builder(zkHosts,zkChroot);
cloudSolrClient = builder.build();
cloudSolrClient.setZkConnectTimeout(30000);
//默认索引集
cloudSolrClient.setDefaultCollection("book");
cloudSolrClient.connect();
}
/**
* 新增
* @throws IOException
* @throws SolrServerException
*/
@Test
public void testAdd() throws IOException, SolrServerException {
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id","4444");
doc.addField("bookname","PHP入门与精通");
doc.addField("shopid","s001");
doc.addField("base_price",Double.valueOf(30));
doc.addField("shop_price",Double.valueOf(40));
doc.addField("pin_price",Double.valueOf(38));
doc.addField("isPintuan","1");
UpdateResponse response = cloudSolrClient.add(doc);
System.out.println(response);
}
/**
* 查询
* @throws IOException
* @throws SolrServerException
*/
@Test
public void testQuery() throws IOException, SolrServerException {
SolrQuery request = new SolrQuery();
request.set("q","id:1111");
QueryResponse response = cloudSolrClient.query(request);
System.out.println(response);
}
/**
* 根据id删除
* @throws IOException
* @throws SolrServerException
*/
@Test
public void testDeleteByID() throws IOException, SolrServerException {
String id = "1111";
UpdateResponse response = cloudSolrClient.deleteById(id);
System.out.println(response);
}
/**
* 根据查询语句删除
* @throws IOException
* @throws SolrServerException
*/
@Test
public void testDeleteByQUery() throws IOException, SolrServerException {
String query = "bookname:PHP入门与精通";
UpdateResponse response = cloudSolrClient.deleteByQuery(query);
System.out.println(response);
}
@After
public void close() throws IOException {
cloudSolrClient.close();
}
}