1 經過經過zookeeper通道創建索引java
public static void main(String[] args) throws IOException, SolrServerException { //注意,zkHost在windows僞分佈式與hadoop分佈式設置不同 //windows僞分佈式zkHost最後不須要加"/solr",linux的hadoop中須要添加"/solr" String zkHost = "node1:2181,node2:2181,node3:2181/solr"; String defaultCollection = "collection1"; CloudSolrServer server = new CloudSolrServer(zkHost); server.setDefaultCollection(defaultCollection); for (int i = 0; i < 1000; ++i) { SolrInputDocument doc = new SolrInputDocument(); doc.addField("cat", "book"); doc.addField("id", "book-" + i); doc.addField("name", "The Legend of Po part " + i); server.add(doc); if (i % 100 == 0) server.commit(); // periodically flush } server.commit(); }
2 注意,CDH中,能夠看zookeeper的設置,最大連接數爲60,因此對於zookeeper通常用單例node
public class myCloudSolrServer { // solrServer public static CloudSolrServer solrServer; //效率不高的方法 // public static synchronized CloudSolrServer getSolrServer() { // if (solrServer == null) { // try { // solrServer = new CloudSolrServer(Const.ZK_HOST + "/solr"); // final int zkClientTimeout = 20000; // 心跳20秒 // final int zkConnectTimeout = 10000; // 設置連接主機超時(單位毫秒) // // solrServer.setDefaultCollection(Const.defaultCollection); // solrServer.setZkClientTimeout(zkClientTimeout); // solrServer.setZkConnectTimeout(zkConnectTimeout); // } catch (Exception e) { // e.printStackTrace(); // } // } // return solrServer; // } //支持大併發方法 public static CloudSolrServer getSolrServer() { if (solrServer == null) { synchronized (myCloudSolrServer.class) { if (solrServer == null) { try { solrServer = new CloudSolrServer(Const.ZK_HOST + "/solr"); final int zkClientTimeout = 20000; // 心跳20秒 final int zkConnectTimeout = 10000; // 設置連接主機超時(單位毫秒) solrServer.setDefaultCollection(Const.defaultCollection); solrServer.setZkClientTimeout(zkClientTimeout); solrServer.setZkConnectTimeout(zkConnectTimeout); } catch (Exception e) { e.printStackTrace(); } } } } return solrServer; } }
3 急羣中能夠指定到某個分片linux
public static void main(String[] args) throws IOException, SolrServerException { String url= "node1:8983/solr/core_shard1_replica1"; String defaultCollection = "collection1"; HttpSolrServer server = new HttpSolrServer (url); server.setDefaultCollection(defaultCollection); for (int i = 0; i < 1000; ++i) { SolrInputDocument doc = new SolrInputDocument(); doc.addField("cat", "book"); doc.addField("id", "book-" + i); doc.addField("name", "The Legend of Po part " + i); server.add(doc); if (i % 100 == 0) server.commit(); // periodically flush } server.commit(); }
注意,在創建索引的時候,不要每個就去commit,爲了提升效率,通常用windows
Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); for(){ SolrInputDocument doc = new SolrInputDocument(); docs.add(doc); } server.add(docs); server.commit();
其實 server.commit()效率也不高,通常用軟提交併發