Elasticsearch Java API - 客户端连接
package com.java1234;
import com.google.gson.JsonObject;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.net.InetAddress;
/**
* @author XXL
* @create 2019-08-04 13:05
*/
public class ESConn {
protected TransportClient client;
@Before
public void setUp() throws Exception {
Settings esSettings = Settings.builder()
.put("cluster.name", "my-application") //设置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)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("公网ip"), 9300));
System.out.println("ElasticsearchClient 连接成功");
}
@Test
public void testClientConnection() throws Exception {
System.out.println(client);
JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("name", "java 编程思想");
jsonObject.addProperty("publishDate", "2018-11-11");
jsonObject.addProperty("price", 100);
IndexResponse response=client.prepareIndex("book", "java", "1")
.setSource(jsonObject.toString(), XContentType.JSON).get();
System.out.println("索引名称:"+response.getIndex());
System.out.println("类型:"+response.getType());
System.out.println("文档ID:"+response.getId());
System.out.println("当前实例状态:"+response.status());
System.out.println("--------------------------");
}
@After
public void tearDown() throws Exception {
if (client != null) {
client.close();
}
}
}
运行结果:
转载于//www.cnblogs.com/Uzai/p/11333592.html
还没有评论,来说两句吧...