Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find entities with missing attributes in Datomic

If I have the following Datomic database:

{ :fred :age 42 }
{ :fred :likes :pizza }
{ :sally :age 42 }

How do I query for both entities (:fred and :sally), getting back the attribute :likes :pizza for :fred and an empty value for :sally?

The query

[:find ?n ?a ?l
 :where [?n :age ?a]
        [?n :likes ?l]]

only returns :fred 42 :pizza.

like image 265
Ralph Avatar asked Jan 13 '14 21:01

Ralph


1 Answers

Datomic has recently been updated with a few expression functions available to you in Datomic queries. One of these functions is called get-else and it lets you provide a default return value if an attribute doesn't exist on an entity, much like how clojure.core/get will return an option third param if the key isn't found.

So using your own example, you would only need to change it like so:

[:find ?n ?a ?l :where [?n :age ?a] [(get-else $ ?n :likes false) ?l]

Unfortunately you can't actually make nil a "default" value since it's not a valid Datomic data type, and Datomic will carp if you try, but false should get you where you're going as well.

like image 56
Jonathan Doane Avatar answered Sep 19 '22 16:09

Jonathan Doane