🔍 Code Extractor

function node_exists

Maturity: 54

Checks if a node with a specific UID exists in a Neo4j graph database by querying for the node and returning a boolean result.

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
932 - 962
Complexity:
simple

Purpose

This function provides a simple existence check for nodes in a Neo4j database based on their UID property. It's useful for validation before performing operations like updates or deletions, preventing duplicate node creation, or verifying node existence in workflows. The function handles database connection management and error cases gracefully, returning False if any errors occur during the check.

Source Code

def node_exists(uid: str) -> bool:
    """
    Check if a node with the given UID exists in the database.
    
    Args:
        uid: UID of node to check
        
    Returns:
        Boolean indicating whether the node exists
    """
    try:
        driver = get_driver()
        with driver.session() as session:
            result = session.run(
                """
                MATCH (n)
                WHERE n.UID = $uid
                RETURN count(n) > 0 as exists
                """,
                uid=uid
            )
            
            record = result.single()
            if record:
                return record["exists"]
            else:
                return False
                
    except Exception as e:
        logger.error(f"Error checking if node exists: {e}")
        return False

Parameters

Name Type Default Kind
uid str - positional_or_keyword

Parameter Details

uid: A string representing the unique identifier (UID) of the node to check. This should match the UID property stored on nodes in the Neo4j database. Expected to be a non-empty string, typically a UUID or other unique identifier format.

Return Value

Type: bool

Returns a boolean value: True if a node with the specified UID exists in the database, False if no such node exists or if an error occurs during the database query. The function is designed to be safe and will return False rather than raising exceptions.

Dependencies

  • neo4j
  • logging

Required Imports

from CDocs.db import get_driver
import logging

Usage Example

from CDocs.db import get_driver
import logging

# Setup logger (assumed to be configured in module)
logger = logging.getLogger(__name__)

# Check if a node exists
uid_to_check = "123e4567-e89b-12d3-a456-426614174000"
exists = node_exists(uid_to_check)

if exists:
    print(f"Node with UID {uid_to_check} exists")
else:
    print(f"Node with UID {uid_to_check} does not exist")

# Use in conditional logic
if not node_exists("some-uid"):
    # Create the node
    pass
else:
    # Update existing node
    pass

Best Practices

  • Always handle the boolean return value appropriately - False can indicate either non-existence or an error condition
  • Ensure the get_driver() function is properly configured before calling this function
  • The function uses a session context manager which automatically handles connection cleanup
  • Error logging is built-in, but consider checking logs if unexpected False results occur
  • The UID parameter should match the exact property name used in your Neo4j schema (case-sensitive)
  • This function performs a database query on every call - consider caching results if checking the same UID multiple times
  • The query matches any node label with the given UID - if you need label-specific checks, modify the Cypher query

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function delete_node 69.0% similar

    Deletes a node from a Neo4j graph database by its unique identifier (UID), with optional cascade deletion of connected nodes and relationships.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_node_with_uid 67.6% similar

    Creates a new node in a Neo4j graph database with a specified UID, label, and properties, automatically adding a creation timestamp if not provided.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function check_document_exists_by_uid 67.2% similar

    Queries a Neo4j database to check if a ControlledDocument with a specific UID exists and returns the document object if found.

    From: /tf/active/vicechatdev/CDocs/FC_sync.py
  • function get_node_by_uid 67.1% similar

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

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function check_node_exists 62.8% similar

    Checks if a node with a specified label and matching properties exists in a Neo4j graph database.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
← Back to Browse