Clojure 在Datomic中查找具有特定属性的最早和最新实体的日期?
假设a有这样一个Datomic模式:Clojure 在Datomic中查找具有特定属性的最早和最新实体的日期?,clojure,datomic,Clojure,Datomic,假设a有这样一个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/in
{: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/createdAt
即时/日期(:app/type
),比如“type1”。这样的查询在Datomic中会是什么样子?一个简单的方法是使用数据日志查询:
[:find (min ?c) (max ?c) :in $ ?type :where
[?e :app/type ?type]
[?e :app/createdAt ?c]]
性能注意事项
从Datomic 0.9.5385开始,数据日志引擎将对与[?e:app/type?type]
子句匹配的实体执行完整扫描;如果有许多这样的实体,这可能会导致许多到存储的网络往返、对端的高资源消耗以及显著的延迟
幸运的是,您可以使用Datomic限制查询扫描的DATOM数量。例如,要计算最大创建日期,如果您知道至少有一个这样的实体是在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的源代码,我只是从个人实验中推断上述断言。您知道这样一个查询的性能吗?如果你有几千个这样的实体呢?主要关注“max”的性能?