title: Neo4j Cypher: Create a relationship only if the end node exists
body: <p>Building on this <a href="https://stackoverflow.com/q/13244894/6893866">similar question</a>, I want the most performant way to handle this scenario.</p>
  
  <pre><code>MERGE (n1{id:&lt;uuid&gt;})
  SET n1.topicID = &lt;unique_name1&gt;
  IF (EXISTS((a:Topic{id:&lt;unique_name1&gt;})) |  CREATE UNIQUE (n1)-[:HAS]-&gt;(a))
  
  MERGE (n2{id:&lt;uuid&gt;})
  SET n2.topicID = &lt;unique_name2&gt;
  IF (EXISTS((a:Topic{id:&lt;unique_name2&gt;})) |  CREATE UNIQUE (n2)-[:HAS]-&gt;(a))
  </code></pre>
  
  <p>Unfortunately, IF doesn't exist, and EXISTS can't be used to match or find a unique node. </p>
  
  <ul>
  <li>I can't use OPTIONAL MATCH, because then CREATE UNIQUE will throw a null exception (as much as I wish it would ignore null parameters)</li>
  <li>I can't use MATCH, because if the topic doesn't exist, I will will loose all my rows.</li>
  <li>I can't use MERGE, because I don't want to create the node if it doesn't exist yet.</li>
  <li>I can't use APOC, because I have no guarantee that it will be available for use on our Neo4j server.</li>
  </ul>
  
  <p>The best solution I have right now is </p>
  
  <pre><code>MERGE (a:TEST{id:1})
  WITH a
  OPTIONAL MATCH (b:TEST{id:2})
  // collect b so that there are no nulls, and rows aren't lost when no match
  WITH a, collect(b) AS c
  FOREACH(n IN c | CREATE UNIQUE (a)-[:HAS]-&gt;(n))
  RETURN a
  </code></pre>
  
  <p>However, this seems kinda complicated and needs 2 <code>WITH</code>s for what is essentially <code>CREATE UNIQUE RELATION if start and end node exist</code> (and in the plan there is an eager). Is it possible to do any better? (Using Cypher 3.1)</p>