🔍 Code Extractor

function create_node

Maturity: 46

Creates a node in a Neo4j graph database with a specified label and properties, automatically generating a unique ID and timestamp if not provided.

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
41 - 96
Complexity:
moderate

Purpose

This function is designed to create nodes in a Neo4j graph database as part of a larger graph data management system. It handles property sanitization, ensures unique identifiers (UID) are present and properly formatted, adds creation timestamps, and executes the Cypher query to persist the node. It's part of the CDocs database layer for managing graph-based document or entity relationships.

Source Code

def create_node(label, properties):
    """Create a node with given label and properties."""
    # Sanitize properties first
    properties = _sanitize_properties(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 Neo4j node label (e.g., 'Person', 'Document', 'Entity'). This categorizes the node type in the graph database and should follow Neo4j naming conventions (typically CamelCase).

properties: A dictionary containing key-value pairs of properties to assign to the node. Keys should be strings representing property names, and values can be any JSON-serializable type. The function will automatically add 'UID' (if missing) and 'created' timestamp. Properties are sanitized before use via the _sanitize_properties helper function.

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's properties as a dict. If the query doesn't return the node object but succeeds, it returns the input properties dictionary (with added UID and timestamp). Raises an exception if node creation fails.

Dependencies

  • logging
  • uuid
  • typing
  • datetime
  • neo4j
  • CDocs.db
  • CDocs.db.schema_manager
  • traceback

Required Imports

import logging
import uuid
from datetime import datetime
from neo4j import Driver, Session, Transaction, Record
from neo4j.exceptions import ServiceUnavailable, ClientError
from CDocs.db import get_driver
from CDocs.db.schema_manager import NodeLabels, RelTypes, migrate_audit_events
import traceback

Usage Example

# Assuming Neo4j is configured and connected
# Create a person node
properties = {
    'name': 'John Doe',
    'email': 'john@example.com',
    'age': 30
}

try:
    node = create_node('Person', properties)
    print(f"Created node with UID: {node['UID']}")
    print(f"Created at: {node['created']}")
except Exception as e:
    print(f"Failed to create node: {e}")

# Create a document node with custom UID
doc_properties = {
    'uid': 'doc-12345',  # Will be converted to uppercase 'UID'
    'title': 'Important Document',
    'content': 'Document content here'
}

doc_node = create_node('Document', doc_properties)
print(f"Document UID: {doc_node['UID']}")

Best Practices

  • Always wrap calls to create_node in try-except blocks to handle potential database connection or query execution errors
  • Ensure the Neo4j database connection is properly initialized before calling this function
  • The 'label' parameter should follow Neo4j naming conventions (CamelCase, no spaces)
  • Properties dictionary should only contain JSON-serializable values
  • The function automatically handles UID generation and normalization - avoid manually setting 'UID' unless you have a specific identifier scheme
  • Be aware that the function depends on _sanitize_properties and run_query helper functions being available in the same module
  • Consider validating the label against NodeLabels schema if using the schema_manager for consistency
  • The function logs errors but re-raises exceptions, so implement appropriate error handling at the call site

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_node_with_uid 81.4% 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 create_node_and_ensure_relationships 70.2% similar

    Creates a new node in a Neo4j graph database and establishes multiple relationships to existing nodes within a single atomic transaction.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function batch_create_nodes 69.5% similar

    Creates multiple Neo4j graph database nodes in batches for improved performance, automatically generating UIDs and timestamps for each node.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_node_with_relationship 69.3% similar

    Creates a new node in a Neo4j graph database and optionally establishes a relationship with an existing node in a single atomic operation.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_dbo_houses 68.4% similar

    Creates a new node with label 'dbo_Houses' in a Neo4j graph database with the specified properties and returns the created node.

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
← Back to Browse