🔍 Code Extractor

function push_changes

Maturity: 48

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

File:
/tf/active/vicechatdev/offline_docstore_multi_vice.py
Lines:
98 - 133
Complexity:
moderate

Purpose

This function provides a flexible way to persist changes to graph database nodes. It handles both dictionary-like objects and Neo4j node objects, extracts their properties and labels, constructs appropriate Cypher queries, and executes them to update the database. It's designed to work with nodes that have a UID (unique identifier) property and can handle nodes with or without labels.

Source Code

def push_changes(node):
    """
    Push changes to a node to the database
    
    Parameters
    ----------
    node : dict or node-like object
        Node with properties to update
    """
    # Extract node properties, handling both dict-like and node-like objects
    if hasattr(node, 'items'):
        # Dict-like object
        properties = {k: v for k, v in node.items() if k != 'labels'}
        labels = node.get('labels', [])
        uid = node.get('UID')
    else:
        # Node-like object from previous driver
        properties = {k: node[k] for k in node.keys() if k != 'UID'}
        labels = list(node.labels)
        uid = node['UID']
    
    # Construct labels string for Cypher
    if labels:
        labels_str = ':'.join(labels)
        match_clause = f"MATCH (n:{labels_str} {{UID: $uid}})"
    else:
        match_clause = "MATCH (n {UID: $uid})"
    
    # Update node properties
    if properties:
        set_clauses = [f"n.`{key}` = ${key}" for key in properties]
        query = f"{match_clause} SET {', '.join(set_clauses)}"
        params = {"uid": uid, **properties}
        run_query(query, params)
    
    return

Parameters

Name Type Default Kind
node - - positional_or_keyword

Parameter Details

node: A node object to be updated in the database. Can be either a dict-like object with 'UID', 'labels', and other properties as key-value pairs, or a Neo4j node-like object with a labels attribute and dictionary-style property access. The node must have a 'UID' property that uniquely identifies it in the database. Properties with key 'labels' are treated specially as node labels rather than properties.

Return Value

Returns None. The function performs a side effect of updating the database but does not return any value.

Dependencies

  • neo4j

Required Imports

from neo4j import GraphDatabase

Usage Example

# Assuming run_query() function and Neo4j connection are set up

# Example 1: Using a dictionary-like node
node_dict = {
    'UID': 'node-123',
    'labels': ['Person', 'Employee'],
    'name': 'John Doe',
    'age': 30,
    'department': 'Engineering'
}
push_changes(node_dict)

# Example 2: Using a Neo4j node object (from a query result)
# result = run_query("MATCH (n:Person {UID: 'node-123'}) RETURN n")
# node_obj = result[0]['n']
# node_obj['age'] = 31  # Modify property
# push_changes(node_obj)

# Example 3: Node without labels
node_no_labels = {
    'UID': 'node-456',
    'status': 'active',
    'updated_at': '2024-01-15'
}
push_changes(node_no_labels)

Best Practices

  • Ensure the node has a valid UID property before calling this function, as it's required for matching
  • The function depends on an external run_query() function that must be properly implemented with database connection handling
  • Properties named 'labels' are excluded from property updates and treated as node labels instead
  • The function does not validate if the node exists before attempting to update; ensure the node exists in the database
  • Consider wrapping calls in try-except blocks to handle potential database connection errors
  • For batch updates, consider using transactions or batch processing rather than calling this function repeatedly
  • The UID property itself is not updated, only other properties are modified
  • Label changes are not supported by this function; it only uses labels for matching

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function update_node 79.3% similar

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

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

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

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_node_and_ensure_relationships 58.3% 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 update_user 58.2% 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
← Back to Browse