<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="java">Java API
Elasticsearch为Java用户提供了两种内置客户端:
节点客户端(node client):
节点客户端以无数据节点(none data node)身份加入集群,换言之,它自己不存储任何数据,但是它知道数据在集群中的具体位置,并且能够直接转发请求到对应的节点上。
传输客户端(Transport client):
这个更轻量的传输客户端能够发送请求到远程集群。它自己不加入集群,只是简单转发请求给集群中的节点。
两个Java客户端都通过9300端口与集群交互,使用Elasticsearch传输协议(Elasticsearch Transport Protocol)。集群中的节点之间也通过9300端口进行通信。如果此端口未开放,你的节点将不能组成集群。
<span style="font-family: Arial, Helvetica, sans-serif;">package com.ucloudlink.oss.elasticsearch;</span>
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import com.alibaba.fastjson.JSONObject;
import com.ucloudlink.oss.elasticsearch.support.DocumentResult;
import com.ucloudlink.oss.elasticsearch.utils.StringUtils;
public class EsSupport implements Serializable {
private static final long serialVersionUID = 1L;
private static Map<String, EsSupport> instanceCache;
private Client esClient;
public EsSupport(){
}
public synchronized static EsSupport getInstance(String clusterName, String hosts){
if (instanceCache == null){
instanceCache = new ConcurrentHashMap<String, EsSupport>();
}
EsSupport instance = instanceCache.get(clusterName + "|" + hosts);
if (null == instance){
instance = new EsSupport();
Client client = getESClient(clusterName, hosts);
instance.setEsClient(client);
instanceCache.put(clusterName + "|" + hosts, instance);
}
return instance;
}
/**
* 连接ES集群
* @param clusterName 集群名称
* @param hosts es集群地址,IP:PORT
* @return
*/
private static Client getESClient(String clusterName, String hosts){
if (StringUtils.isEmpty(hosts)){
System.out.println("hosts is empty");
return null;
}
Builder settingsBuilder = Settings.builder();
settingsBuilder.put(ClusterName.SETTING, clusterName);
settingsBuilder.put("client.transport.sniff", true);
Settings settings = settingsBuilder.build();
String[] hostList = hosts.split(",");
TransportClient.Builder clientBuilder = new TransportClient.Builder();
TransportClient transportClient = clientBuilder.settings(settings).build();
String[] address;
String host = null;
int port = 0;
for (String s: hostList){
address = s.split(":");
if (null != address && address.length > 1){
try{
host = address[0];
port = Integer.parseInt(address[1]);
InetSocketAddress ipAddress = new InetSocketAddress(host, port);
transportClient.addTransportAddress(new InetSocketTransportAddress(ipAddress));
}catch(Exception ex){
System.out.println("address error:" + address);
}
}
}
return transportClient;
}
/**
* 创建索引(往ES中插入数据)
* @param index
* @param type
* @param jsonData json格式字符串,否则报错
* @return
*/
public IndexResponse createIndex(String index, String type, String jsonData, String timestamp){
IndexResponse response = esClient.prepareIndex(index, type).setSource(jsonData).setTimestamp(timestamp).execute().actionGet();
return response;
}
/**
* 创建索引(往ES中插入数据)
* @param index 索引的格式,例如YYYY.MM.DD
* @param type 索引类型,例如group
* @param jsonData json格式字符串,否则报错
* @param ttl 设置过期为空不设置
* @return
*/
public IndexResponse createIndex(String index, String type, Map<String,Object> data, Long ttl){
IndexResponse response = esClient.prepareIndex(index, type).setSource(data).setTTL(ttl).execute().actionGet();
return response;
}
/**
* 创建索引(往ES中插入数据)
* @param index 索引的格式,例如YYYY.MM.DD
* @param type 索引类型,例如group
* @param jsonData json格式字符串,否则报错
* @param ttl 设置过期,为空不设置
* @return
*/
public IndexResponse createIndex(String index, String type, JSONObject data, Long ttl){
IndexResponse response = esClient.prepareIndex(index, type).setSource(data).setTTL(ttl).execute().actionGet();
return response;
}
/**
* 创建索引(往ES中插入数据)
* @param index 索引的格式,例如YYYY.MM.DD
* @param type 索引类型,例如group
* @param jsonData json格式字符串,否则报错
* @param ttl 设置过期,为空不设置
* @return
*/
public void createIndex(String index, String type, List<JSONObject> data, Long ttl){
if (null != data && data.size() > 0){
for (JSONObject obj : data){
esClient.prepareIndex(index, type).setSource(obj).setTTL(ttl);
}
}
}
public DeleteResponse deleteIndex(String index, String type, String id){
DeleteResponse response = esClient.prepareDelete(index, type, id).get();
return response;
}
public DeleteResponse deleteAll(){
return null;
}
public GetResponse search(String index, String type, String id){
GetResponse response = esClient.prepareGet(index, type, id).get();
return response;
}
public List<DocumentResult> search(QueryBuilder queryBuilder, String index, String type){
SearchResponse searchResponse = esClient.prepareSearch(index).setTypes(type).setQuery(queryBuilder).execute().actionGet();
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHists = hits.getHits();
if (searchHists.length > 0){
List<DocumentResult> list = new ArrayList<DocumentResult>();
for (SearchHit hit: searchHists){
Integer id = (Integer)hit.getSource().get("id");
String name = (String)hit.getSource().get("name");
String function = (String)hit.getSource().get("function");
list.add(new DocumentResult(id, name, function));
}
return list;
}
return null;
}
public Client getEsClient() {
return esClient;
}
public void setEsClient(Client esClient) {
this.esClient = esClient;
}
}
</span>