Solr 14 - SolrJ操作SolrCloud集群 (Solr的Java API)
1 pom.xml文件的配置
项目的pom.xml依赖信息请参照:
Solr 09 - SolrJ操作Solr单机服务 (Solr的Java API)
2 SolrJ操作SolrCloud
public class SolrCloudTest {
// ZooKeeper地址
private static String zkHostString = "10.0.20.50:2181, 10.0.20.51:2181, 10.0.20.52:2181";
// collection默认名称, 比如Solr服务器上的collection是collection_shard1_replica1, 就是去掉"_shard1_replica1"的名称
private static String defaultCollection = "my_collection";
// 客户端连接超时时间
private static int zkClientTimeout = 3000;
// ZooKeeper连接超时时间
private static int zkConnectTimeout = 3000;
// cloudSolrServer实际
private CloudSolrServer cloudSolrServer;
// 测试方法之前构造 CloudSolrServer
@Before
public void init() {
cloudSolrServer = new CloudSolrServer(zkHostString);
cloudSolrServer.setDefaultCollection(defaultCollection);
cloudSolrServer.setZkClientTimeout(zkClientTimeout);
cloudSolrServer.setZkConnectTimeout(zkConnectTimeout);
cloudSolrServer.connect();
}
// 向SolrCloud中创建索引
@Test
public void testCreateIndexToSolrCloud() throws Exception {
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "100001");
document.addField("title", "李四");
cloudSolrServer.add(document);
cloudSolrServer.commit();
}
// 搜索索引
@Test
public void testSearchIndexFromSolrCloud() throws Exception {
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
try {
QueryResponse response = cloudSolrServer.query(query);
SolrDocumentList docs = response.getResults();
System.out.println("文档个数: " + docs.getNumFound());
System.out.println("查询时间: " + response.getQTime());
for (SolrDocument doc : docs) {
ArrayList title = (ArrayList) doc.getFieldValue("title");
String id = (String) doc.getFieldValue("id");
System.out.println("id: " + id);
System.out.println("title: " + title);
System.out.println();
}
} catch (SolrServerException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("Unknowned Exception!!!!");
e.printStackTrace();
}
}
// 删除索引
@Test
public void testDeleteIndexFromSolrCloud() throws Exception {
// 根据id删除
UpdateResponse response = cloudSolrServer.deleteById("zhangsan");
// 根据多个id删除
// cloudSolrServer.deleteById(ids);
// 自动查询条件删除
// cloudSolrServer.deleteByQuery("product_keywords:教程");
// 提交
cloudSolrServer.commit();
}
}
版权声明
作者: 马瘦风
出处: 博客园 马瘦风的博客
您的支持是对博主的极大鼓励, 感谢您的阅读.
本文版权归博主所有, 欢迎转载, 但请保留此段声明, 并在文章页面明显位置给出原文链接, 否则博主保留追究相关人员法律责任的权利.