在 Datomic 的关系中查找出现次数最多的实体

Find entity with most occurrences in a relation in Datomic

有没有一种方法可以纯粹在查询中表达这种逻辑?

(def e-top
  (let [res (d/q '[:find ?e (count ?p)
                   :where [?p :likes ?e]] db)]
    (first (apply max-key last res))))

如果您需要在一个查询中工作,那么最好使用子查询(在查询中嵌套调用查询)来解决聚合问题的聚合。看到这个 answer on the Datomic mailing list which includes a similar (not identical) query on the results of an aggregate against mbrainz:

(d/q '[:find ?track ?count
       :where [(datomic.api/q '[:find ?track (count ?artist)
               :where [?track :track/artists ?artist]] $) [[?track ?count]]]
       [(> ?count 1)]]
  (d/db conn))

对于您的情况(假设工作留在 Clojure 中),申请会更快更简单。如果您使用 REST API 或其他一些您没有 perf 的 Datomic 客户端,则只需要做一些简单的事情(例如获取与最大值相关联的东西)的子查询往往更有意义与对等图书馆相关的好处正在处理中。