Given a simple exists query like

RETURN exists( (:NodeA {propA:{0}})-[:REL_B]->(:NodeB) )

how could I make the node label NodeA be queried dynamically? For example

RETURN exists( (:{1} {propA:{0}})-[:REL_B]->(:NodeB) )

but this doesn't work. I know that you can use {1} in labels(n) but how would I use it as WHERE clause in the EXISTS pattern?

2 Answers

1
cybersam On Best Solutions

This pure-Cypher query should work, but it is not performant since it will scan all nodes to find the appropriate x node(s) and cannot take advantage of indexing:

MATCH (x{propA: $0})
WHERE $1 IN LABELS(x)
RETURN EXISTS((x)-[:REL_B]->(:NodeB));

A more performant way to do it would be to use the APOC procedure apoc.cypher.run to execute a Cypher query with the desired label hardcoded:

CALL apoc.cypher.run(
  "RETURN EXISTS((:`" + $1 + "` {propA: $p})-[:REL_B]->(:NodeB)) AS res",
  {p: $0}) YIELD value
RETURN value.res;

This way, you can also take advantage of indexing.

2
âńōŋŷXmoůŜ On

No, you cannot use parameters in node labels. See https://neo4j.com/docs/cypher-manual/current/syntax/parameters/ for details.

Parameters cannot be used for the following :

  • property keys; so, MATCH (n) WHERE n.$param = 'something' is invalid
  • relationship types like :REL_B
  • labels like :NodeA