🔍 Code Extractor

function run_query_v1

Maturity: 50

Executes a Cypher query against a Neo4j database session and returns the result, with optional parameterization for safe query execution.

File:
/tf/active/vicechatdev/offline_docstore_multi_vice.py
Lines:
54 - 72
Complexity:
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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function run_query 83.1% similar

    Executes a custom Cypher query against a Neo4j database and returns the results as a list of dictionaries, handling conversion of Neo4j-specific types.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function evaluate_query 79.5% similar

    Executes a Cypher query against a Neo4j database session and returns the first value from a single result record.

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
  • function run_query_v2 75.6% similar

    Executes a Cypher query against a Neo4j graph database and returns the results as a list of dictionaries.

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
  • function complex_query_example 50.4% similar

    Executes a Neo4j Cypher query to find relationships between LIMS_Parameters nodes where either the source or target node name contains a specified search term.

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
  • function search_documents 49.5% similar

    Searches for documents in a Neo4j graph database based on multiple optional filter criteria including text query, document type, department, status, and owner.

    From: /tf/active/vicechatdev/document_controller_backup.py
← Back to Browse