Fork me on GitHub
#datomic
<
2023-12-18
>
danbunea15:12:13

Hi, maybe someone can give me a hint. Need to load a list of conversations and the text and the time of the last message in that conversation:

(d/q '[:find  ?c (max ?message-time)
               :in $
               :where               
               [?m :message/parent-id ?c]
               [?m :message/sent-at ?message-time]
               ]
             db)
This works, but I cannot load also the :message/text for that last message.

favila15:12:28

aggregate over time + m

favila15:12:59

(d/q '[:find  ?c (max ?message-time+m+text)
               :in $
               :where               
               [?m :message/parent-id ?c]
               [?m :message/sent-at ?message-time]
               [?m :message/text ?text]
               [(tuple ?message-time ?m ?text) ?message-time+m+text]
             db)

favila15:12:32

Consider getting the text in a second query, it might be faster if there is IO or memory pressure to get that text

favila15:12:39

that looks like this:

favila15:12:02

(d/q '[:find  ?c (max ?message-time+m)
               :in $
               :where               
               [?m :message/parent-id ?c]
               [?m :message/sent-at ?message-time]
               [(tuple ?message-time ?m) ?message-time+m]
             db)

danbunea15:12:07

This is very nice, thank you

favila15:12:39

(d/q '[:find ?c ?m ?message-time ?message-text)
               :in $ [[?c ?message-time+m]] ; result of previous query
               :where               
               [(untuple ?message-time+m) [?message-time ?m]]
               [?m :message/text ?text]]
             db)

favila15:12:15

You could even do the first query as a subquery of the second

favila15:12:42

(d/q '[:find ?c ?sent-at ?text
       :where
       [(q '[:find ?c (max ?sent-at+m)
             :where
             [?m :message/parent-id ?c]
             [?m :message/sent-at ?sent-at]
             [(tuple ?sent-at ?m) ?sent-at+m]
            $) [[?c ?sent-at+m]]]
       [(untuple ?sent-at+m) [?sent-at ?m]]
       [?m :message/text ?text]]
     db)

😍 2
💪 2
danbunea16:12:03

I learn about using tuples and subqueries from this thread 🙂

☝️ 1
1