简体   繁体   English

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

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

I was going through these docs to create an elastic search index from Elastic's high level JAVA REST client.我正在浏览这些文档以从 Elastic 的高级 JAVA REST 客户端创建弹性搜索索引。 It seems to skip over steps for authenticating with my elastic cloud account.它似乎跳过了使用我的弹性云帐户进行身份验证的步骤。 Can someone please point me toward the relevant documentation?有人可以指出我的相关文档吗?

I launched my elastic search instance and copied the endpoint URL into my client code.我启动了我的弹性搜索实例并将端点 URL 复制到我的客户端代码中。

I initially had connection errors and now there are none.我最初有连接错误,现在没有。 Only authentication errors.只有身份验证错误。 So, I'm pretty sure I'm connecting with the correct endpoint URL and need to authenticate somehow - perhaps with a header.所以,我很确定我正在使用正确的端点 URL 进行连接,并且需要以某种方式进行身份验证 - 可能带有标头。

Now, I am seeing this error:现在,我看到了这个错误:

Elasticsearch exception [type=security_exception, reason=action [indices:data/write/index] requires authentication] Elasticsearch 异常 [type=security_exception, reason=action [indices:data/write/index] 需要身份验证]

I can view the endpoint of my Elastic Search deployment with no problems from Postman with this command: GET https://:@d97215aee2.us-east-1.aws.found.io:9243我可以使用以下命令从 Postman 查看我的 Elastic Search 部署的端点,没有问题:GET https://:@d97215aee2.us-east-1.aws.found.io:9243

I can also create an index using this command from Postman... PUT https://elastic:4YQIMXfoSZ9mXPgY1fj7T5BU@d97218f74f6d48489b355dd7d665aee2.us-east-1.aws.found.io:9243/ .我还可以使用 Postman 的此命令创建索引... PUT https://elastic:4YQIMXfoSZ9mXPgY1fj7T5BU@d97218f74f6d48489b355dd7d665aee2.us-east-1.aws.found.io:9243/ Yet, I cannot do the same from the Java code.然而,我不能从 Java 代码中做同样的事情。

Here is the state of my Java code.这是我的 Java 代码的状态。 It is pretty much the code from these tutorial pages.这几乎是来自这些教程页面的代码。

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/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 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();
    }    
}

I have also tried updating the URL address with our username and password as suggested by this post: ElasticSearch authentication error with ElasticCloud?我还尝试按照这篇文章的建议使用我们的用户名和密码更新 URL 地址: ElasticSearch authentication error with ElasticCloud?

Essentially, I updated my URL like this...基本上,我像这样更新了我的网址......

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

This did not work for me.这对我不起作用。 I am guessing this person wasn't using the new Elastic High Level REST client.我猜这个人没有使用新的 Elastic High Level REST 客户端。 I received this error:我收到此错误:

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

Found the answer here: enter link description here在这里找到答案:在此处输入链接描述

Updated code that works:更新的代码有效:

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

}

This code creates an index called contacts and adds a document to that index.此代码创建一个名为contacts的索引并将文档添加到该索引。

You can use both synchronous and asynchronous API of elastic search to create index.您可以使用弹性搜索的同步和异步 API 来创建索引。 But it depends on requirement.但这取决于要求。

Find the below link of elastic search documentation which explain both synchronous and asynchronous API use.找到解释同步和异步 API 使用的弹性搜索文档的以下链接。 https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-create-index.html https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-create-index.html

Sample code:- Synchronous API :-示例代码:- 同步 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);

Asynchronous API:-异步 API:-

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

Asynchronous API adds advantages of thread and makes API to work better way.异步 API 增加了线程的优势并使 API 以更好的方式工作。 Concern in asynchronous API is to receive response.异步 API 中的关注点是接收响应。 Below is the snippet how can you receive response.以下是您如何收到回复的片段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring 数据弹性搜索与 Java 高级 REST 客户端 - Spring Data Elastic Search vs Java High Level REST Client 为什么在弹性搜索中引入 Java 高级 REST 客户端? - Why Java High Level REST Client got introduced in Elastic search? Elastic Search 7 高级客户端使用映射创建索引 - Elastic Search 7 High level Client Create Index with mapping 如何通过 Java 高级 rest 客户端在 Elastic Search 中使用多个字段进行搜索 - How to search using multiple fields in Elastic Search through Java high level rest client 如何通过 Java 高级 Rest 客户端访问安全弹性搜索 - How to hit Secure Elastic Search through Java High Level Rest Client 无法使用Java高级Rest客户端创建索引 - Not able to create index using Java high level Rest client 弹性搜索:将客户端传输到高级其余客户端 - Elastic Search: Transport Client to High Level Rest Client 通过 rest 高级客户端在弹性搜索中创建类型内部索引 - Creating type inside index in elastic search through rest high level client 为什么 filterQuery 在用于 JAVA 的 Elastic Search 的高级 REST 客户端中不起作用? - Why does filterQuery not work in Elastic Search's high level REST client for JAVA? 将映射与 Elastic Search 的高级 REST JAVA 客户端异步放置 - 不推荐使用的错误 - Put mapping with Elastic Search's High level REST JAVA client asynchronously - deprecated error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM