Java API之增删改操作

 


1、项目搭建

Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对 Elasticsearch服务进行访问。

先 IDEA 开发工具中创建简单的 java se Maven 项目(模块也可),如下:

修改 pom 文件,增加 Maven 依赖关系如下:

复制代码
  1. <dependencies>
  2. <dependency>
  3. <groupId>junit</groupId>
  4. <artifactId>junit</artifactId>
  5. <version>4.11</version>
  6. <scope>test</scope>
  7. </dependency>
  8.  
  9. <dependency>
  10. <groupId>org.elasticsearch</groupId>
  11. <artifactId>elasticsearch</artifactId>
  12. <version>7.8.0</version>
  13. </dependency>
  14. <!-- elasticsearch 的客户端 -->
  15. <dependency>
  16. <groupId>org.elasticsearch.client</groupId>
  17. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  18. <version>7.8.0</version>
  19. </dependency>
  20. <!-- elasticsearch 依赖 2.x 的 log4j -->
  21. <dependency>
  22. <groupId>org.apache.logging.log4j</groupId>
  23. <artifactId>log4j-api</artifactId>
  24. <version>2.8.2</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.apache.logging.log4j</groupId>
  28. <artifactId>log4j-core</artifactId>
  29. <version>2.8.2</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>com.fasterxml.jackson.core</groupId>
  33. <artifactId>jackson-databind</artifactId>
  34. <version>2.9.9</version>
  35. </dependency>
  36. </dependencies>
复制代码

 

2、Elasticsearch 客户端对象

代码如下:

