Running Cypher fragments

Cypher can be used as a safe, graph-aware, partially compiled scripting language within APOC.

Procedure Overview

The supported procedures are described in the table below:

Qualified Name Type

apoc.cypher.doIt

apoc.cypher.doIt(fragment, params) yield value - executes writing fragment with the given parameters

Procedure

apoc.cypher.run

apoc.cypher.run(fragment, params) yield value - executes reading fragment with the given parameters

Procedure

apoc.cypher.runMany

apoc.cypher.runMany('cypher;\nstatements;',{params},[{statistics:true,timeout:10}]) - runs each semicolon separated statement and returns summary

Procedure

apoc.cypher.runFirstColumnMany

apoc.cypher.runFirstColumnMany(statement, params) - executes statement with given parameters, returns first column only collected into a list, params are available as identifiers

Function

apoc.cypher.runFirstColumnSingle

apoc.cypher.runFirstColumnSingle(statement, params) - executes statement with given parameters, returns first element of the first column only, params are available as identifiers

Function

Example: Fast Node-Counts by Label

It is possible to quickly compute the number of nodes for a specific label using the count function, but only if the query is limited to containing the count function. For example:

MATCH (:Person) RETURN count(*);

It is also possible to combine several computations of nodes related to a specific label using the UNION ALL clause:

Works
MATCH (:Person) RETURN count(*)
UNION ALL
MATCH (:Movie) RETURN count(*);

The same is not possible using the WITH clause:

Doesn’t work
MATCH (:Person)
WITH count(*) as people
MATCH (:Movie) RETURN people, count(*) as movies;

This query will work out the count by iterating over all nodes, which is a very slow operation.

For a much faster process (completed in a few milliseconds), apoc.cypher.run can be used to construct the COUNT() statements and run each of them individually.

CALL db.labels() yield label
CALL apoc.cypher.run("match (:`"+label+"`) return count(*) as count", null) yield value
return label, value.count as count

A similar approach can be used to get the property-keys for each label:

CALL db.labels() yield label
CALL apoc.cypher.run("MATCH (n:`"+label+"`) RETURN keys(n) as keys LIMIT 1",null) yield value
RETURN label, value.keys as keys