|
package com.rodge.elasticSearch.firstDemo;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
public class ESFirstDemo {
@SuppressWarnings("unchecked")
public TransportClient client() throws UnknownHostException {
// es地址, 地址為192.168.253.129(此處地址不能加"http://"), 此處的連接埠為es的tcp連接埠為9300,
// 而不是之前的http9200連接埠, 如果es有多可節點, 可以建立多個node, 然後再client中add進去
// 注意,這裡的連接埠號碼不是9200,而是9300。9200連接埠是用來讓HTTP REST
// API來訪問Elasticsearch,而9300連接埠是傳輸層監聽的預設連接埠。
InetSocketTransportAddress node = new InetSocketTransportAddress(
InetAddress.getByName("192.168.253.129"), 9300);
// es的配置類
Settings settings = Settings.builder().put("cluster.name", "wali").build();
// TransportClient是es啟動的核心類, 後續的關於es的開發都是圍繞著TransportClient進行的
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(node);
return client;
}
@Test
public void get() throws UnknownHostException {
GetResponse result = client().prepareGet("book", "novel", "1").get();
System.out.println(result.getSource().toString());
}
} |