solr-cloud-JAVA调用(十一)

闲话不多说 直接看代码  ,使用的是集群的方式连接

package com.julong.test;

import java.io.IOException;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SolrPingResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

public class SolrCloudTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String zkHost = "192.168.10.132:12181,192.168.10.132:22181,192.168.10.132:32181";
		CloudSolrClient cloudSolrClient = new CloudSolrClient(zkHost);
		cloudSolrClient.setDefaultCollection("julong_collections");//设置连接的地址
		cloudSolrClient.setZkConnectTimeout(5000);//连接超时
		cloudSolrClient.setZkClientTimeout(5000);//客户端连接超时
		cloudSolrClient.connect();
		SolrPingResponse solrPingResponse = null;
		try {
			//检测状态
			solrPingResponse = cloudSolrClient.ping();
			System.out.println(solrPingResponse.getStatus());
			System.out.println(solrPingResponse.getElapsedTime());
			System.out.println(solrPingResponse.getRequestUrl());
			System.out.println(solrPingResponse.getQTime());
			System.out.println(solrPingResponse.getResponse().size());
			
			//新增数据
			SolrInputDocument solrInputDocument = new SolrInputDocument();
			solrInputDocument.setField("id", 1);
			solrInputDocument.setField("user_name", "zhangsan");
			solrInputDocument.setField("user_age", 18);
			UpdateResponse updateResponse = cloudSolrClient.add(solrInputDocument);
			cloudSolrClient.commit();
			int updateStatus = updateResponse.getStatus();
			System.out.println("新增数据:"+updateStatus);
			// 查询数据
			SolrQuery solrQuery = new SolrQuery();
			solrQuery.setQuery("*:*");
			QueryResponse queryResponse = cloudSolrClient.query(solrQuery);
			SolrDocumentList solrDocumentList = queryResponse.getResults();
			System.out.println(solrDocumentList.toString());
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		
	}

}

控制台打印结果:

log4j:WARN No appenders could be found for logger (org.apache.solr.client.solrj.impl.HttpClientUtil).
log4j:WARN Please initialize the log4j system properly.
0
474
null
1
2
新增数据:0
{numFound=2,start=0,maxScore=1.0,docs=[SolrDocument{id=1, user_name=[zhangsan], user_age=[18], _version_=1655415275108958208}, SolrDocument{id=julong, title=[helloworld], _version_=1655352650602905600}]}

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页