Search code examples
neo4jcypherneo4j-apoccypher-3.1

MATCH for nodes with variable label name NEO4J


By queries in neo4j I get name of label as variable so in the same query I want to find all nodes with this label. I know that I can't have variable for label name like this

MATCH (n:${variable}) RETURN n

and nor

MATCH (n:variable) RETURN n

I am looking for work around for my situation I couldn't find apoc function for this situation. I expected a function like this

apoc.match.node(['labelName'])

I know that it's possible to find nodes with label using WHERE

WHERE label IN labels(nodes)

My guess is that this structure will slow down the speed of search so I want to avoid it


Solution

  • It's not possible with pure Cypher but you can consider using APOC's apoc.cypher.run procedure :

    WITH $variable AS label
    CALL apoc.cypher.run("MATCH (:" + label + ") RETURN count(*) AS count", {})
    YIELD value
    RETURN label, value.count AS count;
    

    https://neo4j.com/labs/apoc/4.1/overview/apoc.cypher/apoc.cypher.run/#usage-apoc.cypher.run