【发布时间】:2021-09-22 21:22:51
【问题描述】:
给定以下文件
{:xt/id 1
:line-item/quantity 23
:line-item/item 20
:line-item/description "Item line description"}
我想将数量更新为25
据我所知,我需要先查询数据库,获取完整文档,合并更改,然后再处理新文档。
有没有办法在不做上述操作的情况下只合并数量的变化?
谢谢
【问题讨论】:
给定以下文件
{:xt/id 1
:line-item/quantity 23
:line-item/item 20
:line-item/description "Item line description"}
我想将数量更新为25
据我所知,我需要先查询数据库,获取完整文档,合并更改,然后再处理新文档。
有没有办法在不做上述操作的情况下只合并数量的变化?
谢谢
【问题讨论】:
您应该可以为此使用transaction functions。这些将允许您指定这些多个步骤并将它们推送到事务日志中,以确保它们按顺序执行(即,您将始终在事务函数调用本身被推送的时间点检索要更新的最新文档进入事务日志)。
对于您的具体示例,我认为它看起来像这样(未经测试):
(xt/submit-tx node [[::xt/put
{:xt/id :update-quantity
;; note that the function body is quoted.
;; and function calls are fully qualified
:xt/fn '(fn [ctx eid new-quantity]
(let [db (xtdb.api/db ctx)
entity (xtdb.api/entity db eid)]
[[::xt/put (assoc entity :line-item/quantity new-quantity)]]))}]])
这会自己创建事务函数,然后你只需要调用它来进行更改:
;; `[[::xt/fn <id-of-fn> <id-of-entity> <new-quantity>]]` -- the `ctx` is automatically-injected
(xt/submit-tx node [[::xt/fn :update-quantity 1 25]])
【讨论】: