elasticsearch 学习教程之三 客户端连接

时间:2022-09-01 00:11:39

部门调整以后进入新部门,新部门用的elasticsearch 1.8.X,很老的版本了,由于里面各种各样的插件,非常多,导致升级版本基本没有希望了,所以代码没有参考价值了,最近打算自己封装一套rest接口的查询API,首先去网上各种搜索各种github,大部分教程好像都是重复的,

好了开始:

单例类

import java.net.InetAddress;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ESClientService {
	private static final Logger logger = LoggerFactory.getLogger(ESClientService.class);

	private TransportClient client;

	private final static ESClientService INSTANCE = new ESClientService();

	private ESClientService() {
		init();
	}

	public void init() {
		try {
			String clusterName = System.getProperties().getProperty("es.cluster.name");//集群名称 social  
			String address = System.getProperties().getProperty("es.cluster.address");//集群地址根据自己的配置修改地址和端口 10.116.2.65:9400,10.116.2.66:9400

			Settings settings = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", true).build();
			client = new PreBuiltTransportClient(settings);

			String[] ars = address.split(",");
			for (String ar : ars) {
				String[] ipAndPort = ar.split(":");
				client.addTransportAddress(new TransportAddress(InetAddress.getByName(ipAndPort[0]), Integer.parseInt(ipAndPort[1])));
			}
			logger.info("Init  transportClient success !!!");
		} catch (Exception e) {
			logger.error("Init transportClient error", e);
		}
	}

	public static ESClientService getInstance() {
		return INSTANCE;
	}

	public TransportClient getClient() {
		return client;
	}

	public void close() {
		try {
			client.close();
		} catch (Exception e) {
			logger.error("close transportClient error", e);
		}
	}

}

测试类:

import cn.com.gome.flash.common.client.ESClientService;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;

public class TestElaselasticsearch {

    public static void main(String[] args) {

        SearchRequestBuilder searchRequestBuilder = ESClientService.getInstance().getClient().prepareSearch("索引名");
        //查询语句开始  中间的脑补吧,下一章说语句拼接

        //查询语句结束
        SearchResponse response = searchRequestBuilder.execute().actionGet();

    }
}