Skip to content

Instantly share code, notes, and snippets.

@terjesb
Created March 1, 2018 11:33
Show Gist options
  • Save terjesb/c79d8a84e3eaa1bb7861fea17ee5a744 to your computer and use it in GitHub Desktop.
Save terjesb/c79d8a84e3eaa1bb7861fea17ee5a744 to your computer and use it in GitHub Desktop.
Pull Query
{:paths ["."]
:deps
{com.datomic/datomic-free {:mvn/version "0.9.5656"}}}
;; https://forum.datomic.com/t/datomic-entity-api-on-large-amount-of-entities/352
(ns user
(:require [datomic.api :as d]))
(def uri "datomic:mem://firstdb")
(def schema [
{:db/ident :entry/uuid
:db/valueType :db.type/uuid
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :entry/date
:db/valueType :db.type/instant
:db/cardinality :db.cardinality/one}
{:db/ident :entry/summ
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :entry/dimensions
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many}
{:db/ident :dimension/id
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity}
{:db/ident :dimension/group
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/one}
{:db/ident :group/id
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity}
{:db/ident :group/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
])
(def data [
{:entry/uuid (d/squuid)
:entry/date (java.util.Date.)
:entry/summ "first entry"
:entry/dimensions [{:dimension/id "d1" :dimension/group {:group/id "g1" :group/name "group1"}}
{:dimension/id "d2" :dimension/group {:group/id "g2" :group/name "group2"}}]}
{:entry/uuid (d/squuid)
:entry/date (java.util.Date.)
:entry/summ "second entry"
:entry/dimensions [{:dimension/id "d3" :dimension/group {:group/id "g3" :group/name "group3"}}
{:dimension/id "d4" :dimension/group {:group/id "g4" :group/name "group4"}}]}])
(defn query [db]
(->>
(d/q '[:find [(pull ?e [[:entry/uuid :as :id]
[:entry/date :as :date]
[:entry/summ :as :summ]
{:entry/dimensions [{:dimension/group [:group/name]}]}]) ...]
:where [?e :entry/uuid]]
db)
(map (fn [entry] (-> entry
(dissoc :entry/dimensions)
(assoc :groups (mapv #(-> % :dimension/group :group/name) (:entry/dimensions entry))))))))
(defn setup! [uri]
(d/create-database uri)
(let [conn (d/connect uri)]
(d/transact conn schema)
(d/transact conn data)))
(defn -main []
(setup! uri)
(let [conn (d/connect uri)
db (d/db conn)]
(println (query db))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment