使用ElasticSearch Java API时遇到错误 "missing authentication credentials for REST request"
这是代码:
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登录用户名和密码添加进去,修改如下:
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();
顺利解决: