写在前面的话:读书破万卷,编码如有神
--------------------------------------------------------------------
最简单的在java客户端连接es服务器
(仅作为快速简单使用demo)
package com.es.util.elasticsearch; import lombok.Data;
import org.apache.log4j.Logger;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.stereotype.Component; import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException; /**
* @author : huobaopaocai
* @date : 2018/2/15 - 10:31
* @Description : elasticsearch客户端
*/
@Component("elasticsearchConstant")
@Data
public class ElasticsearchConstant { public static final Logger LOG = Logger.getLogger(ElasticsearchConstant.class); /**
* es服务器地址
*/
private String host = "127.0.0.1"; /**
* es服务器端口
*/
private Integer port = 9300; /**
* es集群名称
*/
private String clusterName = "huobaopaocai-es-cluster"; /**
* es索引名称
*/
private String esIndex = "ecommerce"; /**
* es索引下type名称
*/
private String esType = "product"; public TransportClient client = null; private SearchRequestBuilder requestBuilder; private Long TIME_OUT = 20L; @PostConstruct
public void init() {
Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", true)
.put("client.transport.ping_timeout", "600s")
.build();
try {
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
} catch (UnknownHostException e) {
LOG.error(e, e.getCause());
}
} /**
* 初始化SearchRequestBuilder
* @return
*/
public SearchRequestBuilder initRequestBuilder() {
requestBuilder = client.prepareSearch(esIndex).setTypes(esType);
return requestBuilder;
} /**
* 执行es操作
* @param requestBuilder
* @return
*/
public SearchResponse execute(SearchRequestBuilder requestBuilder) {
SearchResponse searchResponse = requestBuilder.setTimeout(TimeValue.timeValueSeconds(TIME_OUT)).execute().actionGet();
return searchResponse;
}
}
--------------------------------------------------------------------