<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class EsConfig {
private String host;
private String post;
@Bean
public ElasticsearchClient client(){
//
// 1. 创建带认证的RestClient
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "admin") // 替换为你的真实密码
);
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider)
).build();
// 2. 创建Java客户端
ElasticsearchClient client = new ElasticsearchClient(
new RestClientTransport(restClient, new JacksonJsonpMapper())
);
return client;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
}
测试
@Resource
private ElasticsearchClient client;
private static final String TEST_LATEST = "test_latest";
@Override
public boolean addTest(TestModel testModel , String id) {
try {
IndexResponse response = client.index(i -> i
.index(TEST_LATEST)
.id(id)
.document(testModel )
);
System.out.println("插入成功"+JSONObject.toJSONString(response));
} catch (IOException e) {
System.out.println("插入失败");
throw new RuntimeException(e);
}
return false;
}
@Override
public Map<String, Object> getTest(String id) {
try {
GetResponse<Map> getResponse = client.get(g -> g
.index(TEST_LATEST)
.id(id),
Map.class
);
if (getResponse.found()) {
System.out.println("单个文档: " + getResponse.source());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return Map.of();
}
@Override
public boolean updateTest(TestModel testModel, String id) {
try {
UpdateResponse<TestModel > updateResponse = client.update(u -> u
.index(TEST_LATEST) // 索引名称
.id(id) // 文档ID
.doc(testModel) // 新的完整文档内容(会替换旧文档)
.docAsUpsert(true) // 如果文档不存在,则插入新文档(类似"upsert")
, TestModel .class);
System.out.println("修改成功");
System.out.println("文档更新成功!"+updateResponse.result());
GetResponse<TestModel > getResponse = client.get(g -> g
.index(TEST_LATEST)
.id(id),
TestModel .class
);
System.out.println("更新后的文档: " + getResponse.source());
} catch (IOException e) {
throw new RuntimeException(e);
}
return false;
}
@Override
public boolean deleteTest(String id) {
DeleteResponse deleteResponse = null;
try {
deleteResponse = client.delete(d -> d
.index(TEST_LATEST) // 索引名称
.id(id) // 文档ID
);
System.out.println("删除成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
return false;
}