title: Nested unions in Cypher/Neo4j
body: <p>I've this metagraph in Neo4j:</p>
  
  <pre><code>:Protein ---&gt; :is_a ---------------&gt; :Enzyme ---&gt; :activated_by|inhibited_by ---&gt; :Compound
           \&lt;-- :activated_by &lt;---/ 
  
  :Compound --&gt; :consumed_by|:produced_by ---&gt; :Transport
            \&lt;---- :catalyzed_by -------&lt;---/
  
  :Transport --&gt; part_of ---&gt; :Pathway
  </code></pre>
  
  <p>(yes, it's biology, yes, it's imported from BioPAX).</p>
  
  <p>I want to use Cypher to return all pairs of <code>(:Protein, :Compounds)</code> that are linked by some graph path. While one simple way would be to follow each possible path between the two node types and issue one query per each of them, clearly a query using some pattern union would be more compact (maybe slower, I'm assessing the performance of different approaches). </p>
  
  <p>But how to write such a query? I've read that Cypher has a UNION construct, but I haven't clear how to combine and nest them, e.g., regarding the subgraphs from enzymes to transports, I would like to be able to write something equivalent to this informal expression: </p>
  
  <pre><code>enz:Enzyme :activated|inhibited_by comp:Compund 
  join with: (
    (comp :consumed_by|produced_by :Transport)
    UNION (:Transport :catalyzed_by comp )
  )
  </code></pre>
  
  <p>I've read <a href="https://neo4j.com/blog/cypher-union-query-using-collect-clause/" rel="nofollow noreferrer">there should be some way</a>, but I didn't get much of it and I'm trying to understand if there is a relatively easy way (in SPARQL or SQL the above is rather simple).</p>