复制代码
  1. import java.io.IOException;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. public class HelloElasticsearch {
  6. public static void main(String[] args) throws IOException {
  7. // 创建客户端对象
  8. RestHighLevelClient client = new RestHighLevelClient(
  9. RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
  10. // ...
  11. System.out.println("ES客户端对象:" + client);
  12. // 关闭客户端连接
  13. client.close();
  14. }
  15. }
复制代码

响应如下:

 

3、索引操作

3.1、创建索引

复制代码
  1. package org.example;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
  4. import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.client.RestClient;
  7. import org.elasticsearch.client.RestHighLevelClient;
  8. import java.io.IOException;
  9. public class CreateIndex {
  10. public static void main(String[] args) throws IOException {
  11. // 创建客户端对象
  12. RestHighLevelClient client = new RestHighLevelClient(
  13. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  14. // 创建索引 - 请求对象
  15. CreateIndexRequest request = new CreateIndexRequest("user2");
  16. // 发送请求,获取响应
  17. CreateIndexResponse response = client.indices().create(request,
  18. RequestOptions.DEFAULT);
  19. boolean acknowledged = response.isAcknowledged();
  20. // 响应状态
  21. System.out.println("操作状态 = " + acknowledged);
  22. // 关闭客户端连接
  23. client.close();
  24. }
  25. }
复制代码

响应如下:

 再次查看索引可以看到已新建了该索引。

 

3.2、查询索引

复制代码
  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.client.RequestOptions;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. import org.elasticsearch.client.indices.GetIndexRequest;
  6. import org.elasticsearch.client.indices.GetIndexResponse;
  7. import java.io.IOException;
  8. public class SearchIndex {
  9. public static void main(String[] args) throws IOException {
  10. // 创建客户端对象
  11. RestHighLevelClient client = new RestHighLevelClient(
  12. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  13. // 查询索引 - 请求对象
  14. GetIndexRequest request = new GetIndexRequest("user2");
  15. // 发送请求,获取响应
  16. GetIndexResponse response = client.indices().get(request,
  17. RequestOptions.DEFAULT);
  18. System.out.println("aliases:"+response.getAliases());
  19. System.out.println("mappings:"+response.getMappings());
  20. System.out.println("settings:"+response.getSettings());
  21. client.close();
  22. }
  23. }
复制代码

响应如下:

 

3.3、删除索引

复制代码
  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  3. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.client.RestClient;
  6. import org.elasticsearch.client.RestHighLevelClient;
  7. import java.io.IOException;
  8. public class DeleteIndex {
  9. public static void main(String[] args) throws IOException {
  10. RestHighLevelClient client = new RestHighLevelClient(
  11. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  12. // 删除索引 - 请求对象
  13. DeleteIndexRequest request = new DeleteIndexRequest("user2");
  14. // 发送请求,获取响应
  15. AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);
  16. // 操作结果
  17. System.out.println("操作结果 : " + response.isAcknowledged());
  18. client.close();
  19. }
  20. }
复制代码

响应如下:

 

4、文档操作

由于频繁使用连接 Elasticsearch 和关闭它的代码,于是先对它进行重构。注意,项目 jdk 需保证在 1.8 或以上才能使用下面的 lambda 语法。

复制代码
  1. package org.util;
  2. import org.elasticsearch.client.RestHighLevelClient;
  3. public interface ElasticsearchTask {
  4. void doSomething(RestHighLevelClient client) throws Exception;
  5. }
复制代码
复制代码
  1. package org.util;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. public class ConnectElasticsearch{
  6. public static void connect(ElasticsearchTask task){
  7. // 创建客户端对象
  8. RestHighLevelClient client = new RestHighLevelClient(
  9. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  10. try {
  11. task.doSomething(client);
  12. // 关闭客户端连接
  13. client.close();
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }
复制代码

 

4.1、新增文档

先创建一个实体类,如下:

复制代码
  1. package org.entity;
  2. public class User {
  3. private String name; private Integer age; private String sex;
  4. public String getName() { return name; }
  5. public void setName(String name){ this.name = name; }
  6. public Integer getAge() { return age; }
  7. public void setAge(Integer age) { this.age = age; }
  8. public String getSex() { return sex; }
  9. public void setSex(String sex) { this.sex = sex; }
  10. }
复制代码

新增文档:

复制代码
  1. package org.example;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import org.elasticsearch.action.index.IndexRequest;
  4. import org.elasticsearch.action.index.IndexResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.common.xcontent.XContentType;
  7. import org.entity.User;
  8. import org.util.ConnectElasticsearch;
  9. public class InsertDoc {
  10. public static void main(String[] args) {
  11. ConnectElasticsearch.connect(client -> {
  12. // 新增文档 - 请求对象
  13. IndexRequest request = new IndexRequest();
  14. // 设置索引及唯一性标识
  15. request.index("user").id("1001");
  16. // 创建数据对象
  17. User user = new User();
  18. user.setName("zhangsan");
  19. user.setAge(30);
  20. user.setSex("男");
  21. ObjectMapper objectMapper = new ObjectMapper();
  22. String productJson = objectMapper.writeValueAsString(user);
  23. // 添加文档数据,数据格式为 JSON 格式
  24. request.source(productJson, XContentType.JSON);
  25. // 客户端发送请求,获取响应对象
  26. IndexResponse response = client.index(request, RequestOptions.DEFAULT);
  27. //3.打印结果信息
  28. System.out.println("_index:" + response.getIndex());
  29. System.out.println("_id:" + response.getId());
  30. System.out.println("_result:" + response.getResult());
  31. });
  32. }
  33. }
复制代码

输出如下:

通过查询文档也可以查看到已经成功创建该文档。

 

4.2、删除文档

复制代码
  1. import org.elasticsearch.action.delete.DeleteRequest;
  2. import org.elasticsearch.action.delete.DeleteResponse;
  3. import org.elasticsearch.client.RequestOptions;
  4. import org.util.ConnectElasticsearch;
  5. public class DeleteDoc {
  6. public static void main(String[] args) {
  7. ConnectElasticsearch.connect(client -> {
  8. //创建请求对象
  9. DeleteRequest request = new DeleteRequest().index("user").id("1001");
  10. //客户端发送请求,获取响应对象
  11. DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
  12. //打印信息
  13. System.out.println(response.toString());
  14. });
  15. }
  16. }
复制代码

输出如下:

执行过后再次查询会发现已经无法查询到该文档。

 

4.3、修改文档

下面修改文档字段值:

复制代码
  1. import org.elasticsearch.action.update.UpdateRequest;
  2. import org.elasticsearch.action.update.UpdateResponse;
  3. import org.elasticsearch.client.RequestOptions;
  4. import org.elasticsearch.common.xcontent.XContentType;
  5. import org.util.ConnectElasticsearch;
  6. public class UpdateDoc {
  7. public static void main(String[] args) {
  8. ConnectElasticsearch.connect(client -> {
  9. // 修改文档 - 请求对象
  10. UpdateRequest request = new UpdateRequest();
  11. // 配置修改参数
  12. request.index("user").id("1001");
  13. // 设置请求体,对数据进行修改
  14. request.doc(XContentType.JSON, "sex", "女");
  15. // 客户端发送请求,获取响应对象
  16. UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
  17. System.out.println("_index:" + response.getIndex());
  18. System.out.println("_id:" + response.getId());
  19. System.out.println("_result:" + response.getResult());
  20. });
  21. }
  22. }
复制代码

输出如下:

 

4.4、批量操作

4.4.1、批量新增

复制代码
  1. import org.elasticsearch.action.bulk.BulkRequest;
  2. import org.elasticsearch.action.bulk.BulkResponse;
  3. import org.elasticsearch.action.index.IndexRequest;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.common.xcontent.XContentType;
  6. import org.util.ConnectElasticsearch;
  7. public class BatchInsertDoc {
  8. public static void main(String[] args) {
  9. ConnectElasticsearch.connect(client -> {
  10. //创建批量新增请求对象
  11. BulkRequest request = new BulkRequest();
  12. request.add(new
  13. IndexRequest().index("user").id("1001").source(XContentType.JSON, "name",
  14. "zhangsan"));
  15. request.add(new
  16. IndexRequest().index("user").id("1002").source(XContentType.JSON, "name",
  17. "lisi"));
  18. request.add(new
  19. IndexRequest().index("user").id("1003").source(XContentType.JSON, "name",
  20. "wangwu"));
  21. //客户端发送请求,获取响应对象
  22. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  23. //打印结果信息
  24. System.out.println("took:" + responses.getTook());
  25. System.out.println("items:" + responses.getItems());
  26. });
  27. }
  28. }
复制代码

输出如下:

 

4.4.2、批量删除

复制代码
  1. import org.elasticsearch.action.bulk.BulkRequest;
  2. import org.elasticsearch.action.bulk.BulkResponse;
  3. import org.elasticsearch.action.delete.DeleteRequest;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.util.ConnectElasticsearch;
  6. public class BatchDeleteDoc {
  7. public static void main(String[] args) {
  8. ConnectElasticsearch.connect(client -> {
  9. //创建批量删除请求对象
  10. BulkRequest request = new BulkRequest();
  11. request.add(new DeleteRequest().index("user").id("1001"));
  12. request.add(new DeleteRequest().index("user").id("1002"));
  13. request.add(new DeleteRequest().index("user").id("1003"));
  14. //客户端发送请求,获取响应对象
  15. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  16. //打印结果信息
  17. System.out.println("took:" + responses.getTook());
  18. System.out.println("items:" + responses.getItems());
  19. });
  20. }
  21. }
复制代码

输出如下:

 

posted @   wenxuehai  阅读(147)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
//右下角添加目录
点击右上角即可分享
微信分享提示