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();
}
}
}
運行結果:

