1Java High Level REST Client说明

Java High Level REST Client6.0.0开始加入的,目的是以java面向对象的方式来进行请求、响应处理。每个API支持同步/异步两种方式,同步方法直接返回一个结果对象。异步的方法以async为后缀,通过listener参数来通知结果。高级java REST 客户端依赖Elasticsearch core project

 

兼容性说明:依赖 java1.8  Elasticsearch core project,请使用与服务端ES版本一致的客户端版本。

 

2Elasticsearch服务搭建

文章中使用Elasticsearch6.5.4版本,该版本在windows启动时会出现以下异常

[2019-06-30T12:12:58,471][INFO][o.e.p.PluginsService     ] [JP55XpU] noplugins loaded
[2019-06-30T12:13:09,651][INFO][o.e.x.s.a.s.FileRolesStore] [JP55XpU] parsed [0] roles from file[D:\devtools\elasticsearch-6.5.4\config\roles.yml]
[2019-06-30T12:13:10,844][ERROR][o.e.b.Bootstrap          ] [JP55XpU] Exception
org.elasticsearch.ElasticsearchException:X-Pack is not supported and Machine Learning is not available for [windows-x86];you can use the other X-Pack features (unsupportedby settingxpack.ml.enabledfalse in elasticsearch.yml
      atorg.elasticsearch.xpack.ml.MachineLearningFeatureSet.isRunningOnMlPlatform(MachineLearningFeatureSet.java:104)~[?:?]
      atorg.elasticsearch.xpack.ml.MachineLearningFeatureSet.isRunningOnMlPlatform(MachineLearningFeatureSet.java:95)~[?:?]

关于该异常可以参考如下这两篇文章的其中的任何一种解决方案

jdkjre安装成64位:

https://www.cnblogs.com/alvin-niu/p/9747361.html

关闭X-Pack支持:

https://blog.csdn.net/fanrenxiang/article/details/81358332


3Maven集成Java High LevelREST Client

<dependencies>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>6.5.4</version>
    </dependency>

<dependency>

      <groupId>org.apache.logging.log4j</groupId>

      <artifactId>log4j-core</artifactId>

      <version>2.12.0</version>

   </dependency>

</dependencies>


4Java High Level REST Client 初始化

public static RestHighLevelClient getClient(){

    RestHighLevelClient client = new RestHighLevelClient(

            RestClient.builder(

                    new HttpHost("localhost"9200"http")));

    return client;

}

可以给定集群的多个节点地址,构建RestHighLevelClient对象

public static RestHighLevelClient getClient(){

    RestHighLevelClient client = new RestHighLevelClient(

            RestClient.builder(

                    new HttpHost("localhost"9200"http"),

                    new HttpHost("localhost"9100"http")));

    return client;

}

Client 不再使用了,记得关闭它:

client.close();

API及用法示例,可以参考官网API

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-supported-apis.html

 

5Create Index(创建索引)

同步方式创建Index

public static void createIndexSync(){

    RestHighLevelClient client=null;

    try{

        client = getClient();

        // 1、创建 创建索引request 参数:索引名java

        CreateIndexRequest request = new CreateIndexRequest("java");



        // 2、设置索引的settings

        request.settings(Settings.builder().put("index.number_of_shards"3// 分片数

                .put("index.number_of_replicas"2// 副本数



        );



        // 3、设置索引的mappings

        request.mapping("_doc",

                "  {\n" +

                        "    \"_doc\": {\n" +

                        "      \"properties\": {\n" +

                        "        \"message\": {\n" +

                        "          \"type\": \"text\"\n" +

                        "        }\n" +

                        "      }\n" +

                        "    }\n" +

                        "  }",

                XContentType.JSON);



        // 4、 设置索引的别名

        request.alias(new Alias("it"));



        RequestOptions requestOptions = RequestOptions.DEFAULT;

        // 5、 发送请求

        // 5.1 同步方式发送请求

        CreateIndexResponse createIndexResponse = client.indices().create(request,requestOptions);



        // 6、处理响应

        boolean acknowledged = createIndexResponse.isAcknowledged();

        boolean shardsAcknowledged = createIndexResponse

                .isShardsAcknowledged();

        System.out.println("acknowledged = " + acknowledged);

        System.out.println("shardsAcknowledged = " + shardsAcknowledged);



    } catch (Exception e) {

        e.printStackTrace();

    }finally {

        try{

            client.close();

        } catch (Exception e) {

        }

    }

}


异步方式创建Index

public static void createIndexAsync(){

    RestHighLevelClient client=null;

    try{

        client = getClient();

        // 1、创建 创建索引request 参数:索引名java

        CreateIndexRequest request = new CreateIndexRequest("python");



        // 2、设置索引的settings

        request.settings(Settings.builder().put("index.number_of_shards"3// 分片数

                .put("index.number_of_replicas"2// 副本数



        );



        // 3、设置索引的mappings

        request.mapping("_doc",

                "  {\n" +

                        "    \"_doc\": {\n" +

                        "      \"properties\": {\n" +

                        "        \"message\": {\n" +

                        "          \"type\": \"text\"\n" +

                        "        }\n" +

                        "      }\n" +

                        "    }\n" +

                        "  }",

                XContentType.JSON);



        // 4、 设置索引的别名

        request.alias(new Alias("py"));



        RequestOptions requestOptions = RequestOptions.DEFAULT;

        // 5、 发送请求



        // 5.1 异步方式发送请求

        ActionListener<CreateIndexResponse> listener = new ActionListener<CreateIndexResponse>() {



            public void onResponse(

                    CreateIndexResponse createIndexResponse
{

                // 6、处理响应

                boolean acknowledged = createIndexResponse.isAcknowledged();

                boolean shardsAcknowledged = createIndexResponse

                        .isShardsAcknowledged();

                System.out.println("acknowledged = " + acknowledged);

                System.out.println(

                        "shardsAcknowledged = " + shardsAcknowledged);

            }



            public void onFailure(Exception e{

                System.out.println("创建索引异常:" + e.getMessage());

            }

        };

        client.indices().createAsync(request, RequestOptions.DEFAULT, listener);



    } catch (Exception e) {

        e.printStackTrace();

    }finally {

        try{

            client.close();

        } catch (Exception e) {

        }

    }

}