如何使用Java高级REST客户端创建ElasticSearch索引?

j8ag8udp  于 2022-10-06  发布在  Java
关注(0)|答案(3)|浏览(236)

我浏览了这些文档,以便从Elastic的高级Java REST客户端创建一个ElasticSearch索引。它似乎跳过了使用我的弹性云账户进行身份验证的步骤。有没有人能给我指一下相关文件?

我启动了ElasticSearch示例,并将端点URL复制到客户机代码中。

我最初有连接错误,现在没有了。只有身份验证错误。因此,我非常确定我正在使用正确的端点URL进行连接,并且需要以某种方式进行身份验证--可能是使用标头。

现在,我看到了这个错误:
ElasticSearch异常[TYPE=SECURITY_EXCEPTION,REASON=ACTION[索引:数据/写入/索引]需要身份验证]

我可以使用以下命令查看我的ElasticSearch部署的端点,从 Postman 那里没有任何问题:Get https://:@d97215aee2.us-east-1.aws.found.io:9243

我还可以使用Postman中的这个命令创建索引...放入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?

基本上,我是这样更新我的URL的。

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

这对我来说不管用。我猜这个人不是在使用新的弹性高级REST客户端。我收到以下错误:

IPV6 java.io.IO异常::@d97265aee2.us-East-1.aws.fin.io:无效的org.glassfish.jersey.server.internal.process.MappableException:地址

2w3kk1z5

2w3kk1z51#

在这里找到答案: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的索引,并向该索引添加一个文档。

bwleehnv

bwleehnv2#

您可以使用ElasticSearch的同步和异步API来创建索引。但这取决于需求。

找到下面的ElasticSearch文档链接,这些文档解释了同步和异步API的使用。https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-create-index.html

示例代码:-Synchronous 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);

异步接口:-

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();
rn0zuynd

rn0zuynd3#

如果您知道如何通过API插入文档,那么这种方式将使您更容易执行任何类似的API操作(删除、发布、放置...)首先,您将需要RestHighLevelClient以及您需要做的所有工作

String index = "/indexName/_doc";
Request request = new Request("POST", index);
request.setJsonEntity(
      "{ "message": " example add insert" }"
);

client.getLowLevelClient().performRequest(request);

这将像API一样执行。

相关问题