Search code examples
datomicdatalog

Datomic query for maximum of aggregated value


Assume I have entity author with many related book entities. What's the query to fetch author with biggest amount of books?


Solution

  • OK. Since I found an answer by myself - I am posting it here in case somebody will search for:

    The solution is to build two datomic queries passing output of first one to second one.

    (->>
      (d/q '[:find (count ?b) ?a :where [?a :author/books ?b]] db)
      (d/q '[:find (max ?count) ?a :in $ [?count ?a]] db))
    

    This is as far as I got it the common way to work with less trivial queries in datomic - split it to several subqueries and chain together giving the DB do its job.