ELK(四)ElasticSearch Java API

本文深入探讨了Elasticsearch为Java用户提供两种内置客户端的功能特性:节点客户端与传输客户端,以及如何利用这些客户端创建索引并进行数据操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<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>



                
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值