Skip to content
Nikita Prokopov edited this page Jul 14, 2015 · 23 revisions

Querying a schema

Unlike Datomic, in DataScript schema is just a map kept separate from database datoms. It means you cannot query it as you would in Datomic, but you can query it just as any other collection. Use [[?attr [[?aprop ?avalue] ...]] ...] destructuring form to convert nested maps into a flat collection of facts.

For example, following query will return all datoms from a DB which attribute has cardinality many:

(def schema
  { :entry/id           {:db/unique :db.unique/identity}
    :entry/child        {:db/cardinality :db.cardinality/many
                         :db/valueType   :db.type/ref}
    :entry/first-child  {:db/valueType   :db.type/ref} })
    
(def db (-> (ds/empty-db schema)
            (ds/db-with [{:db/id 1,
                          :entry/id "a",
                          :entry/child #{2 3},
                          :entry/first-child 2}])))

(d/q '[:find ?entity ?attr ?value
       :in $ [[?attr [[?aprop ?avalue] ...]] ...]
       :where [(= ?avalue :db.cardinality/many)]
              [?entity ?attr ?value]]
      db (:schema db))

=> #{[1 :entry/child 3] [1 :entry/child 2]}

Clone this wiki locally