function create_node
Creates a node in a Neo4j graph database with a specified label and properties, automatically generating a UID and timestamp if not provided.
/tf/active/vicechatdev/CDocs single class/db/db_operations.py
21 - 73
moderate
Purpose
This function is designed to create nodes in a Neo4j graph database with automatic handling of unique identifiers and timestamps. It ensures data consistency by normalizing UID property names to uppercase, generates UUIDs when not provided, adds creation timestamps, and executes a Cypher CREATE query. The function is part of a larger graph database management system (CDocs) and integrates with schema management and database driver utilities.
Source Code
def create_node(label, properties):
"""Create a node with given label and properties."""
# Ensure UID is set and uppercase
if 'uid' in properties and 'UID' not in properties:
properties['UID'] = properties.pop('uid')
elif 'UID' not in properties:
properties['UID'] = str(uuid.uuid4())
# Continue with node creation...
"""
Create a node with the given label and properties.
Parameters
----------
label : str
The node label
properties : dict
Properties for the node
Returns
-------
dict
The created node properties
"""
try:
# Generate a unique ID if not provided
# Add creation timestamp if not provided
if 'created' not in properties:
properties['created'] = datetime.now().isoformat()
# Build property string for Cypher
property_str = ", ".join([f"n.{key} = ${key}" for key in properties.keys()])
# Build the query
query = f"""
CREATE (n:{label})
SET {property_str}
RETURN n
"""
# Execute the query
result = run_query(query, properties)
# Return created node properties
if result and 'n' in result[0]:
return dict(result[0]['n'])
return properties
except Exception as e:
logger.error(f"Error creating node: {str(e)}")
raise e
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
label |
- | - | positional_or_keyword |
properties |
- | - | positional_or_keyword |
Parameter Details
label: A string representing the node label/type in Neo4j (e.g., 'Person', 'Document', 'Event'). This determines the category or class of the node being created in the graph database.
properties: A dictionary containing key-value pairs of properties to assign to the node. Can include 'uid' or 'UID' for unique identification, 'created' for timestamp, and any other custom properties. The function will modify this dict by normalizing 'uid' to 'UID' and adding missing 'UID' and 'created' fields.
Return Value
Returns a dictionary containing the properties of the created node. If the node creation is successful and the query returns the node, it extracts and returns the node properties from the result. If the query doesn't return the expected result, it returns the properties dictionary that was used for creation. In case of an error, an exception is raised after logging.
Dependencies
logginguuidtypingdatetimeneo4jtraceback
Required Imports
import logging
import uuid
from datetime import datetime
from neo4j import Driver, Session, Transaction, Record
from neo4j.exceptions import ServiceUnavailable, ClientError
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.db import get_driver
Condition: Required for database connection management - the run_query function likely depends on this
Required (conditional)from CDocs.db.schema_manager import NodeLabels, RelTypes, migrate_audit_events
Condition: Required for schema management and validation in the broader CDocs system
Required (conditional)Usage Example
# Assuming CDocs database utilities are properly configured
# and run_query function is available
# Example 1: Create a node with minimal properties
node_props = create_node(
label='Person',
properties={'name': 'John Doe', 'email': 'john@example.com'}
)
print(f"Created node with UID: {node_props['UID']}")
# Example 2: Create a node with custom UID
node_props = create_node(
label='Document',
properties={
'uid': 'custom-id-123',
'title': 'Important Document',
'status': 'draft'
}
)
print(f"Created document: {node_props}")
# Example 3: Create a node with all properties specified
node_props = create_node(
label='Event',
properties={
'UID': 'event-001',
'created': '2024-01-15T10:30:00',
'name': 'Conference',
'location': 'New York'
}
)
print(f"Created event: {node_props}")
Best Practices
- Always handle the returned dictionary to verify node creation was successful
- The function modifies the input 'properties' dictionary by normalizing 'uid' to 'UID' and adding default values - be aware of side effects
- Ensure the 'label' parameter follows Neo4j naming conventions (typically PascalCase)
- The function depends on a module-level 'logger' and 'run_query' function - ensure these are properly initialized
- Wrap calls in try-except blocks to handle potential database connection errors or Cypher query failures
- Be cautious with property names that might conflict with Neo4j reserved keywords
- The function automatically generates UUIDs and timestamps - avoid passing these unless you need specific values
- Ensure the Neo4j database connection is established before calling this function
- Consider validating the 'label' against NodeLabels schema if using the CDocs schema manager
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_node_v1 96.6% similar
-
function create_node_with_uid 84.9% similar
-
function batch_create_nodes 71.0% similar
-
function create_node_and_ensure_relationships 68.3% similar
-
function create_node_with_relationship_v1 68.1% similar