function evaluate_query
Executes a Cypher query against a Neo4j database session and returns the first value from a single result record.
/tf/active/vicechatdev/offline_docstore_multi_vice.py
74 - 96
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function run_query_v1 79.5% similar
-
function run_query 71.7% similar
-
function run_query_v2 63.1% similar
-
function search_documents 48.7% similar
-
function get_all_lims_sampletestresultdetails 47.2% similar