使用 Java 客户端对 ElasticSearch 文档进行删改查

2年前 (2022) 程序员胖胖胖虎阿
208 0 0

松哥原创的 Spring Boot 视频教程已经杀青,感兴趣的小伙伴戳这里-->Spring Boot+Vue+微人事视频教程


前面和小伙伴们分享了通过 Java 客户端来添加 Es 文档,整体操作还是非常 Easy,今天我们来看看通过 Java 客户端对 Es 文档进行删改查。

以下是视频笔记:

注意,笔记只是视频内容的一个简要记录,因此笔记内容比较简单,完整的内容可以查看视频。

29.2 获取文档

根据 id 获取文档:

public class GetDoc {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost"9200"http"),
                new HttpHost("localhost"9201"http"),
                new HttpHost("localhost"9202"http")
        ));
        GetRequest request = new GetRequest("book""98");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println("response.getId() = " + response.getId());
        System.out.println("response.getIndex() = " + response.getIndex());
        if (response.isExists()) {
            //如果文档存在
            long version = response.getVersion();
            System.out.println("version = " + version);
            String sourceAsString = response.getSourceAsString();
            System.out.println("sourceAsString = " + sourceAsString);
        }else{
            System.out.println("文档不存在");
        }
        client.close();
    }
}

29.3 判断文档是否存在

判断文档是否存在和获取文档的 API 是一致的。只不过在判断文档是否存在时,不需要获取 source。

public class ExistsDoc {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost"9200"http"),
                new HttpHost("localhost"9201"http"),
                new HttpHost("localhost"9202"http")
        ));
        GetRequest request = new GetRequest("book""99");
        request.fetchSourceContext(new FetchSourceContext(false));
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println("exists = " + exists);
        client.close();
    }
}

29.4 删除文档

删除 id 为 99 的文档:

public class DeleteDoc {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost"9200"http"),
                new HttpHost("localhost"9201"http"),
                new HttpHost("localhost"9202"http")
        ));
        DeleteRequest request = new DeleteRequest("book""99");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println("response.getId() = " + response.getId());
        System.out.println("response.getIndex() = " + response.getIndex());
        System.out.println("response.getVersion() = " + response.getVersion());
        ReplicationResponse.ShardInfo shardInfo = response.getShardInfo();
        if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
            System.out.println("有分片存在问题");
        }
        if (shardInfo.getFailed() > 0) {
            for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                System.out.println("failure.reason() = " + failure.reason());
            }
        }
        client.close();
    }
}

删除文档的响应和添加文档成功的响应类似,可以对照着理解。

29.4 更新文档

通过脚本更新:

public class UpdateDoc {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost"9200"http"),
                new HttpHost("localhost"9201"http"),
                new HttpHost("localhost"9202"http")
        ));
        UpdateRequest request = new UpdateRequest("book""1");
        //通过脚本更新
        Map<String, Object> params = Collections.singletonMap("name""三国演义666");
        Script inline = new Script(ScriptType.INLINE, "painless""ctx._source.name=params.name", params);
        request.script(inline);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println("response.getId() = " + response.getId());
        System.out.println("response.getIndex() = " + response.getIndex());
        System.out.println("response.getVersion() = " + response.getVersion());
        if (response.getResult() == DocWriteResponse.Result.UPDATED) {
            System.out.println("更新成功!");
        }
        client.close();
    }
}

通过 JSON 更新:

public class UpdateDoc {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost"9200"http"),
                new HttpHost("localhost"9201"http"),
                new HttpHost("localhost"9202"http")
        ));
        UpdateRequest request = new UpdateRequest("book""1");
        request.doc("{\"name\": \"三国演义\"}", XContentType.JSON);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println("response.getId() = " + response.getId());
        System.out.println("response.getIndex() = " + response.getIndex());
        System.out.println("response.getVersion() = " + response.getVersion());
        if (response.getResult() == DocWriteResponse.Result.UPDATED) {
            System.out.println("更新成功!");
        }
        client.close();
    }
}

当然,这个 JSON 字符串也可以通过 Map 或者 XContentBuilder 来构建:

Map:

