🔍 Code Extractor

function create_relationship_with_retry

Maturity: 54

Creates a relationship between two nodes in a graph database with automatic retry logic that handles case-insensitive UID matching when the initial attempt fails.

File:
/tf/active/vicechatdev/CDocs/utils/uid_helper.py
Lines:
62 - 114
Complexity:
moderate

Purpose

This function provides robust relationship creation in graph databases (likely Neo4j) by attempting to create a relationship using standard methods first, then falling back to a Cypher query that handles case variations in UID properties (uid vs UID). This is useful when dealing with databases that may have inconsistent UID property naming conventions or when migrating data between systems with different casing standards.

Source Code

def create_relationship_with_retry(db, from_uid, to_uid, relationship_type, properties=None):
    """
    Create relationship with automatic retry with different UID case variants.
    
    Parameters
    ----------
    db : module
        Database module with create_relationship method
    from_uid : str
        Source node UID
    to_uid : str
        Target node UID
    relationship_type : str
        Type of relationship to create
    properties : dict, optional
        Properties for the relationship
        
    Returns
    -------
    bool
        True if relationship was created successfully
    """
    if properties is None:
        properties = {}
        
    # Try with original UIDs
    success = db.create_relationship(from_uid, to_uid, relationship_type, properties)
    if success:
        return True
        
    # Log the retry attempt
    logger.debug(f"Retrying relationship creation with alternate case variants between {from_uid} and {to_uid}")
    
    # Try with direct Cypher query as a fallback
    try:
        result = db.run_query(
            f"""
            MATCH (from), (to) 
            WHERE (from.uid = $from_uid OR from.UID = $from_uid)
            AND (to.uid = $to_uid OR to.UID = $to_uid)
            CREATE (from)-[r:{relationship_type}]->(to)
            RETURN r
            """,
            {
                "from_uid": from_uid,
                "to_uid": to_uid
            }
        )
        
        return result and len(result) > 0
    except Exception as e:
        logger.error(f"Error in fallback relationship creation: {e}")
        return False

Parameters

Name Type Default Kind
db - - positional_or_keyword
from_uid - - positional_or_keyword
to_uid - - positional_or_keyword
relationship_type - - positional_or_keyword
properties - None positional_or_keyword

Parameter Details

db: Database module or connection object that must implement two methods: create_relationship() for standard relationship creation and run_query() for executing Cypher queries. Expected to be a custom database wrapper or ORM-like module.

from_uid: String identifier for the source node in the relationship. This is the UID of the node where the relationship originates. Must match either 'uid' or 'UID' property in the database.

to_uid: String identifier for the target node in the relationship. This is the UID of the node where the relationship points to. Must match either 'uid' or 'UID' property in the database.

relationship_type: String specifying the type/label of the relationship to create in the graph database (e.g., 'KNOWS', 'WORKS_WITH', 'CONTAINS'). This becomes part of the Cypher query pattern.

properties: Optional dictionary containing key-value pairs of properties to attach to the relationship. Defaults to an empty dictionary if not provided. These properties are metadata about the relationship itself.

Return Value

Returns a boolean value: True if the relationship was successfully created (either through the initial attempt or the fallback Cypher query), False if both attempts failed or an exception occurred during the fallback attempt.

Dependencies

  • logging

Required Imports

import logging

Usage Example

import logging

logger = logging.getLogger(__name__)

# Assuming you have a database module/class
class DatabaseModule:
    def create_relationship(self, from_uid, to_uid, rel_type, props):
        # Standard relationship creation logic
        return False  # Simulating failure
    
    def run_query(self, query, params):
        # Execute Cypher query
        return [{'r': 'relationship_object'}]

db = DatabaseModule()

# Create a simple relationship
success = create_relationship_with_retry(
    db=db,
    from_uid='user123',
    to_uid='user456',
    relationship_type='FOLLOWS'
)

# Create a relationship with properties
success = create_relationship_with_retry(
    db=db,
    from_uid='user123',
    to_uid='post789',
    relationship_type='CREATED',
    properties={'timestamp': '2024-01-01', 'version': 1}
)

if success:
    print('Relationship created successfully')
else:
    print('Failed to create relationship')

Best Practices

  • Ensure the database module implements both create_relationship() and run_query() methods before calling this function
  • Initialize a logger object in the module scope to capture debug and error messages
  • The relationship_type parameter should follow Neo4j naming conventions (typically uppercase with underscores)
  • Be aware that the fallback Cypher query uses OR conditions which may impact performance on large databases
  • Consider adding indexes on uid/UID properties in your database for better performance
  • The function handles case variations (uid vs UID) but assumes these are the only property names used for unique identifiers
  • Properties dictionary should contain serializable values compatible with your graph database
  • This function does not prevent duplicate relationships - implement uniqueness constraints in your database schema if needed

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_relationship 76.9% similar

    Creates a directed relationship between two Neo4j graph database nodes identified by their UIDs, with optional properties attached to the relationship.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_node_with_relationship 66.1% 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_node_and_ensure_relationships 61.0% 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 create_node_with_uid 59.6% 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_related_nodes 58.3% similar

    Retrieves nodes from a Neo4j graph database that are related to a source node identified by its UID, with optional filtering by relationship type, target node label, and relationship direction.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
← Back to Browse