要想知道ES怎么具体实现对数据的操作,我们首先应该了解一下什么叫做restful编码风格,因为es的具体操作都是restful风格的。
1.RESTful风格
RESTful 是一种软件架构风格,用于创建可扩展的网络服务。它使用 HTTP 方法(如 GET、POST、PUT、DELETE)来执行 CRUD 操作(创建、读取、更新、删除)。RESTful API 通常具有以下特征:
资源导向:所有内容都是资源,每个资源都有唯一的 URI。
无状态:每个请求都是独立的,服务器不存储客户端的状态。
使用标准方法:使用 HTTP 动词来表示操作。
可缓存:响应可以被客户端缓存以提高性能。
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.web.bind.annotation.*;import java.util.Map;@RestController
@RequestMapping("/api/documents")
public class DocumentController {private final ElasticsearchClient client;public DocumentController() {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());this.client = new ElasticsearchClient(transport);}@PostMapping("/{indexName}/{docId}")public String addDocument(@PathVariable String indexName, @PathVariable String docId, @RequestBody Map<String, Object> document) throws Exception {client.index(i -> i.index(indexName).id(docId).document(document));return "Document added.";}@GetMapping("/{indexName}/{docId}")public Map<String, Object> getDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {GetResponse<Map<String, Object>> response = client.get(g -> g.index(indexName).id(docId), Map.class);return response.source();}@DeleteMapping("/{indexName}/{docId}")public String deleteDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {client.delete(d -> d.index(indexName).id(docId));return "Document deleted.";}
}
- URI 设计:API 路径如
/api/documents/{indexName}/{docId}
用于操作特定索引和文档。 - HTTP 方法:使用
@PostMapping
、@GetMapping
、@DeleteMapping
分别处理创建、读取和删除操作。 - 依赖注入:通过构造函数创建 Elasticsearch 客户端实例。
2.ES的具体操作
2.1添加具体依赖
在pom.xml里面添加下面的依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>co.elastic.clients</groupId><artifactId>elasticsearch-java</artifactId><version>8.4.0</version>
</dependency>
2.2控制器代码
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.*;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.Map;@RestController
@RequestMapping("/api")
public class ElasticsearchController {private final ElasticsearchClient client;public ElasticsearchController() {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());this.client = new ElasticsearchClient(transport);}// 创建索引@PostMapping("/index/{indexName}")public String createIndex(@PathVariable String indexName) throws Exception {CreateIndexResponse response = client.indices().create(c -> c.index(indexName));return response.acknowledged() ? "Index created." : "Index creation failed.";}// 删除索引@DeleteMapping("/index/{indexName}")public String deleteIndex(@PathVariable String indexName) throws Exception {DeleteIndexResponse response = client.indices().delete(d -> d.index(indexName));return response.acknowledged() ? "Index deleted." : "Index deletion failed.";}// 添加文档@PostMapping("/document/{indexName}/{docId}")public String addDocument(@PathVariable String indexName, @PathVariable String docId, @RequestBody Map<String, Object> document) throws Exception {client.index(i -> i.index(indexName).id(docId).document(document));return "Document added.";}// 获取文档@GetMapping("/document/{indexName}/{docId}")public Map<String, Object> getDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {GetResponse<Map<String, Object>> response = client.get(g -> g.index(indexName).id(docId), Map.class);return response.source();}// 删除文档@DeleteMapping("/document/{indexName}/{docId}")public String deleteDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {client.delete(d -> d.index(indexName).id(docId));return "Document deleted.";}// 批量插入文档@PostMapping("/bulk/{indexName}")public String bulkInsert(@PathVariable String indexName, @RequestBody List<Map<String, Object>> documents) throws Exception {BulkRequest.Builder br = new BulkRequest.Builder();for (int i = 0; i < documents.size(); i++) {br.operations(op -> op.index(idx -> idx.index(indexName).id(String.valueOf(i)).document(documents.get(i))));}BulkResponse result = client.bulk(br.build());return result.errors() ? "Bulk insert had errors." : "Bulk insert completed.";}
}
2.2.1控制器类
@RestController
@RequestMapping("/api")
public class ElasticsearchController {
@RestController:标记这个类为一个 RESTful 控制器。
@RequestMapping("/api"):为所有方法定义基础路径 /api。
2.2.2Elasticsearch 客户端初始化
private final ElasticsearchClient client;public ElasticsearchController() {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());this.client = new ElasticsearchClient(transport);
}
创建一个 ElasticsearchClient
实例,用于与 Elasticsearch 通信。
连接到本地运行的 Elasticsearch 实例(localhost:9200
)。 这里的localhost可以修改成服务器地址
2.2.3创建索引
@PostMapping("/index/{indexName}")
public String createIndex(@PathVariable String indexName) throws Exception {CreateIndexResponse response = client.indices().create(c -> c.index(indexName));return response.acknowledged() ? "Index created." : "Index creation failed.";
}
@PostMapping("/index/{indexName}")
:处理 POST 请求,路径中包含索引名称。
使用 client.indices().create()
创建索引。
返回创建结果。
2.2.4删除索引
@DeleteMapping("/index/{indexName}")
public String deleteIndex(@PathVariable String indexName) throws Exception {DeleteIndexResponse response = client.indices().delete(d -> d.index(indexName));return response.acknowledged() ? "Index deleted." : "Index deletion failed.";
}
@DeleteMapping("/index/{indexName}")
:处理 DELETE 请求,路径中包含索引名称。
使用 client.indices().delete()
删除索引。
返回删除结果。
2.2.5添加文档
@PostMapping("/document/{indexName}/{docId}")
public String addDocument(@PathVariable String indexName, @PathVariable String docId, @RequestBody Map<String, Object> document) throws Exception {client.index(i -> i.index(indexName).id(docId).document(document));return "Document added.";
}
@PostMapping("/document/{indexName}/{docId}")
:处理 POST 请求,包含索引名称和文档 ID。
@RequestBody Map<String, Object> document
:从请求体中获取文档内容。
使用 client.index()
添加文档。
2.2.6获取文档
@GetMapping("/document/{indexName}/{docId}")
public Map<String, Object> getDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {GetResponse<Map<String, Object>> response = client.get(g -> g.index(indexName).id(docId), Map.class);return response.source();
}
@GetMapping("/document/{indexName}/{docId}")
:处理 GET 请求,路径中包含索引名称和文档 ID。
使用 client.get()
获取文档,返回文档内容。
2.2.7删除文档
@DeleteMapping("/document/{indexName}/{docId}")
public String deleteDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {client.delete(d -> d.index(indexName).id(docId));return "Document deleted.";
}
@DeleteMapping("/document/{indexName}/{docId}")
:处理 DELETE 请求,路径中包含索引名称和文档 ID。
使用 client.delete()
删除文档。
2.2.8批量插入文档
@PostMapping("/bulk/{indexName}")
public String bulkInsert(@PathVariable String indexName, @RequestBody List<Map<String, Object>> documents) throws Exception {BulkRequest.Builder br = new BulkRequest.Builder();for (int i = 0; i < documents.size(); i++) {br.operations(op -> op.index(idx -> idx.index(indexName).id(String.valueOf(i)).document(documents.get(i))));}BulkResponse result = client.bulk(br.build());return result.errors() ? "Bulk insert had errors." : "Bulk insert completed.";
}
@PostMapping("/bulk/{indexName}")
:处理 POST 请求,路径中包含索引名称。
@RequestBody List<Map<String, Object>> documents
:从请求体中获取多个文档。
使用 BulkRequest.Builder
进行批量操作。
返回批量插入结果。
2.3启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class ElasticsearchApplication {public static void main(String[] args) {SpringApplication.run(ElasticsearchApplication.class, args);}
}
3.总结
索引操作:使用 POST 和 DELETE 方法创建和删除索引。
文档操作:使用 POST、GET 和 DELETE 方法进行文档的添加、读取和删除。
批处理:通过 POST 方法实现批量插入文档。
依赖注入:通过构造函数创建 Elasticsearch 客户端实例。