1. ES 啟動監聽兩個端口: 9200與9300的區別
9300是Tcp協議端口:通過tcp協議通訊,ES集群之間是通過9300進行通訊,java客戶端(TransportClient)的方式是也是以tcp協議在9300 端口上與集群進行通信。
9200是Http協議端口:主要用於外部通訊,外部使用RESTful接口進行訪問。 如下圖:url地址上輸入對應的RESTful接口 就可以訪問。

2. 高級客戶端連接ES集群
2.1介紹:ES提供了兩個JAVA REST client 版本
- Java Low Level REST Client :用於Elasticsearch的官方低級客戶端。它允許通過http與Elasticsearch集群通信。將請求編排和響應反編排留給用戶自己處理。它兼容所有的Elasticsearch版本。(PS:學過WebService的話,對編排與反編排這個概念應該不陌生。可以理解為對請求參數的封裝,以及對響應結果的解析)
- Java High Level REST Client :用於Elasticsearch的官方高級客戶端。它是基於低級客戶端的,它提供很多API,並負責請求的編排與響應的反編排。( PS:就好比是,一個是傳自己拼接好的字符串,並且自己解析返回的結果;而另一個是傳對象,返回的結果也已經封裝好了,直接是對象,更加規范了參數的名稱以及格式,更加面對對象一點 )
( PS:所謂低級與高級,我覺得一個很形象的比喻是,面向過程編程與面向對象編程 )
在 Elasticsearch 7.0 中不建議使用TransportClient,並且在8.0中會完全刪除TransportClient。因此,官方更建議我們用Java High Level REST Client,它執行HTTP請求,而不是序列號的Java請求。既然如此,這里就直接用高級了。
2.2 Maven倉庫配置
高級客戶端要與Elasticsearch集群進行通信,主版本號需要一致,次版本號不必相同。
本案例,es 使用6.8.0版本,而高級客戶端使用6.6.2是可以的。例如:6.0客戶端能夠與任何6.x Elasticsearch節點通信,而6.1客戶端肯定能 夠與6.1,6.2和任何后來的6.x版本進行通 信,但與舊版本的 Elasticsearch節點通信時可能會存在不兼容的問題,例如6.1和6.0之間, 可能6.1客戶端支持elasticsearch 6.0還沒出來的API。
1 <dependency> 2 <groupId>org.elasticsearch.client</groupId> 3 <artifactId>elasticsearch-rest-high-level-client</artifactId> 4 <version>6.6.2</version> 5 </dependency>
連接到es集群 RestHighLevelClient實例需要低級客戶端構建器來構建,
如下所示: RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("192.168.20.210", 9200, "http"))
);
高級客戶端將在內部創建低級客戶端,用來執行基於提供的構建器的請求,並 管理其生命周期。
當不再需要時,需要關閉高級客戶端實例,以便它所使用的所有資源以及底層 的http客戶端實例及其線程得到正確釋放。可以通過close方法來完成,該方法將關閉內部的RestClient實例。
client.close();
/*
使用高級客戶端連接ES集群
*/
public class ElasticSearchClient {
public static void main(String[] args){
RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost ("localhost", 9200, "http") ) );
GetIndexRequest request = new GetIndexRequest();
request.indices("test");
boolean exists = false;
try {
exists = client.indices().exists(request, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace ();
}
if(exists){
System.out.println("test索引庫存在");
}else{
System.out.println("test索引庫不存在");
}
//關閉高級客戶端實例,以便它所使用的所有資源以及底層 的http客戶端實例及其線程得到正確釋放
try {
client.close();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
2.3 創建索引 四種方式
索引index(四種json,map,XContentBuilder,object)
IndexResponse indexResponse = client.index(indexRequest,RequestOptions.DEFAULT);
1 /** 2 * index api 3 * @throws IOException 4 */ 5 @Test 6 public void test3() throws IOException { 7 XContentBuilder builder = XContentFactory.jsonBuilder(); 8 builder.startObject(); 9 { 10 builder.field("user", "kimchy"); 11 builder.timeField("postDate", new Date()); 12 builder.field("message", "trying out Elasticsearch"); 13 } 14 builder.endObject(); 15 IndexRequest indexRequest = new IndexRequest("posts", "doc", "1") 16 .source(builder); 17 18 IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); 19 System.out.println(indexResponse.getId()); 20 client.close(); 21 } 22 23 /** 24 * index api 25 * @throws IOException 26 */ 27 @Test 28 public void test4() throws IOException { 29 IndexRequest indexRequest = new IndexRequest("posts", "doc", "1") 30 .source("user", "kimchy", 31 "postDate", new Date(), 32 "message", "trying out Elasticsearch"); 33 34 IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); 35 System.out.println(indexResponse.getId()); 36 client.close(); 37 }
運行結果:如圖從head插件中可以看書創建了‘posts’索引,和四個文檔。

2.4 索引查詢
官網代碼:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.8/java-rest-high-document-get.html
@Test
public void test5() throws IOException {
GetRequest getRequest = new GetRequest(
"posts",
"doc",
"1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSource());
client.close();
}
運行結果:
{postDate=2019-06-14T09:15:05.372Z, message=trying out Elasticsearch, user=kimchy}
2.5 索引判斷exist 索引更新update 索引刪除delete 批量操作bulk 多條數據查詢Multi Get
/**
* exist api
* @throws IOException
*/
@Test
public void test6() throws IOException {
GetRequest getRequest = new GetRequest(
"posts",
"doc",
"1");
getRequest.fetchSourceContext(new FetchSourceContext (false));
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
if(exists){
System.out.println("數據存在");
}else{
System.out.println("數據不存在");
}
client.close();
}
/**
* update api
* @throws IOException
*/
@Test
public void test7() throws IOException {
UpdateRequest request = new UpdateRequest(
"posts",
"doc",
"1");
String jsonString = "{" +
"\"updated\":\"2017-01-01\"," +
"\"reason\":\"daily update\"" +
"}";
request.doc(jsonString, XContentType.JSON);
UpdateResponse updateResponse = client.update(
request, RequestOptions.DEFAULT);
client.close();
}
/**
* delete api
* @throws IOException
*/
@Test
public void test8() throws IOException {
DeleteRequest request = new DeleteRequest(
"posts",
"doc",
"1");
DeleteResponse deleteResponse = client.delete(
request, RequestOptions.DEFAULT);
client.close();
}
/**
* bulk api
* @throws IOException
*/
@Test
public void test9() throws IOException {
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest("posts", "doc", "3"));
request.add(new UpdateRequest("posts", "doc", "2")
.doc(XContentType.JSON,"other", "test"));
request.add(new IndexRequest("posts", "doc", "4")
.source(XContentType.JSON,"field", "baz"));
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
if (bulkResponse.hasFailures()) {
for (BulkItemResponse bulkItemResponse : bulkResponse) {
if (bulkItemResponse.isFailed()) {
BulkItemResponse.Failure failure =
bulkItemResponse.getFailure();
System.out.println(failure.getMessage());
}
}
}
client.close();
}
/**
* multi get api
* @throws IOException
*/
@Test
public void test10() throws IOException {
MultiGetRequest request = new MultiGetRequest();
request.add(new MultiGetRequest.Item(
"test",
"user",
"2"));
request.add(new MultiGetRequest.Item("test", "user", "4"));
MultiGetResponse responses = client.mget(request, RequestOptions.DEFAULT);
for (MultiGetItemResponse itemResponse : responses) {
GetResponse response = itemResponse.getResponse();
if (response.isExists()) {
String json = response.getSourceAsString();
System.out.println(json);
}
}
client.close();
}
