ElasticSearch java 客戶端開發

1. ES 啓動監聽兩個端口: 9200與9300的區別

  9300是Tcp協議端口:經過tcp協議通信,ES集羣之間是經過9300進行通信,java客戶端(TransportClient)的方式是也是以tcp協議在9300 端口上與集羣進行通訊。html

  9200是Http協議端口:主要用於外部通信,外部使用RESTful接口進行訪問。      以下圖:url地址上輸入對應的RESTful接口 就能夠訪問。java

 

 

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請求。既然如此,這裏就直接用高級了。json

 

2.2 Maven倉庫配置

    高級客戶端要與Elasticsearch集羣進行通訊,主版本號須要一致,次版本號沒必要相同。api

    本案例,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。 elasticsearch

1  <dependency>
2       <groupId>org.elasticsearch.client</groupId>
3       <artifactId>elasticsearch-rest-high-level-client</artifactId>
4       <version>6.6.2</version>
5     </dependency>
View Code

 

鏈接到es集羣 RestHighLevelClient實例須要低級客戶端構建器來構建tcp

以下所示: RestHighLevelClient client = new RestHighLevelClient(ide

      RestClient.builder(
      new HttpHost("192.168.20.210", 9200, "http"))post

    ); fetch

高級客戶端將在內部建立低級客戶端,用來執行基於提供的構建器的請求,並 管理其生命週期。 

當再也不須要時,須要關閉高級客戶端實例,以便它所使用的全部資源以及底層 的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);

   代碼官方文檔提供實例:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.8/java-rest-high-document-index.html

 

 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     }
View Code

 

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

  

  

 

 

 

 

 

 

參考文獻:http://www.javashuo.com/article/p-cdtukkgq-a.html

相關文章
相關標籤/搜索