啟動tomcat
創(chuàng)建一個索引庫(在瀏覽器中輸入下面的命令)
http://192.168.25.110:8180/solr/admin/collections?action=CREATE&name=collection2&numShards=2&replicationFactor=2
刪除多余的索引庫
http://192.168.25.110:8180/solr/admin/collections?action=DELETE&name=collection1
啟動集群版只需要啟動下面兩個服務(wù)就可以了
測試方法
package cn.e3mall.solrj.test;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
public class TestSolrCloud {
@Test
public void testAddDocument() throws Exception {
//創(chuàng)建一個集群的連接俘种,應(yīng)該使用CloudSolrServer創(chuàng)建。
CloudSolrServer solrServer = new CloudSolrServer("192.168.25.110:2181,192.168.25.110:2182,192.168.25.110:2183");
//zkHost:zookeeper的地址列表
//設(shè)置一個defaultCollection屬性棍矛。
solrServer.setDefaultCollection("collection2");
//創(chuàng)建一個文檔對象
SolrInputDocument document = new SolrInputDocument();
//向文檔中添加域
document.setField("id", "solrcloud01");
document.setField("item_title", "測試商品01");
document.setField("item_price", 123);
//把文件寫入索引庫
solrServer.add(document);
//提交
solrServer.commit();
}
@Test
public void testQueryDocument() throws Exception {
//創(chuàng)建一個CloudSolrServer對象
CloudSolrServer cloudSolrServer = new CloudSolrServer("192.168.25.110:2181,192.168.25.110:2182,192.168.25.110:2183");
//設(shè)置默認的Collection
cloudSolrServer.setDefaultCollection("collection2");
//創(chuàng)建一個查詢對象
SolrQuery query = new SolrQuery();
//設(shè)置查詢條件
query.setQuery("*:*");
//執(zhí)行查詢
QueryResponse queryResponse = cloudSolrServer.query(query);
//取查詢結(jié)果
SolrDocumentList solrDocumentList = queryResponse.getResults();
System.out.println("總記錄數(shù):" + solrDocumentList.getNumFound());
//打印
for (SolrDocument solrDocument : solrDocumentList) {
System.out.println(solrDocument.get("id"));
System.out.println(solrDocument.get("title"));
System.out.println(solrDocument.get("item_title"));
System.out.println(solrDocument.get("item_price"));
}
}
}