elasticsearch版本类型统一7.8.0
1、项目架构如下
2、配置文件(进行验证登陆的时候需要输入账号、密码)
/**
* @author yfc
* @date 2020/8/17
* @description elasticsearch配置文件
* @parmas
*/
@Configuration
public class ElasticsearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
//集群构建多个,非集群构建一个 RestClient.builder(
// new HttpHost("localhost", 9200, "http"),
// new HttpHost("localhost", 9201, "http")))
//1、用户认证对象
final CredentialsProvider credentialsProvider=new BasicCredentialsProvider();
//2、设置账号密码
credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","elastic"));
//3、创建rest对象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("121.0.0.170", 9200, "http")).setHttpClientConfigCallback(
new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}
));
return client;
}
}
没有设置账号密码的配置文件如下:
@Bean
public RestHighLevelClient restHighLevelClient(){
//集群构建多个,非集群构建一个 RestClient.builder(
// new HttpHost("localhost", 9200, "http"),
// new HttpHost("localhost", 9201, "http")))
//创建客户端对象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("121.0.0.170", 9200, "http")));
return client;
}
3、测试类
@SpringBootTest
class DemoApplicationTests {
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* @Author yfc
* @Date 2020/8/17
* @Despration 测试索引的创建
* @Param
*/
@Test
void testCreateIndex() throws IOException {
//1、创建索引请求
CreateIndexRequest request=new CreateIndexRequest("yfc");
//2、执行请求 IndicesClient
CreateIndexResponse createIndexResponse=restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
}
4、创建索引成功