绘制Datomic事实随时间变化的价值

时间:2014-02-18 11:34:42

标签: charts datomic

由于Datomic存储事实的断言和撤销,是否可以使用此内置存储来绘制随时间变化的值,例如价格历史?

1 个答案:

答案 0 :(得分:3)

是。您想要的命令是datomic.api/history

使用数据库值调用,它返回一个特殊的数据库,其中包含所有数据添加和撤消。

(ns datomic-history-demo.core
  (:require [datomic.api :as d :refer [db q]]))

(defn demonstrate []
  (let [db-uri '"datomic:mem://fnord"]
    (d/delete-database db-uri)
    (d/create-database db-uri)
    (let [conn (d/connect db-uri)]

      (d/transact conn [{:db/id #db/id[:db.part/db]
                         :db/ident :demo/amount
                         :db/valueType :db.type/long
                         :db/cardinality :db.cardinality/one
                         :db/doc "An interesting quantity."
                         :db.install/_attribute :db.part/db}])

      (let [tempid (dbg (d/tempid :db.part/user))
            tx-data @(d/transact conn [{:db/id tempid
                                       :db/doc "initial value"
                                       :demo/amount 5}])
            id (dbg (d/resolve-tempid (:db-after tx-data) (:tempids tx-data) tempid))]

        @(d/transact conn [{:db/id id
                            :db/doc "subsequent value"
                            :demo/amount 17}])

        @(d/transact conn [{:db/id id
                            :db/doc "final value"
                            :demo/amount 23}])

        (let [special-history-db (d/history (db conn))]
          (->>  (q '[:find ?instant ?e ?amount ?operation
                     :where
                     [?e :demo/amount ?amount ?tx ?operation]
                     [?tx :db/txInstant ?instant]]
                   special-history-db)
                (sort-by first)))))))

(demonstrate)

(comment
  ;; evaluates to
  ([#inst "2014-02-25T19:12:24.054-00:00" 17592186045418 5 true]
   [#inst "2014-02-25T19:12:24.058-00:00" 17592186045418 5 false]
   [#inst "2014-02-25T19:12:24.058-00:00" 17592186045418 17 true]
   [#inst "2014-02-25T19:12:24.062-00:00" 17592186045418 23 true]
   [#inst "2014-02-25T19:12:24.062-00:00" 17592186045418 17 false])