簡體   English   中英

如何使用 JAVA 高級 REST 客戶端創建彈性搜索索引?

[英]How can I create an elastic search index with the JAVA high level REST client?

我正在瀏覽這些文檔以從 Elastic 的高級 JAVA REST 客戶端創建彈性搜索索引。 它似乎跳過了使用我的彈性雲帳戶進行身份驗證的步驟。 有人可以指出我的相關文檔嗎?

我啟動了我的彈性搜索實例並將端點 URL 復制到我的客戶端代碼中。

我最初有連接錯誤,現在沒有。 只有身份驗證錯誤。 所以,我很確定我正在使用正確的端點 URL 進行連接,並且需要以某種方式進行身份驗證 - 可能帶有標頭。

現在,我看到了這個錯誤:

Elasticsearch 異常 [type=security_exception, reason=action [indices:data/write/index] 需要身份驗證]

我可以使用以下命令從 Postman 查看我的 Elastic Search 部署的端點,沒有問題:GET https://:@d97215aee2.us-east-1.aws.found.io:9243

我還可以使用 Postman 的此命令創建索引... PUT 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 High Level REST 客戶端。 我收到此錯誤:

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

在這里找到答案:在此處輸入鏈接描述

更新的代碼有效:

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的索引並將文檔添加到該索引。

您可以使用彈性搜索的同步和異步 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(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM