如何使用JAVA高级REST客户端创建弹性搜索索引?

时间:2020-03-01 21:35:13

标签: java elasticsearch resthighlevelclient

我正在浏览这些文档,以从Elastic的高级JAVA REST客户端创建一个弹性搜索索引。似乎跳过了使用我的弹性云帐户进行身份验证的步骤。 有人可以指出相关文档吗?

我启动了弹性搜索实例,并将端点URL复制到了我的客户端代码中。

我最初有连接错误,现在没有。仅身份验证错误。因此,我很确定我正在连接正确的端点URL,并且需要以某种方式进行身份验证-也许使用标头。

现在,我看到此错误:

Elasticsearch异常[类型= security_exception,原因=操作 [indices:data / write / index]需要认证]

使用此命令,我可以查看我的Elastic Search部署的端点,而Postman则没有问题: GET https://:@ d97215aee2.us-east-1.aws.found.io:9243

我还可以使用邮递员的此命令创建索引... 放入https://elastic:4YQIMXfoSZ9mXPgY1fj7T5BU@d97218f74f6d48489b355dd7d665aee2.us-east-1.aws.found.io:9243/。但是,我无法通过Java代码执行相同的操作。

这是我的Java代码的状态。这些教程页面中的代码差不多。

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.4/java-rest-high-document-index.html

import java.io.IOException;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

@Path("/elasticsearch")
public class ElasticSearchService {

    @POST
    public void createElasticIndex() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                    new HttpHost("d9<deleted a bunch of characters for privacy>7d665aee2.us-east-1.aws.found.io", 9243, "https")));


        IndexRequest request = new IndexRequest(
                "posts",
                "doc",
                "1");
        String jsonString = "{" +
                "\"user\":\"kimchy\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";
        request.source(jsonString, XContentType.JSON);

        client.close();
    }    
}

我还尝试按照这篇文章的建议,使用用户名和密码更新URL地址:ElasticSearch authentication error with ElasticCloud?

基本上,我是这样更新我的网址的...

        RestClient.builder(
                new HttpHost(
                        "<my user name>:<my password>@d97218<hidden characters>d665aee2.us-east-1.aws.found.io",
                        9243, "https")));

这对我不起作用。我猜这个人没有使用新的Elastic 高级REST客户端。 我收到此错误:

org.glassfish.jersey.server.internal.process.MappableException: java.io.IOException :: @ d97265aee2.us-east-1.aws.found.io:无效的IPv6地址

2 个答案:

答案 0 :(得分:0)

在这里找到答案:enter link description here

有效的更新代码:

import java.io.IOException;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

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.ElasticsearchException;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;

@Path("/elasticsearch")
public class ElasticSearchService {
    private static final String ELASTIC_SEARCH_USER_NAME = <my elastic search username>;
    private static final String ELASTIC_SEARCH_PASSWORD = <my elastic search password>;
    private static final String ELASTIC_SEARCH_ENDPOINT_URL = <my elastic search endpoint url>
    private static final Integer ELASTIC_SEARCH_PORT = 9243;

    @POST
    public void createElasticIndex() throws IOException {

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(ELASTIC_SEARCH_USER_NAME, ELASTIC_SEARCH_PASSWORD));

        RestClientBuilder builder = RestClient
                .builder(new HttpHost(
                        ELASTIC_SEARCH_ENDPOINT_URL,
                        ELASTIC_SEARCH_PORT, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        RestHighLevelClient client = new RestHighLevelClient(builder);

        IndexRequest request = new IndexRequest(
                "contacts",
                "doc",
                "1");
        String jsonString = "{" +
                "\"user\":\"frank\"," +
                "\"postDate\":\"2020-03-02\"," +
                "\"message\":\"created this document from Java\"" +
                "}";
        request.source(jsonString, XContentType.JSON);

        try {
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            System.out.println(response);

        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.CONFLICT) {
            }
        }

        client.close();
    }

}

此代码创建一个名为contacts的索引,并将文档添加到该索引。

答案 1 :(得分:0)

您可以使用弹性搜索的同步和异步API来创建索引。但这取决于要求。

找到弹性搜索文档的以下链接,其中解释了同步和异步API的用法。 https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-create-index.html

示例代码:- 同步API:-

    CreateIndexRequest request = new CreateIndexRequest("twitter");
    request.settings(Settings.builder() 
        .put("index.number_of_shards", 3)
        .put("index.number_of_replicas", 2)
    );

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

异步API:-

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

异步API增加了线程的优势,并使API可以更好地工作。异步API的关注点是接收响应。以下是您如何获得回复的代码段。

PlainActionFuture<CreateIndexResponse > future = new PlainActionFuture<>();
client.indices().createAsync(request, RequestOptions.DEFAULT, future);
CreateIndexResponse response = future.actionGet();