🔍 Code Extractor

function delete_node

Maturity: 62

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

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
454 - 500
Complexity:
moderate

Purpose

This function provides a safe way to remove nodes from a Neo4j database. It supports two deletion modes: (1) cascade mode that removes the node along with all its relationships, and (2) safe mode that only deletes the node if it has no relationships. This prevents orphaning related data unless explicitly requested. The function is useful for data cleanup, entity removal, and maintaining graph database integrity.

Source Code

def delete_node(uid: str, cascade: bool = False) -> bool:
    """
    Delete a node identified by UID.
    
    Args:
        uid: UID of node to delete
        cascade: If True, also delete connected nodes
        
    Returns:
        Boolean indicating whether the node was deleted successfully
    """
    try:
        driver = get_driver()
        with driver.session() as session:
            if cascade:
                # Delete the node and all relationships
                result = session.run(
                    """
                    MATCH (n {UID: $uid})
                    DETACH DELETE n
                    RETURN count(n) as deleted
                    """,
                    uid=uid
                )
            else:
                # Only delete if no relationships exist
                result = session.run(
                    """
                    MATCH (n {UID: $uid})
                    WHERE NOT (n)--()
                    DELETE n
                    RETURN count(n) as deleted
                    """,
                    uid=uid
                )
                
            record = result.single()
            if record and record["deleted"] > 0:
                logger.debug(f"Deleted node with UID: {uid}")
                return True
            else:
                logger.warning(f"No node deleted with UID: {uid}")
                return False
                
    except Exception as e:
        logger.error(f"Error deleting node: {e}")
        return False

Parameters

Name Type Default Kind
uid str - positional_or_keyword
cascade bool False positional_or_keyword

Parameter Details

uid: String representing the unique identifier of the node to delete. This should match the UID property stored on the node in the Neo4j database. Must be a valid string value that exists in the database.

cascade: Boolean flag that controls deletion behavior. When True, deletes the node and all its relationships (DETACH DELETE). When False (default), only deletes the node if it has no relationships, preventing accidental data orphaning. Defaults to False for safety.

Return Value

Type: bool

Returns a boolean value indicating the success of the deletion operation. Returns True if the node was successfully deleted (deleted count > 0), False if no node was found with the given UID or if the deletion failed due to existing relationships (when cascade=False). Also returns False if any exception occurs during the operation.

Dependencies

  • neo4j
  • logging
  • CDocs.db
  • CDocs.db.schema_manager

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 in module scope)
logger = logging.getLogger(__name__)

# Delete a node without cascade (safe mode - only if no relationships)
node_uid = "abc-123-def-456"
success = delete_node(node_uid)
if success:
    print(f"Node {node_uid} deleted successfully")
else:
    print(f"Failed to delete node {node_uid} - may have relationships")

# Delete a node with cascade (removes all relationships)
success_cascade = delete_node(node_uid, cascade=True)
if success_cascade:
    print(f"Node {node_uid} and all relationships deleted")
else:
    print(f"Failed to delete node {node_uid}")

Best Practices

  • Always use cascade=False (default) unless you are certain you want to delete all connected relationships
  • Check the return value to verify successful deletion before proceeding with dependent operations
  • Consider querying for relationships before deletion to understand the impact
  • Use within a try-except block if you need custom error handling beyond the built-in exception catching
  • Ensure the UID exists before calling this function to avoid unnecessary database queries
  • Be aware that cascade deletion is irreversible and will remove all relationships connected to the node
  • Monitor logs (debug, warning, error levels) for deletion status and troubleshooting
  • Consider implementing a soft-delete pattern for critical data instead of hard deletion
  • Ensure proper database connection pooling and session management via get_driver()
  • Test cascade deletion in a non-production environment first to understand the scope of deletion

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function delete_notification 75.8% similar

    Deletes a notification node from a Neo4j graph database by its unique identifier (UID).

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function node_exists 69.0% similar

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

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_node_with_uid 67.2% 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 delete_all_notifications 66.8% similar

    Deletes all notifications or only read notifications for a specific user from a Neo4j graph database.

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function get_node_by_uid 64.7% 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
← Back to Browse