🔍 Code Extractor

function get_node_by_uid

Maturity: 53

Retrieves a node from a Neo4j graph database by its unique identifier (UID) and returns it as a dictionary.

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
502 - 536
Complexity:
simple

Purpose

This function queries a Neo4j database to find and retrieve a single node matching the provided UID. It's used for looking up specific nodes in the graph database, handling connection management automatically, and providing error handling with logging. Returns None if the node is not found or if an error occurs during retrieval.

Source Code

def get_node_by_uid(uid: str) -> Optional[Dict[str, Any]]:
    """
    Get a node by its UID.
    
    Args:
        uid: UID of node to retrieve
        
    Returns:
        Node as dictionary or None if not found
    """
    #logger.info(f"Retrieving node with UID: {uid}")
    try:
        driver = get_driver()
        with driver.session() as session:
            # Modified query to look for both uppercase and lowercase UIDs
            result = session.run(
                """
                MATCH (n)
                WHERE n.UID = $uid
                RETURN n
                """,
                uid=uid
            )
            
            record = result.single()
            if record:
                node = record["n"]
                return dict(node.items())
            else:
                logger.debug(f"No node found with UID: {uid}")
                return None
                
    except Exception as e:
        logger.error(f"Error retrieving node: {e}")
        return None

Parameters

Name Type Default Kind
uid str - positional_or_keyword

Parameter Details

uid: A string representing the unique identifier (UID) of the node to retrieve from the Neo4j database. This should match the 'UID' property of a node in the graph. The function performs a case-sensitive match on this value.

Return Value

Type: Optional[Dict[str, Any]]

Returns Optional[Dict[str, Any]]. If a node with the matching UID is found, returns a dictionary containing all properties of the node as key-value pairs. Returns None if no node is found with the given UID or if an error occurs during the database query. The dictionary keys are property names and values are the corresponding property values from the Neo4j node.

Dependencies

  • neo4j
  • logging
  • typing

Required Imports

from typing import Dict, Any, Optional
import logging
from neo4j import Driver
from CDocs.db import get_driver

Usage Example

from CDocs.db import get_driver
from typing import Dict, Any, Optional
import logging

# Ensure logger is configured
logger = logging.getLogger(__name__)

# Example usage
uid_to_find = "abc123-def456-ghi789"
node = get_node_by_uid(uid_to_find)

if node:
    print(f"Found node: {node}")
    print(f"Node properties: {node.keys()}")
    # Access specific properties
    if 'name' in node:
        print(f"Node name: {node['name']}")
else:
    print(f"No node found with UID: {uid_to_find}")

Best Practices

  • Always check if the returned value is None before accessing node properties to avoid AttributeError
  • Ensure the Neo4j driver is properly configured and the database is accessible before calling this function
  • The function automatically manages database sessions and closes them after use
  • UIDs are case-sensitive; ensure the provided UID matches the exact case stored in the database
  • This function returns only the first matching node if multiple nodes have the same UID (though UIDs should be unique)
  • Error logging is handled internally, but callers should still handle None returns appropriately
  • The function uses a parameterized query to prevent Cypher injection attacks

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_dbo_usergroup_by_uid 70.8% similar

    Retrieves a single dbo_UserGroup node from a Neo4j graph database by matching its unique identifier (UID).

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
  • function get_dbo_product_by_uid 68.6% similar

    Retrieves a single dbo_Product node from a Neo4j graph database by matching its unique identifier (UID).

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
  • function get_reference_municipalities_by_uid 67.9% similar

    Retrieves a single Reference_Municipalities node from a Neo4j graph database by matching its unique identifier (UID).

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
  • function get_user_by_id 67.8% similar

    Retrieves user data from a Neo4j graph database by user ID, including associated roles and formatted name fields.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function get_parameter_medicationtypeproperties_by_uid 67.5% similar

    Retrieves a Parameter_MedicationTypeProperties node from a Neo4j graph database using its unique identifier (UID).

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