ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

第四阶段 30 · index / document 单文档写入

2026/8/3 16:57:07 拓冰建站 浏览量
第四阶段 30 · index / document 单文档写入 30 · index / document 单文档写入阶段第四阶段 / 写入与索引管理ESindex/create/update/delete 单文档 | PostgreSQLINSERT/UPDATE/DELETE1. 概念ES 的单文档写入 APIAPI语义SQL 对照index有则覆盖、无则新建upsert 整篇INSERT ... ON CONFLICT DO UPDATE整行替换create仅当不存在时创建存在则报错INSERT主键冲突报错update局部更新指定字段或脚本更新UPDATE ... SET col ?delete按_id删除DELETE ... WHERE id ?文档由_index_id唯一定位_id相当于主键。2. PostgreSQL 对照INSERTINTOsalesdata(id,invoice_number,net_amount)VALUES(1,INV-001,100)ONCONFLICT(id)DOUPDATESETnet_amountEXCLUDED.net_amount;UPDATEsalesdataSETnet_amount200WHEREid1;DELETEFROMsalesdataWHEREid1;3. ES DSL# index整篇 upsert指定 _id PUT salesdata_idx/_doc/1 { invoice_number: INV-001, net_amount: 100 } # create仅新建 PUT salesdata_idx/_create/1 { invoice_number: INV-001, net_amount: 100 } # update局部更新 POST salesdata_idx/_update/1 { doc: { net_amount: 200 } } # delete DELETE salesdata_idx/_doc/14. Spring Boot 实现ComponentpublicclassDoc30SingleDoc{AutowiredprivateElasticsearchClientelasticsearchClient;/** index整篇 upsert */publicvoidindexDoc(StringindexName,Stringid,MapString,Objectdoc)throwsIOException{elasticsearchClient.index(i-i.index(indexName).id(id).document(doc));}/** update局部更新指定字段 */publicvoidupdateFields(StringindexName,Stringid,MapString,Objectpartial)throwsIOException{elasticsearchClient.update(u-u.index(indexName).id(id).doc(partial),// 只更新给出的字段Map.class);}/** delete */publicvoiddeleteDoc(StringindexName,Stringid)throwsIOException{elasticsearchClient.delete(d-d.index(indexName).id(id));}}5. 坑与最佳实践不指定_idindex会自动生成随机 id通常业务上要显式指定方便幂等。index是整篇替换漏传的字段会丢失只改部分字段用update。写入近实时NRT默认 1s 后可搜到refresh_interval不是立即可见。别逐条写大批量批量场景用bulk第 31 篇单条写吞吐低。版本冲突并发更新可用if_seq_no/if_primary_term做乐观锁。