public class UpdateDoc {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost"9200"http"),
                new HttpHost("localhost"9201"http"),
                new HttpHost("localhost"9202"http")
        ));
        UpdateRequest request = new UpdateRequest("book""1");
        Map<String, Object> docMap = new HashMap<>();
        docMap.put("name""三国演义888");
        request.doc(docMap);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println("response.getId() = " + response.getId());
        System.out.println("response.getIndex() = " + response.getIndex());
        System.out.println("response.getVersion() = " + response.getVersion());
        if (response.getResult() == DocWriteResponse.Result.UPDATED) {
            System.out.println("更新成功!");
        }
        client.close();
    }
}

XContentBuilder:

public class UpdateDoc {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost"9200"http"),
                new HttpHost("localhost"9201"http"),
                new HttpHost("localhost"9202"http")
        ));
        UpdateRequest request = new UpdateRequest("book""1");
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
        jsonBuilder.startObject();
        jsonBuilder.field("name""三国演义666");
        jsonBuilder.endObject();
        request.doc(jsonBuilder);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println("response.getId() = " + response.getId());
        System.out.println("response.getIndex() = " + response.getIndex());
        System.out.println("response.getVersion() = " + response.getVersion());
        if (response.getResult() == DocWriteResponse.Result.UPDATED) {
            System.out.println("更新成功!");
        }
        client.close();
    }
}

也可以通过 upsert 方法实现文档不存在时就添加文档:

public class UpdateDoc {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost"9200"http"),
                new HttpHost("localhost"9201"http"),
                new HttpHost("localhost"9202"http")
        ));
        UpdateRequest request = new UpdateRequest("book""99");
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
        jsonBuilder.startObject();
        jsonBuilder.field("name""三国演义666");
        jsonBuilder.endObject();
        request.doc(jsonBuilder);
        request.upsert("{\"name\": \"红楼梦\",\"author\": \"曹雪芹\"}", XContentType.JSON);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println("response.getId() = " + response.getId());
        System.out.println("response.getIndex() = " + response.getIndex());
        System.out.println("response.getVersion() = " + response.getVersion());
        if (response.getResult() == DocWriteResponse.Result.UPDATED) {
            System.out.println("更新成功!");
        } else if (response.getResult() == DocWriteResponse.Result.CREATED) {
            System.out.println("文档添加成功");
        }
        client.close();
    }
}

ElasticSearch 基础知识:

  1. 打算出一个 ElasticSearch 教程,谁赞成,谁反对?
  2. ElasticSearch 从安装开始
  3. ElasticSearch 第三弹,核心概念介绍
  4. ElasticSearch 中的中文分词器该怎么玩?
  5. ElasticSearch 索引基本操作
  6. ElasticSearch 文档的添加、获取以及更新
  7. ElasticSearch 文档的删除和批量操作
  8. ElasticSearch 文档路由,你的数据到底存在哪一个分片上?
  9. ElasticSearch 并发的处理方式:锁和版本控制
  10. ElasticSearch 中的倒排索引到底是什么?
  11. ElasticSearch 动态映射与静态映射
  12. ElasticSearch 四种字段类型详解
  13. ElasticSearch 中的地理类型和特殊类型
  14. ElasticSearch 23 种映射参数详解
  15. ElasticSearch 如何配置某个字段的权重?
  16. ElasticSearch 23 种映射参数详解【3】
  17. ElasticSearch 映射模版
  18. ElasticSearch 搜索入门
  19. ElasticSearch 全文搜索怎么玩?
  20. ElasticSearch 打错字还能搜索到?试试 fuzzy query!
  21. ElasticSearch 复合查询,理解 Es 中的文档评分策略!
  22. 想搜索附近评分较高的餐厅,ElasticSearch 大显身手!
  23. ElasticSearch 如何像 MySQL 一样做多表联合查询?
  24. ElasticSearch 地理位置查询与特殊查询
  25. ElasticSearch 搜索高亮与排序
  26. ElasticSearch 指标聚合
  27. ElasticSearch 桶聚合
  28. ElasticSearch 管道聚合
  29. Java 操作 ElasticSearch,so easy!
  30. ElasticSearch Java 高级客户端索引操作~
  31. ElasticSearch Java 高级客户端如何操作索引?
  32. 使用 Java 客户端添加 ElasticSearch 文档

今日干货

使用 Java 客户端对 ElasticSearch 文档进行删改查
刚刚发表
查看:
66666
回复:666

公众号后台回复 ssm,免费获取松哥纯手敲的 SSM 框架学习干货。

本文分享自微信公众号 - 江南一点雨(a_javaboy)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

相关文章

暂无评论

暂无评论...