You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从ES API迁移至Spring Data Elasticsearch,如何实现Upsert?

使用Spring Data Elasticsearch的UpdateQuery实现Upsert

你可以通过UpdateQuery.builder()构建查询,完全对应原ES API的逻辑,代码实现如下:

// 将JSON字符串解析为Spring Data ES的Document对象,替代原API的source设置
Document updateDoc = Document.parse(jsonForUpdate);
Document upsertDoc = Document.parse(jsonForIndex);

// 构建UpdateQuery,映射原UpdateRequest的所有配置
UpdateQuery updateQuery = UpdateQuery.builder(id)
        .withDocument(updateDoc) // 对应原updateRequest.doc()
        .withUpsert(upsertDoc)   // 对应原updateRequest.upsert(indexRequest)
        .withFetchSource(true)   // 对应原updateRequest.fetchSource(true)
        .build();

// 执行更新操作,假设你已注入ElasticsearchOperations实例
elasticsearchOperations.update(updateQuery, IndexCoordinates.of(indexName));

关键映射说明

  • Document.parse():替代原API中IndexRequest.source()和UpdateRequest.doc()的JSON内容设置,将JSON字符串转为Spring Data ES标准的文档对象。
  • withUpsert():直接传入文档内容,当指定ID的文档不存在时自动插入该内容,和原代码的upsert逻辑完全一致。
  • withFetchSource(true):开启返回更新后的源数据,与原API的fetchSource(true)效果相同。

该写法适用于Spring Data Elasticsearch 4.x及以上版本,旧版本可调整UpdateQuery的构造方式,但核心upsert逻辑保持一致。

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:50:24