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.
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)
)
-
The method returns a tuple that can be unpacked to access the query result, summary, and keys.
-
The method expects a Cypher statement as a string as the first argument.
-
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:
-
A list of
Record
objects -
A summary of the query execution
-
A list of keys specified in the
RETURN
clause
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.
# 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.
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
.
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.
from neo4j import Result, RoutingControl
driver.execute_query(
cypher, result_transformer_=Result.to_df,
routing_=RoutingControl.READ # or simply "r"
)
r
for read mode and w
for write mode.Check your understanding
Summary
In this lesson, you learned how to execute one-off Cypher statements using the execute_query()
method and access the results.