Fork me on GitHub
#datascript
<
2020-08-24
>
oly10:08:57

I want todo a count on the number of prices in a database, this works fine using (count ?prices) except when there are none then I get no data returned from the query how can i handle this so 0 is returned ?

cjsauer13:08:15

Not sure how to achieve that within the query itself, but you could wrap the query in an or expression: (or (my-query db) 0)

oly15:08:37

I think the issue with that is the query returns multiple fields, I always want the other fields only the aggregate to be 0 and not remove the other data

oly15:08:55

unless you mean i can use the or in the middle of the where conditions ?

cjsauer17:08:56

Ah I think I misunderstood your original question. Could you post an example of the query?

oly08:08:17

(d/q '[:find ?e ?i ?n ?slug  (count ?eid2)
                :keys eid id product/name product/slug ?prices
                :in $ ?product-id
                :where
                [?e :product/id ?i]
                [?eid2 :price/product ?prices]
                [?e :product/name ?n]
                [?e :product/slug ?slug]] @conn product-id)

oly08:08:02

That's what i currently have, I can split it out in this situation but Its something that would be good to know how to achieve

pithyless08:08:24

Is that ?eid2 supposed to fetch all prices in the DB? It doesn't seem to be related to any other clause in the query. If so, I'd just do a separate query for it (queries are cheap, don't need to join them into one big one). Otherwise, if you want to fetch something that may or may not exist (but want to ensure it's absence does not remove it from the result set), you want to pull that info, not query it. A pull would work like a maybe, but a where clause works like a must.

pithyless08:08:44

You can also consider, if this kind of aggregate should not be done as a separate query (or even just using the indexes directly, if it's a simple relationship).

pithyless08:08:36

And just a friendly reminder: whenever working with aggregates, don't forget to ask yourself if you need :with to make sure the results are accurate. (If you're aggregating on eids, this won't be an issue).