How to make attribute dynamic in XTDB query?

I am trying to write an XTDB query… My use case requires me to fetch list of all ids for a given entity.

Following code doesn’t work…

(defn exec-query
  [env {:adapter/keys [type id]} entity-id]
  (let [node (get-in env [type id :node])
        db (xt/db node)
        result (xt/q db
                     '{:find [(pull ?entity [*])]
                       :in [eid]
                       :where [[?entity eid _]]}
                     entity-id)]
    (tap> result)
    []))

when I hardcode the attribute place it works. and I get list of all ids for datasource entity.

(defn exec-query
  [env {:adapter/keys [type id]} entity-id]
  (let [node (get-in env [type id :node])
        db (xt/db node)
        result (xt/q db
                     '{:find [(pull ?entity [*])]
                       
                       :where [[?entity :datasource/id _]]}
                     )]
    (tap> result)
    []))

I have multiple entities like this, I was hoping how can use entity-id variable to do this task.
On reading the documentation Datalog Queries · XTDB Docs
I realized this is not allowed. Is there any way I can generate this query and use it.

1 Like

Answering my question based on the slack conversion - Slack

That’s right, attributes in the triple clauses can’t be “dynamic” like that, as the query planner needs to know which attributes are being used. However you can certainly dynamically generate new queries, by manipulating the edn symbolically, e.g.

(defn exec-query
  [env {:adapter/keys [type id]} entity-id]
  (let [node (get-in env [type id :node])
        db (xt/db node)
        result (xt/q db
                     {:find '[(pull ?entity [*])]
                      :where [['?entity entity-id '_]]})]
    (tap> result)
    []))
2 Likes