Blocks that reference page, or any of its parents, or any of its children (by name or alias)

I am using the page property parent:: to generate hierarchies and use this to view them.

I would like to an advanced query that fetches all blocks that reference (ideally by name or alias) a page or any of its parents or any of its children. To make it concrete, suppose I have the following pages:

  • PageP1
  • PageP2
  • ThisPage with parent:: [[PageP1]], [[PageP2]]
  • PageC1 with parent:: [[ThisPage]]
  • PageC2 with parent:: [[ThisPage]]

I would like to do an advanced query that gets all blocks that reference any of the following (ideally by name or alias): ThisPage, PageP1, PageP2, PageC1, PageC2.

This is related to this.

A lot asked in this one. Here is an untested query:

#+BEGIN_QUERY
{:query [:find (pull ?b [*])
 :in $ ?target-name
 :where
   [?target :block/name ?target-name]
   [?target :block/original-name ?target-original-name]
   (or-join [?b ?p]
     [?b :block/refs ?p]
     (and
       [?b :block/refs ?a]
       [?p :block/alias ?a]
     )
   )
   (or-join [?target ?target-original-name ?p]
     [(= ?p ?target)]
     (and
       [?p :block/properties ?child-props]
       [(get ?child-props :parent) ?child-parents]
       [(contains? ?child-parents ?target-original-name)]
     )
     (and
       [?p :block/original-name ?parent-original-name]
       [?target :block/properties ?target-props]
       [(get ?target-props :parent) ?target-parents]
       [(contains? ?target-parents ?parent-original-name)]
     )
   )
 ]
 :inputs [:current-page]
 }
#+END_QUERY
2 Likes

It works! Thank you. I am beginning to understand these queries better.