Sum and query problem with identical property values

Hi team,
Thanks for all the good work, really enjoy logseq!

I have maybe a naive question, but I am using the following query:

{:title “TOTAL TIME SPENT
:query [ :find (sum ?tt)
:in $ ?pattern
:where
[?q :block/page ?p]
[?p :page/journal? true]
[?q :block/content ?c]
[(clojure.string/includes? ?c ?pattern)]
[?q :block/properties ?prop]
[(get ?prop :time-spent) ?tt]
]
:inputs [“new task test”]
}

So that for each [[new task test]] with property time-spent, I add up the values, ex:
[[new task test]]
time-spent:: 60

It seems like if I have twice the same value, it doesn’t add up, like :
[[new task test]]
time-spent:: 60
[[new task test]]
time-spent:: 60

the result of the query will be 60, whereas if one of the 2 is 61, the result will be correct (121)

What did I do wrong?

Another question, how do you divide the result of a query? (here by 60?)

Thanks in advance!

I looked up the working of Sum in Datomic and found this: Datomic Queries and Rules | Datomic

Which has the exact same example as you list.

“Unless otherwise specified, Datomic’s datalog returns sets, and you will not see duplicate values. This is often undesirable when producing aggregates.”

“The solution to this problem is the :with clause, which considers additional variables when forming the basis set for the query result. The :with variables are then removed, leaving a bag (not a set!) of values available for aggregation.”

In your query add :with ?q between the lines :query and :in.
Basically use the block’s unique id as an extra consideration.

As for dividing:

Add :view (fn [result] (for [r result] (/ r 60) )) between :inputs and }.

Hi @Siferiax, thanks a lot for your answers! It works !

I have the feeling that the entry cost in this datomic queries is high. I also tried to use format in the function, to get soemthing better than 1.16666666666667, but I failed.
I tried this
:view (fn [result] (for [r result] (format "%.2f" (/ r 60))) )

And it gives me 70 again (which was the result before dividing by 60, instead of 1.17)

Do you have any clue about this?

Again many thanks

It seems that the format function is not supported in the :view clause. It doesn’t give an error, it just skips the clause as a whole, thus giving you the query result as is.
So it seems the view I posted is the best possible. But I’m no expert on the clojure function use in advanced queries tbh.

Actually you can use what is in the view in result-transform as well. (It failed for me initially because I was a dumdum and missed a ) lol)
:result-transform (fn [result] (for [r result] (/ r 60) ))
It doesn’t give you a solution, but it’s an alternative. It also doesn’t allow the use of format unfortunately.

Cool, thanks a lot for the quick answer @Siferiax !