Search code examples
clojuredatomic

In Datomic, how do I get a timeline view of the changes made to the values of a particular entity?


I'm following the tutorial, http://www.datomic.com/company/resources/tutorial but I think I am missing a simple piece of the puzzle of how to access Datomic's time model.

If I do a series of adds and retracts

;; DO a series of transactions 
;; (transact conn [:db/add entity-id attribute value0])

(use 'datomic.api)
(dir datomic.api)
(def conn (connect "datomic:dev://localhost:4334/demo"))

(transact conn '[:db/add 2000 :db/doc "Hello There"])
(q '[:find ?e ?n :where [?e :db/doc ?n] [(= 2000 ?e)]] (db conn))
; => <HashSet [[2000 "Hello There"]]>

(transact conn '[:db/add 2000 :db/doc "Hello There 1"])
(q '[:find ?e ?n :where [?e :db/doc ?n] [(= 2000 ?e)]] (db conn))
; => <HashSet [[2000 "Hello There 1"]]>

(transact conn '[:db/add 2000 :db/doc "Hello There 2"])
(q '[:find ?e ?n :where [?e :db/doc ?n] [(= 2000 ?e)]] (db conn))
; => <HashSet [[2000 "Hello There 2"]]>

(transact conn '[:db/add 2000 :db/doc "Hello There 3"])
(q '[:find ?e ?n :where [?e :db/doc ?n] [(= 2000 ?e)]] (db conn))
; => <HashSet [[2000 "Hello There 3"]]>

How is it possible to get a series of changes of the value on (entity 2000 attribute :db/doc)?

I want to get something in the format of

[ [Transaction Number, Time, Value] .... [Transaction Number, Time, Value]]

For example:

[ [T1, "2012-March-16-9:30:12", "Hello There"] 
  .... 
  .... 
  .... 
  [T27, "2012-June-14-9:54:38", "Hello There 3"] ]

It can't be that difficult, but there are a lot of :db internal parameters that I'm not familiar with.


Solution

  • Take a look at the (history db) function in the reference.

    Returns a special database containing all assertions and retractions across time. This special database can be used for datoms and index-range calls and queries, but not for entity or with calls. as-of and since bounds are also supported. Note that queries will get all of the additions and retractions, which can be distinguished by the fifth datom field :added (true for add/assert) [e a v tx added]

    Using history you can do something like this to get the data you wanted:

    datomic-test.core> (q '[:find ?tx ?tx-time ?v 
                            :in $ ?e ?a 
                            :where [?e ?a ?v ?tx _] 
                                   [?tx :db/txInstant ?tx-time]] 
                          (d/history (db conn)) 
                          2000 
                          :db/doc)
    #<HashSet [[13194139534315 #inst "2012-09-09T00:45:49.086-00:00" "Hello There"] [...]]>
    

    Also look at (tempid :db.part/user) to get IDs instead of using hard coded numbers like 2000.