function create_node_with_uid
Creates a new node in a Neo4j graph database with a specified UID, label, and properties, automatically adding a creation timestamp if not provided.
/tf/active/vicechatdev/CDocs/db/db_operations.py
883 - 930
moderate
Purpose
This function provides a controlled way to create Neo4j graph database nodes with predetermined UIDs rather than auto-generated ones. It's useful for data migration, synchronization scenarios, or when you need to maintain consistent identifiers across systems. The function ensures the UID is set, adds a creation timestamp if missing, and provides comprehensive error handling and logging.
Source Code
def create_node_with_uid(label: str, properties: Dict[str, Any], uid: str) -> bool:
"""
Create a node with a specific UID.
Args:
label: Node label
properties: Node properties
uid: UID to use for the node
Returns:
Boolean indicating success
"""
try:
# Make a copy to avoid modifying the original
props = dict(properties)
# Ensure UID is set
props['UID'] = uid
# Add creation timestamp if not provided
if 'createdDate' not in props:
props['createdDate'] = datetime.now()
driver = get_driver()
with driver.session() as session:
result = session.run(
f"""
CREATE (n:{label} $props)
RETURN n
""",
props=props
)
record = result.single()
success = record is not None
if success:
logger.debug(f"Created new node with UID: {uid}")
else:
logger.warning(f"Failed to create node with UID: {uid}")
return success
except Exception as e:
logger.error(f"Error creating node with UID: {e}")
import traceback
logger.error(traceback.format_exc())
return False
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
label |
str | - | positional_or_keyword |
properties |
Dict[str, Any] | - | positional_or_keyword |
uid |
str | - | positional_or_keyword |
Parameter Details
label: The Neo4j node label (type) to assign to the created node. This is a string that categorizes the node (e.g., 'User', 'Document', 'Event'). Must be a valid Neo4j label name without special characters.
properties: A dictionary containing key-value pairs of properties to assign to the node. Can include any valid Neo4j property types (strings, numbers, booleans, dates). The original dictionary is not modified as the function creates a copy.
uid: A unique identifier string to assign to the node's UID property. This should be a unique value across all nodes of this type. Typically a UUID string or other unique identifier from an external system.
Return Value
Type: bool
Returns a boolean value: True if the node was successfully created in the database (verified by checking if a record was returned from the query), False if creation failed due to any error or if no record was returned. Errors are logged but not raised.
Dependencies
neo4jloggingdatetimetypingtraceback
Required Imports
from typing import Dict, Any
from datetime import datetime
from CDocs.db import get_driver
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
import traceback
Condition: only used in exception handling for detailed error logging
Required (conditional)Usage Example
from typing import Dict, Any
from datetime import datetime
from CDocs.db import get_driver
import logging
import uuid
# Setup logger (assumed to be configured in module)
logger = logging.getLogger(__name__)
# Example 1: Create a user node with custom UID
user_properties = {
'name': 'John Doe',
'email': 'john@example.com',
'role': 'admin'
}
user_uid = str(uuid.uuid4())
success = create_node_with_uid('User', user_properties, user_uid)
if success:
print(f"User created with UID: {user_uid}")
# Example 2: Create a document node with existing timestamp
doc_properties = {
'title': 'Project Plan',
'content': 'Project details...',
'createdDate': datetime(2024, 1, 15)
}
doc_uid = 'doc-12345'
success = create_node_with_uid('Document', doc_properties, doc_uid)
# Example 3: Create node with minimal properties (timestamp auto-added)
minimal_props = {'status': 'active'}
node_uid = 'node-' + str(uuid.uuid4())
success = create_node_with_uid('Entity', minimal_props, node_uid)
Best Practices
- Always ensure the UID provided is truly unique to avoid conflicts or unexpected behavior
- The function creates a copy of the properties dictionary, so the original is safe from modification
- Check the return value to verify successful creation before proceeding with dependent operations
- The function automatically adds a 'createdDate' timestamp if not provided, using datetime.now()
- Error details are logged but exceptions are caught and converted to False returns, so check logs for debugging
- Ensure the Neo4j driver is properly initialized via get_driver() before calling this function
- The label parameter is directly interpolated into the Cypher query, so ensure it comes from trusted sources to avoid injection
- Consider using this function within a transaction context if you need to create multiple related nodes atomically
- The function uses session.run() which auto-commits; wrap in explicit transactions if rollback capability is needed
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_node 81.4% similar
-
function update_node 69.7% similar
-
function create_node_with_relationship 67.9% similar
-
function node_exists 67.6% similar
-
function create_node_and_ensure_relationships 67.4% similar