接下来是Elasticsearch (版本5.x)中数据的CRUD 操作,为此,根据ES官网上的资料总结了一个工具类.
具体如下:
(1)maven 添加依赖
(2)工具类代码:
public class ESClientUtils {
protected static Logger logger = Logger.getLogger(ESClientUtils.class);
protected static TransportClient client;
private static String es_node1_host = "";
private static String es_node1_port = "";
static {
String configName = "/hbase_elasticsearch.properties";
PropertiesLoader propertiesLoader = new PropertiesLoader(configName);
try {
es_node1_host = propertiesLoader.getProperty("es_node1_host");
es_node1_port = propertiesLoader.getProperty("es_node1_port");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Title: setUp
* @Description: TODO(创建client连接)
* @param: @throws Exception
* @return: void
* @throws
*/
@Before
public static void setUp() throws Exception {
Settings esSettings = Settings.builder()
.put("cluster.name", "utan-es") //设置ES实例的名称
.put("client.transport.sniff", true) //自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
.build();
/**
* 这里的连接方式指的是没有安装x-pack插件,如果安装了x-pack则参考{@link ElasticsearchXPackClient}
* 1. java客户端的方式是以tcp协议在9300端口上进行通信
* 2. http客户端的方式是以http协议在9200端口上进行通信
*/
/*client = new PreBuiltTransportClient(esSettings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.0.0.12"), Integer.parseInt("9300")));*/
client = new PreBuiltTransportClient(esSettings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(es_node1_host), Integer.parseInt(es_node1_port)));
System.out.println("ElasticsearchClient 连接成功");
}
public ESClientUtils() throws Exception{
setUp();
}
@After
public static void closeClient() throws Exception {
if (client != null) {
client.close();
}
}
/**
* @Title: getQueryResponse
* @Description: TODO(查询数据,精确查询)
* @param: @throws Exception
* @return: void
* @throws
*/
public static GetResponse getQueryResponse(String indexName, String type, String id) throws Exception{
setUp();
// 搜索数据
GetResponse response = client.prepareGet(indexName, type, id).execute().actionGet();
// 输出结果
System.out.println(response.getSourceAsString());
// 关闭client
closeClient();
return response;
}
/**
* @Title: getQueryResSource
* @Description: TODO(查询数据,返回Source,与getQueryResponse搭配使用)
* @param</