如何提取从Datomic中另一个实体链接的所有实体?

时间:2019-01-31 09:38:07

标签: datomic

我不知道如何表达我的问题。

:host/id有指向:server/id的链接。我想拉链接到特定主机的所有服务器。

我尝试了几种方法,但是得到的结果都是空白,所有结果或IllegalArgumentExceptionInfo :db.error/not-a-keyword Cannot interpret as a keyword

我尝试遵循文档,但我一直迷路。到目前为止,这是我的尝试:

所有主机

(d/q '[:find (pull ?server [{:host/id [:host/hostname]}])
   :in $ ?hostname
   :where 
   [?host :host/hostname ?hostname]
   [?server :server/name]] db "myhost")

IllegalArgumentExceptionInfo

(d/q '[:find (pull ?server [{:host/id [:host/hostname]}])
   :in $ ?hostname
   :where 
   [?server :server/name ?host]
   [?host :host/hostname ?hostname]] db "myhost") 

[]

(d/q '[:find (pull ?host [{:host/id [:host/hostname]}])
   :in $ ?hostname
   :where 
   [?host :host/hostname ?hostname]
   [?host :server/name]] db "myhost")

1 个答案:

答案 0 :(得分:2)

假设您有这些实体处于原子状态:

(d/transact conn [{:host/name "host1"}])

(d/transact conn [{:server/name "db1"
                   :server/host [:host/name "host1"]}
                  {:server/name "web1"
                   :server/host [:host/name "host1"]}])

并假设每个服务器都有对主机的引用(请参见下面的架构),为了查询将哪些服务器链接到主机,请使用反向关系语法“ _”:


(d/q '[:find (pull ?h [* {:server/_host [:server/name]}])
       :in $ ?hostname
       :where
       [?h :host/name ?hostname]]
     (d/db conn)
     "host1")

会给您:

[[{:db/id 17592186045418,
   :host/name "host1",
   :server/_host [#:server{:name "db1"} #:server{:name "web1"}]}]]

以下是示例架构供您参考:

(def uri "datomic:free://localhost:4334/svr")
(d/delete-database uri)
(d/create-database uri)
(def conn (d/connect uri))

(d/transact conn [{:db/ident       :server/name
                   :db/cardinality :db.cardinality/one
                   :db/unique      :db.unique/identity
                   :db/valueType   :db.type/string}
                  {:db/ident       :server/host
                   :db/cardinality :db.cardinality/one
                   :db/valueType   :db.type/ref}
                  {:db/ident       :host/name
                   :db/cardinality :db.cardinality/one
                   :db/unique      :db.unique/identity
                   :db/valueType   :db.type/string}])