springboot集成es高级客户端给出增伤改查代码
当使用Spring Boot集成Elasticsearch高级客户端进行增删改查操作时,需要先引入相关依赖和配置,然后编写相应的代码。
- 引入依赖和配置
在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>版本号</version>
</dependency>
在application.properties或application.yml中添加Elasticsearch的配置:
spring.elasticsearch.rest.uris=es的地址
- 编写增删改查代码
下面是一个简单的示例,演示如何使用Elasticsearch高级客户端进行增删改查操作:
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ElasticsearchService {
@Autowired
private RestHighLevelClient client;
public void createIndex(String index, String id, String json) {
IndexRequest request = new IndexRequest(index).id(id).source(json, XContentType.JSON);
try {
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
// 处理响应结果
} catch (Exception e) {
e.printStackTrace();
}
}
public void getIndex(String index, String id) {
GetRequest request = new GetRequest(index).id(id);
try {
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 处理响应结果
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateIndex(String index, String id, String json) {
UpdateRequest request = new UpdateRequest(index, id).doc(json, XContentType.JSON);
try {
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
// 处理响应结果
} catch (Exception e) {
e.printStackTrace();
}
}
public void deleteIndex(String index, String id) {
DeleteRequest request = new DeleteRequest(index).id(id);
try {
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
// 处理响应结果
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码中,createIndex方法用于创建索引并插入文档,getIndex方法用于根据id获取文档,updateIndex方法用于更新文档,deleteIndex方法用于删除文档。
注意:上述代码只是简单示例,实际使用时可能需要更复杂的操作,例如搜索、分页等,可以根据具体需求进行扩展。
原文地址: http://www.cveoy.top/t/topic/i5we 著作权归作者所有。请勿转载和采集!