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(statement STRING, params MAP<STRING, ANY>) - runs a dynamically constructed statement with the given parameters. This procedure allows for both read and write statements.

Procedure

apoc.cypher.run
apoc.cypher.run(statement STRING, params MAP<STRING, ANY>) - runs a dynamically constructed read-only statement with the given parameters.

Procedure

apoc.cypher.runMany
apoc.cypher.runMany(statement STRING, params MAP<STRING, ANY>, config MAP<STRING, ANY>) - runs each semicolon separated statement and returns a summary of the statement outcomes.

Procedure

apoc.cypher.runFirstColumnMany
apoc.cypher.runFirstColumnMany(statement STRING, params MAP<STRING, ANY>) - runs the given statement with the given parameters and returns the first column collected into a LIST<ANY>.

Function

apoc.cypher.runFirstColumnSingle
apoc.cypher.runFirstColumnSingle(statement STRING, params MAP<STRING, ANY>) - runs the given statement with the given parameters and returns the first element of the first column.

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