ElasticsearchBES

    High Level REST Client

    本文基于Java High Level REST Client 7.x版本,为您介绍Elasticsearch Java API的用法。

    准备工作

    • 安装Java,要求JDK版本为1.8及以上。
    • 创建Baidu Elasticsearch实例,版本7.4.2。

      注意 High Level Client能够向上兼容,但为了保证最大程度地使用最新版客户端的特性,推荐High Level Client版本与集群版本一致。

    • 创建Java Maven工程,并将如下的pom依赖添加到Java工程的pom.xml文件中。

    pom依赖

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.4.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.7</version>
    </dependency>

    示例

    以下代码为使用Create Index API创建索引,使用异步调用的方式写入文档,删除文档,使用Delete API删除该索引等操作的示例,可供参考。

    import java.io.IOException;
    import org.apache.http.HttpHost;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.apache.http.client.CredentialsProvider;
    import org.apache.http.impl.client.BasicCredentialsProvider;
    import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
    import org.elasticsearch.action.ActionListener;
    import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
    import org.elasticsearch.action.delete.DeleteRequest;
    import org.elasticsearch.action.delete.DeleteResponse;
    import org.elasticsearch.action.index.IndexRequest;
    import org.elasticsearch.action.index.IndexResponse;
    import org.elasticsearch.action.support.master.AcknowledgedResponse;
    import org.elasticsearch.client.RequestOptions;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestClientBuilder;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.elasticsearch.client.indices.CreateIndexRequest;
    import org.elasticsearch.client.indices.CreateIndexResponse;
    import org.elasticsearch.common.settings.Settings;
    import org.elasticsearch.common.xcontent.XContentBuilder;
    import org.elasticsearch.common.xcontent.XContentFactory;
    import org.elasticsearch.common.xcontent.XContentType;
    
    public class RestClientTest742 {
    
        public static void main(String[] args) {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            //访问用户名和密码为您创建Elasticsearch实例时设置的用户名和密码。
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("{访问用户名}", "{访问密码}"));
            // 通过builder创建rest client,配置http client的HttpClientConfigCallback。
            // ES HTTP URL 在Baidu Elasticsearch界面中可以查询
            RestClientBuilder builder = RestClient.builder(new HttpHost("{ES HTTP URL}", 8200))
                    .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        }
                    });
    
            // RestHighLevelClient实例通过REST low-level client builder进行构造。
            RestHighLevelClient client = new RestHighLevelClient(builder);
    
            try {
                //创建索引
                CreateIndexRequest createRequest = new CreateIndexRequest("my_index");
    
                //创建的每个索引都可以有与之关联的特定设置。
                createRequest.settings(Settings.builder()
                        .put("index.number_of_shards", 3)
                        .put("index.number_of_replicas", 1)
                        .put("index. refresh_interval", "10s")
                );
                // 创建索引时创建文档类型映射
                createRequest.mapping("{\n" +
                                "    \"message\": {\n" +
                                "      \"properties\": {\n" +
                                "        \"message\": {\n" +
                                "          \"type\": \"text\"\n" +
                                "        }\n" +
                                "      }\n" +
                                "    }\n" +
                                "  }",
                        XContentType.JSON);
                // 同步执行创建索引操作
                CreateIndexResponse createIndexResponse = client.indices().create(createRequest, RequestOptions.DEFAULT);
                System.out.println("create index successfully! response : " + createIndexResponse.toString());
    
                // 写入文档
                // 以XContentBuilder对象的形式提供,Elasticsearch 内部会帮我们生成JSON内容
                XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
                jsonBuilder.startObject();
                {
                    jsonBuilder.field("user", "Kobe Bryant");
                    jsonBuilder.field("number", 24);
                    jsonBuilder.field("message", "One of the greatest basketball players since the 21st century");
                }
                jsonBuilder.endObject();
                IndexRequest indexRequest = new IndexRequest("my_index").id("1").source(jsonBuilder);
                //异步执行写入文档操作,方法不会阻塞并立即返回。
                ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
                    @Override
                    public void onResponse(IndexResponse indexResponse) {
                        //执行成功时调用。 Response以参数方式提供
                        System.out.println("Index doc successfully! response : " + indexResponse.toString());
                    }
    
                    @Override
                    public void onFailure(Exception e) {
                        //在失败的情况下调用。 引发的异常以参数方式提供
                        System.out.println("Index doc fail!");
                        e.printStackTrace();
                    }
                };
                //异步执行索引请求需要将IndexRequest实例和ActionListener实例传递给异步方法:
                client.indexAsync(indexRequest, RequestOptions.DEFAULT, listener);
    
                // 删除文档
                DeleteRequest deleteRequest = new DeleteRequest("my_index").id("1");
                // 执行删除文档操作
                DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
                System.out.println("Delete doc successfully! \n" + deleteResponse.toString() + "\n" + deleteResponse.status());
    
                // 指定要删除的索引名称
                DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("my_index");
                // 执行删除索引操作
                AcknowledgedResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
                System.out.println("delete index successfully! response : " + deleteIndexResponse.toString());
            } catch (IOException ioException) {
                // 异常处理。
                ioException.printStackTrace();
            } finally {
                // 在不需要使用client后,将client关闭。
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    以上示例代码中带{}的参数需要替换为您具体业务的参数,详情请参见代码注释。

    更多Java High Level REST Client的使用特性,请参见Java High Level REST Client官方文档

    上一篇
    Java REST Client
    下一篇
    Low Level REST Client