11

I am using datomic with play framework. Play is amazing and datomic is fast. So a good combination overall. Since, I am new to datomic (and datalog i.e. query language datomic uses), I am unable to sort my result ( like we do, order by in sql). For example.

if my query is :

q= [:find ?title 
:where 
[?e :movie/title ?title]
[?e :movie/director "Dave Swag"]
[?e :movie/year ?year]
[(sort ?year)] //here I am trying to sort by year
]

It should return titles of the movies whose director was Dave Swag and result is ordered by year in which image was released. Thankyou :)

Dave Ranjan
  • 2,966
  • 24
  • 55
  • Hey I am stuck in the same place, let me know if you have this figured out ? – Coding active Apr 28 '15 at 06:38
  • 1
    A datalog query finds the set of all of the variables (or tuples of variables) that satisfy the set of clauses. Sort doesn't really have any place _inside_ query - it should be done on the result of the query from outside the query. I.e., return a set of [?title ?year] tuples and sort those by year (into an ordered collection) using Clojure or Java (or Scala in this case). – Ben Kamphaus May 03 '15 at 17:19

1 Answers1

8

If you want to sort your result set, you will need to do this outside of the query, on the returned result set. There is an example of this on a Datomic blog post about querying in listing 20:

(def hist (d/history db))

(->> (d/q '[:find ?tx ?v ?op
            :in $ ?e ?attr
            :where [?e ?attr ?v ?tx ?op]]
        hist
        editor-id
        :user/firstName)
   (sort-by first))

=> ([13194139534319 "Ed" true]
    [13194139534335 "Ed" false]
    [13194139534335 "Edward" true])
Daniel Compton
  • 13,878
  • 4
  • 40
  • 60
  • Just wanted to add the reference to Datomic's own built-in sort aggregator which can be combined to sort multiple fields from result set. – m33lky Mar 03 '17 at 10:41
  • Can you show how to sort by the transaction insertion date? (newest first) Or at least, how do I retrieve the transaction date – Petrus Theron May 30 '17 at 15:25
  • @m33lky could you, please, expand on this? Can't find anything on "sort aggregator". – Igor Kharin Jun 21 '17 at 02:48
  • 1
    Ah, OK. Looks like I misunderstood. Basic sorting could be done with, e.g.: `[:find ?movie (min ?e)]` – Igor Kharin Jun 21 '17 at 03:25
  • 1
    @IgorKharin There is a built-in datomic `sort` aggregate function that you can use instead of `min`. However, if you just want to sort tuples by a column, then using Clojure is perfectly fine (~ Datomic way). – m33lky Jun 21 '17 at 14:25