function run_query_v1
Executes a Cypher query against a Neo4j database session and returns the result, with optional parameterization for safe query execution.
/tf/active/vicechatdev/offline_docstore_multi_vice.py
54 - 72
simple
Purpose
This function serves as a wrapper for executing Cypher queries in Neo4j graph databases. It handles parameterized queries to prevent injection attacks and provides a consistent interface for database operations. The function is designed to work with Neo4j sessions and supports both simple queries and complex parameterized queries for CRUD operations on graph data.
Source Code
def run_query(session,query, params=None):
"""
Execute a Cypher query and return the result
Parameters
----------
query : str
The Cypher query to execute
params : dict, optional
Parameters for the query
Returns
-------
result
The query result
"""
if params is None:
params = {}
return session.run(query, params)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session |
- | - | positional_or_keyword |
query |
- | - | positional_or_keyword |
params |
- | None | positional_or_keyword |
Parameter Details
session: A Neo4j database session object obtained from GraphDatabase.driver().session(). This is the active connection to the Neo4j database through which the query will be executed. Must be a valid, open session.
query: A string containing the Cypher query to execute. This should be valid Cypher syntax (Neo4j's query language). Can include parameter placeholders using $param_name syntax for parameterized queries.
params: An 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 not provided. This enables safe parameterized queries and prevents Cypher injection attacks.
Return Value
Returns a Neo4j Result object (neo4j.Result) which is an iterable containing the query results. The result can be consumed using methods like .data() to get a list of dictionaries, .single() to get one record, or iterated directly. The exact structure depends on the RETURN clause in the Cypher query. The result object is a cursor that can only be consumed once.
Dependencies
neo4j
Required Imports
from neo4j import GraphDatabase
Usage Example
from neo4j import GraphDatabase
# Setup connection
driver = GraphDatabase.driver('bolt://localhost:7687', auth=('neo4j', 'password'))
session = driver.session()
# Simple query without parameters
result = run_query(session, 'MATCH (n:Person) RETURN n.name LIMIT 5')
for record in result:
print(record['n.name'])
# Parameterized query
query = 'MATCH (n:Person {name: $name}) RETURN n'
params = {'name': 'John Doe'}
result = run_query(session, query, params)
data = result.data()
print(data)
# Create node with parameters
create_query = 'CREATE (p:Person {name: $name, age: $age}) RETURN p'
create_params = {'name': 'Jane Smith', 'age': 30}
result = run_query(session, create_query, create_params)
# Cleanup
session.close()
driver.close()
Best Practices
- Always use parameterized queries (params argument) instead of string concatenation to prevent Cypher injection attacks
- Ensure the session is properly opened before calling this function and closed after use
- Remember that Neo4j Result objects can only be consumed once - store results in a list if you need to iterate multiple times
- Use session.close() and driver.close() in a try-finally block or context manager to ensure proper cleanup
- Consider using transactions (session.begin_transaction()) for multiple related queries to ensure atomicity
- Handle potential exceptions like ServiceUnavailable and AuthError that may be raised by the Neo4j driver
- For large result sets, consider using pagination in your Cypher query (SKIP/LIMIT) to avoid memory issues
- The function does not commit transactions automatically - use appropriate transaction management based on your use case
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function run_query 83.1% similar
-
function evaluate_query 79.5% similar
-
function run_query_v2 75.6% similar
-
function complex_query_example 50.4% similar
-
function search_documents 49.5% similar