假设有一个像这样的 Datomic 模式:
{:db/id #db/id[:db.part/db]
:db/ident :app/createdAt
:db/doc "The date and time when the entity was created (not necessarily the same as tx time)"
:db/valueType :db.type/instant
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id #db/id[:db.part/db]
:db/ident :app/type
:db/doc "The type of the entity"
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
并且在应用程序的生命周期中会创建多个此类实体。我有兴趣查找某种类型 (:app/type
) 的最旧和最新实体的 :app/createdAt
即时/日期,例如“type1”。这样的查询在 Datomic 中会是什么样子?
最佳答案
一个简单的方法是使用数据记录查询:
[:find (min ?c) (max ?c) :in $ ?type :where
[?e :app/type ?type]
[?e :app/createdAt ?c]]
性能考虑因素
从 Datomic 0.9.5385 开始,Datalog 引擎将对与 [?e :app/type ?type]
子句匹配的实体执行完整扫描;如果有很多这样的实体,这可能会导致到存储的网络往返次数较多、对等点的资源消耗较高以及显着的延迟。
幸运的是,您可以使用 Datomic 的 Optimization of Range Predicates限制查询扫描的数据原子数量。例如,要计算最长创建日期,如果您知道至少有一个此类实体是在 2016 年 8 月之后创建的,则可以调用:
(d/q '[:find (max ?c) . :in $ ?type ?lower-bound :where
[?e :app/createdAt ?c]
[(>= ?c ?lower-bound)]
[?e :app/type ?type]]
db #inst "2016-08")
请注意,Datalog 子句的顺序很重要。
免责声明:我对 Datomic 的源代码并不了解,仅根据个人实验推断上述断言。
关于clojure - 在 Datomic 中查找具有特定属性的最旧和最新实体的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39180765/