function run_query_v2
Executes a Cypher query against a Neo4j graph database and returns the results as a list of dictionaries.
/tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
15 - 18
simple
Purpose
This function provides a convenient wrapper for executing Neo4j Cypher queries. It manages the database session lifecycle, executes parameterized queries to prevent injection attacks, and transforms the Neo4j result records into Python dictionaries for easier data manipulation. It's designed for synchronous query execution in applications that need to interact with Neo4j graph databases.
Source Code
def run_query(query, params=None):
with driver.session() as session:
result = session.run(query, params or {})
return [dict(record) for record in result]
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
query |
- | - | positional_or_keyword |
params |
- | None | positional_or_keyword |
Parameter Details
query: A string containing the Cypher query to execute against the Neo4j database. This should be a valid Cypher statement (e.g., 'MATCH (n:Person) RETURN n.name'). Can include parameter placeholders using the $parameter_name syntax.
params: Optional dictionary containing parameters to be passed to the Cypher query. Keys should match the parameter names used in the query (without the $ prefix). Defaults to an empty dictionary if None is provided. This enables parameterized queries for security and performance.
Return Value
Returns a list of dictionaries, where each dictionary represents one record from the query result. Each dictionary's keys correspond to the column names in the RETURN clause of the Cypher query, and values are the corresponding data from the database. Returns an empty list if the query produces no results.
Dependencies
neo4j
Required Imports
from neo4j import GraphDatabase
Usage Example
from neo4j import GraphDatabase
# Initialize the driver (required setup)
driver = GraphDatabase.driver(
'bolt://localhost:7687',
auth=('neo4j', 'password')
)
# Example 1: Simple query without parameters
results = run_query('MATCH (n:Person) RETURN n.name AS name, n.age AS age')
for record in results:
print(f"Name: {record['name']}, Age: {record['age']}")
# Example 2: Parameterized query
query = 'MATCH (n:Person {name: $name}) RETURN n.name AS name, n.age AS age'
params = {'name': 'Alice'}
results = run_query(query, params)
print(results)
# Don't forget to close the driver when done
driver.close()
Best Practices
- Always use parameterized queries (the params argument) instead of string concatenation to prevent Cypher injection attacks
- Ensure the 'driver' variable is properly initialized with GraphDatabase.driver() before calling this function
- Close the driver connection using driver.close() when your application terminates to free resources
- Handle potential exceptions such as neo4j.exceptions.ServiceUnavailable for connection issues or neo4j.exceptions.CypherSyntaxError for invalid queries
- For large result sets, consider using session.run() with pagination or streaming to avoid memory issues
- The function creates a new session for each query; for multiple queries, consider refactoring to reuse sessions for better performance
- Be aware that this function loads all results into memory; for very large datasets, consider using iterators or cursors instead
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function run_query 79.7% similar
-
function run_query_v1 75.6% similar
-
function evaluate_query 63.1% similar
-
function generate_cypher_examples 57.4% similar
-
function generate_python_snippets 53.6% similar