🔍 Code Extractor

function update_node

Maturity: 60

Updates properties of a Neo4j graph database node identified by its unique UID, automatically adding a modification timestamp.

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
414 - 452
Complexity:
moderate

Purpose

This function provides a safe way to update node properties in a Neo4j database. It accepts a UID to identify the target node and a dictionary of properties to update. The function automatically adds a 'modifiedDate' timestamp to track when the update occurred. It uses the Cypher query language with the SET += operator to merge new properties with existing ones without removing unspecified properties. The function includes error handling and logging, returning the updated node as a dictionary on success or None on failure.

Source Code

def update_node(uid: str, properties: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Update properties of a node identified by UID.
    
    Args:
        uid: UID of node to update
        properties: Properties to update
        
    Returns:
        Updated node as dictionary or None if update failed
    """
    try:
        # Add modification timestamp
        properties['modifiedDate'] = datetime.now()
        
        driver = get_driver()
        with driver.session() as session:
            result = session.run(
                """
                MATCH (n {UID: $uid})
                SET n += $props
                RETURN n
                """,
                uid=uid,
                props=properties
            )
            
            record = result.single()
            if record:
                node = record["n"]
                logger.debug(f"Updated node with UID: {uid}")
                return dict(node.items())
            else:
                logger.warning(f"No node found with UID: {uid}")
                return None
                
    except Exception as e:
        logger.error(f"Error updating node: {e}")
        return None

Parameters

Name Type Default Kind
uid str - positional_or_keyword
properties Dict[str, Any] - positional_or_keyword

Parameter Details

uid: String identifier that uniquely identifies the node to update in the Neo4j database. This should be a valid UID that exists in the database. The function will search for a node with a 'UID' property matching this value.

properties: Dictionary containing key-value pairs of properties to update on the node. Keys should be valid Neo4j property names (strings), and values can be any type supported by Neo4j (strings, numbers, booleans, dates, lists, etc.). The 'modifiedDate' property will be automatically added/overwritten by the function, so it doesn't need to be included in this dictionary.

Return Value

Type: Optional[Dict[str, Any]]

Returns an Optional[Dict[str, Any]]. On success, returns a dictionary containing all properties of the updated node (including both the newly updated properties and any existing properties that weren't modified). Returns None if the node with the specified UID is not found or if an error occurs during the update operation. The returned dictionary keys are property names and values are the property values from the Neo4j node.

Dependencies

  • neo4j
  • logging
  • datetime
  • typing

Required Imports

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

Usage Example

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

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

# Example 1: Update a node's properties
uid = "node-12345-abcde"
properties_to_update = {
    "name": "Updated Node Name",
    "status": "active",
    "version": 2
}

updated_node = update_node(uid, properties_to_update)

if updated_node:
    print(f"Node updated successfully: {updated_node}")
    print(f"Modified date: {updated_node.get('modifiedDate')}")
else:
    print("Failed to update node or node not found")

# Example 2: Update with complex properties
complex_properties = {
    "tags": ["important", "reviewed"],
    "metadata": {"author": "John Doe"},
    "score": 95.5
}

result = update_node("another-uid-123", complex_properties)
if result:
    print(f"Updated node UID: {result.get('UID')}")

Best Practices

  • Always check if the returned value is None before accessing properties to avoid AttributeError
  • The function automatically adds 'modifiedDate' timestamp, so don't include it in the properties dictionary
  • The SET += operator merges properties, so existing properties not in the update dictionary will be preserved
  • Ensure the UID exists in the database before calling this function, or handle None return value appropriately
  • Be aware that the function modifies the input properties dictionary by adding 'modifiedDate'
  • Use appropriate error handling around this function call as it returns None on any exception
  • Consider validating property values before passing them to ensure they are Neo4j-compatible types
  • The function uses a database session context manager, so connections are properly closed even on errors
  • Monitor logs for warnings about missing nodes and errors during updates for debugging purposes

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function push_changes 79.3% similar

    Updates a node's properties in a Neo4j graph database by matching on UID and setting new property values.

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
  • function create_node_with_uid 69.7% 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 get_node_by_uid 63.3% 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 update_user 61.0% similar

    Updates an existing user's information in a Neo4j database, including profile fields, password, and role assignments.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function get_parameter_medicationtypeproperties_by_uid 61.0% 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