Executing Cypher statements

Introduction

You can use the execute_query() method to run one-off Cypher statements or statements that return a small number of records. This method fetches a list of records and loads them into memory.

python
cypher = """
MATCH (p:Person {name: $name})-[r:ACTED_IN]->(m:Movie)
RETURN m.title AS title, r.role AS role
"""
name="Tom Hanks"

records, summary, keys = driver.execute_query( # (1)
    cypher,    # (2)
    name=name  # (3)
)
  1. The method returns a tuple that can be unpacked to access the query result, summary, and keys.

  2. The method expects a Cypher statement as a string as the first argument.

  3. Any named parameters not suffixed with an underscore can be accessed in the query by prefixing the name with a dollar sign.

Using Parameters

It is good practice to use parameters in your queries to avoid malicious code being injected into your Cypher statement.

Handling the Result

The execute_query() method returns an a tuple containing three objects:

  1. A list of Record objects

  2. A summary of the query execution

  3. A list of keys specified in the RETURN clause

python
print(keys) # ['title', 'role']
print(summary) # A summary of the query execution

Accessing results

Each row returned by the query is a Record object. The Record object is a dictionary-like object that provides access to the data returned by the query.

You can access any item in the RETURN clause using square brackets.

python
# RETURN m.title AS title, r.role AS role

for record in records:
    print(record["title"]) # Toy Story
    print(record["role"]) # "Woody"

Transforming results

The execute_query() method accepts a result_transformer_ argument that allows you to transform the result into an alternative format.

Rather than returning the tuple, the query will return the output of the result_transformer_ function.

python
result = driver.execute_query(
    cypher,
    name=name,
    result_transformer_= lambda result: [
        f"Tom Hanks played {record['role']} in {record['title']}"
        for record in result
    ]
)

print(result) # [Tom Hanks played Woody in Toy Story, ...]

Working with DataFrames

The Result class provides a to_df() method that can be used to transform the result into a pandas DataFrame.

python
from neo4j import Result

driver.execute_query(
  cypher,
  result_transformer_=Result.to_df
)

Reading and writing

By default, execute_query() runs in WRITE mode. In a clustered environment, this sends all queries to the cluster leader, putting unnecessary load on the leader.

When you’re only reading data, you can optimize performance by setting the routing_ parameter to READ mode. This distributes your read queries across all cluster members.

python
from neo4j import Result, RoutingControl

driver.execute_query(
  cypher, result_transformer_=Result.to_df,
  routing_=RoutingControl.READ # or simply "r"
)

You can also pass r for read mode and w for write mode.

Summary

In this lesson, you learned how to execute one-off Cypher statements using the execute_query() method and access the results.