使用ElasticSearch Java API时遇到错误 "missing authentication credentials for REST request"
这是代码:
java
RestHighLevelClient esClient =
new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));
CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = esClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("创建索引:" + acknowledged);
esClient.close();
原因是请求没有发送用户名和密码,没有通过验证导致的。
- 解决方法,使用RestClientBuilder,将ES登录用户名和密码添加进去,修改如下:
java
RestClientBuilder build = RestClient.builder(new HttpHost("localhost",9200,"http"));
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "e5nTeAjoHTTPg--WgM49")); //用户名和密码
build.setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncClientBuilder) -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient esClient = new RestHighLevelClient(build);
CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = esClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("创建索引:" + acknowledged);
esClient.close();
顺利解决:
- 还有一种解决方法,就是取消身份验证(不推荐)。
进入ES的config文件,找到并打开文件elasticsearch.yml。
找到以下配置,并改为false,如下:
# Enable security features
xpack.security.enabled: false
xpack.security.enrollment.enabled: false