How do you update a single value in xtdb?

Viewed 350

Given the following document

{:xt/id 1
 :line-item/quantity 23
 :line-item/item 20
 :line-item/description "Item line description"}

I want to update the quantity to 25

As I can tell so far, I will need to first query the DB, get the full doc, merge in the change, then transact the new doc back.

Is there a way to merge in just a change in quantity without doing the above?

Thank you

1 Answers

You should be able to use transaction functions for this. These will allow you to specify those multiple steps and push them down into the transaction log to ensure that they execute in-sequence (i.e. that you will always retrieve the latest doc to update against at the point in time the transaction function call itself is pushed into the transaction log).

For your specific example I think it would look something like this (untested):

(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)]]))}]])

This creates the transaction function itself, then you just need to call it to make the change:

;; `[[::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]])
Related