🔍 Code Extractor

function evaluate_query

Maturity: 48

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

File:
/tf/active/vicechatdev/offline_docstore_multi_vice.py
Lines:
74 - 96
Complexity:
simple

Purpose

This function is designed to execute Cypher queries that are expected to return a single scalar value or record. It's commonly used for queries that return counts, single property values, or existence checks in Neo4j graph databases. The function handles parameterized queries for security and returns None if no results are found.

Source Code

def evaluate_query(session,query, params=None):
    """
    Execute a Cypher query and return a single result
    
    Parameters
    ----------
    query : str
        The Cypher query to execute
    params : dict, optional
        Parameters for the query
        
    Returns
    -------
    object
        The single result value
    """
    if params is None:
        params = {}
    result = session.run(query, params)
    record = result.single()
    if record:
        return record[0]
    return None

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.

query: A string containing the Cypher query to execute. This should be a valid Cypher query syntax that returns a single result. Can include parameter placeholders (e.g., $param_name) for parameterized queries.

params: An optional dictionary containing parameters to be passed to the Cypher query. Keys should match parameter names in the query (without the $ prefix). Defaults to an empty dictionary if not provided. This enables safe parameterized queries to prevent injection attacks.

Return Value

Returns the first value (index 0) from the single result record if a record exists. The return type is 'object' and can be any Neo4j data type (integer, string, node, relationship, list, etc.) depending on what the query returns. Returns None if the query produces no results or if the result set is empty.

Dependencies

  • neo4j

Required Imports

from neo4j import GraphDatabase

Usage Example

from neo4j import GraphDatabase

# Setup Neo4j connection
driver = GraphDatabase.driver('bolt://localhost:7687', auth=('neo4j', 'password'))

# Create a session
with driver.session() as session:
    # Example 1: Count nodes
    count = evaluate_query(session, 'MATCH (n) RETURN count(n)')
    print(f'Total nodes: {count}')
    
    # Example 2: Get a specific property with parameters
    query = 'MATCH (p:Person {name: $name}) RETURN p.age'
    params = {'name': 'John Doe'}
    age = evaluate_query(session, query, params)
    print(f'Age: {age}')
    
    # Example 3: Check existence
    exists_query = 'MATCH (p:Person {email: $email}) RETURN count(p) > 0'
    exists = evaluate_query(session, exists_query, {'email': 'john@example.com'})
    print(f'Person exists: {exists}')

driver.close()

Best Practices

  • Always use parameterized queries (params argument) instead of string concatenation to prevent Cypher injection attacks
  • This function is designed for queries that return a single value; use different methods for queries returning multiple records
  • Always wrap session usage in a context manager (with statement) or ensure proper session closure to avoid connection leaks
  • Handle the None return value appropriately in your code, as it indicates no results were found
  • Ensure the query returns at least one column; accessing record[0] will fail if the query returns no columns
  • Consider adding error handling around this function to catch Neo4j exceptions (ServiceUnavailable, AuthError, etc.)
  • For queries that might return multiple records, only the first record is used; ensure your query uses LIMIT 1 if needed

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function run_query 79.5% similar

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

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
  • function search_documents 48.7% 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
  • function generate_cypher_examples 40.0% similar

    Generates a comprehensive Cypher query examples file for interacting with a Neo4j graph database based on the provided schema information.

    From: /tf/active/vicechatdev/neo4j_schema_report.py
  • function parse_query_string 39.6% similar

    Extracts a specific query parameter value from a URL string, with compatibility for both Python 2 and Python 3.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/compat.py
  • function generate_neo4j_schema_report 37.1% similar

    Generates a comprehensive schema report of a Neo4j graph database, including node labels, relationships, properties, constraints, indexes, and sample data, outputting multiple report formats (JSON, HTML, Python snippets, Cypher examples).

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