我正在使用 Datomic,并希望根据我的查询从任意数量的时间点中提取整个实体。如果我在执行查询之前知道这些实例,Datomic 文档有一些关于如何从两个不同数据库实例执行查询的不错示例。但是,我希望我的查询确定我需要的“as-of”类型数据库实例的数量,然后在拉取实体时使用这些实例。这是我到目前为止所拥有的:
(defn pull-entities-at-change-points [entity-id]
(->>
(d/q
'[:find ?tx (pull ?dbs ?client [*])
:in $ [?dbs ...] ?client
:where
[?client ?attr-id ?value ?tx true]
[(datomic.api/ident $ ?attr-id) ?attr]
[(contains? #{:client/attr1 :client/attr2 :client/attr3} ?attr)]
[(datomic.api/tx->t ?tx) ?t]
[?tx :db/txInstant ?inst]]
(d/history (d/db db/conn))
(map #(d/as-of (d/db db/conn) %) [1009 1018])
entity-id)
(sort-by first)))
我正在尝试查找所有事务,其中某些属性在
:client
上。实体发生变化,然后拉动实体,因为它在这些时间点存在。线路:(map #(d/as-of (d/db db/conn) %) [1009 1018])
是我尝试在我知道客户端属性已更改的两个特定事务中创建一系列数据库实例。理想情况下,我想在一个查询中完成所有这些,但我不确定这是否可能。希望这是有道理的,但如果您需要更多详细信息,请告诉我。
最佳答案
我会将拉取调用拆分为单独的 API 调用,而不是在查询中使用它们。我会将查询本身限制为获取感兴趣的交易。解决此问题的一个示例解决方案是:
(defn pull-entities-at-change-points
[db eid]
(let
[hdb (d/history db)
txs (d/q '[:find [?tx ...]
:in $ [?attr ...] ?eid
:where
[?eid ?attr _ ?tx true]]
hdb
[:person/firstName :person/friends]
eid)
as-of-dbs (map #(d/as-of db %) txs)
pull-w-t (fn [as-of-db]
[(d/as-of-t as-of-db)
(d/pull as-of-db '[*] eid)])]
(map pull-w-t as-of-dbs)))
这个针对我用玩具模式构建的数据库的函数将返回如下结果:
([1010
{:db/id 17592186045418
:person/firstName "Gerry"
:person/friends [{:db/id 17592186045419} {:db/id 17592186045420}]}]
[1001
{:db/id 17592186045418
:person/firstName "Jerry"
:person/friends [{:db/id 17592186045419} {:db/id 17592186045420}]}])
我将评论几点:
contains
和 leverages query caching . 关于clojure - Datomic:如何在查询中查询任意数量的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33181396/