function create_relationship
Creates a directed relationship between two Neo4j graph database nodes identified by their UIDs, with optional properties attached to the relationship.
/tf/active/vicechatdev/CDocs/db/db_operations.py
360 - 412
moderate
Purpose
This function establishes a typed relationship edge in a Neo4j graph database between a source node and a target node. It's used for building graph structures by connecting entities with labeled relationships (e.g., 'KNOWS', 'CONTAINS', 'REFERENCES'). The function handles database connection management, error logging, and returns success/failure status. It's particularly useful in knowledge graph construction, document relationship mapping, and entity linking scenarios.
Source Code
def create_relationship(from_uid: str,
to_uid: str,
relationship_type: str,
properties: Optional[Dict[str, Any]] = None) -> bool:
"""
Create a relationship between two nodes identified by their UIDs.
Args:
from_uid: UID of source node
to_uid: UID of target node
relationship_type: Type of relationship to create
properties: Optional properties for the relationship
Returns:
Boolean indicating whether the relationship was created successfully
"""
try:
if properties is None:
properties = {}
driver = get_driver()
with driver.session() as session:
# Modified query to look for both uppercase and lowercase UIDs
result = session.run(
f"""
MATCH (from)
WHERE from.UID = $from_uid
MATCH (to)
WHERE to.UID = $to_uid
CREATE (from)-[r:{relationship_type} $props]->(to)
RETURN r
""",
from_uid=from_uid,
to_uid=to_uid,
props=properties
)
record = result.single()
success = record is not None
# Log success or failure
if success:
logger.debug(f"Created relationship {relationship_type} from {from_uid} to {to_uid}")
else:
logger.warning(f"Failed to create relationship {relationship_type} from {from_uid} to {to_uid}")
return success
except Exception as e:
logger.error(f"Error creating relationship: {e}")
import traceback
logger.error(f"Traceback: {traceback.format_exc()}")
return False
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
from_uid |
str | - | positional_or_keyword |
to_uid |
str | - | positional_or_keyword |
relationship_type |
str | - | positional_or_keyword |
properties |
Optional[Dict[str, Any]] | None | positional_or_keyword |
Parameter Details
from_uid: String identifier (UID) of the source node from which the relationship originates. Must match an existing node's UID property in the database. This is case-sensitive and should correspond to a node's UID attribute.
to_uid: String identifier (UID) of the target node to which the relationship points. Must match an existing node's UID property in the database. This is case-sensitive and should correspond to a node's UID attribute.
relationship_type: String specifying the type/label of the relationship to create (e.g., 'KNOWS', 'CONTAINS', 'REFERENCES'). This becomes the relationship type in Neo4j and should follow Neo4j naming conventions (typically uppercase with underscores). Used in Cypher query as a dynamic relationship type.
properties: Optional dictionary containing key-value pairs to attach as properties to the relationship. Can include metadata like timestamps, weights, confidence scores, etc. Defaults to an empty dictionary if not provided. Values can be any JSON-serializable type supported by Neo4j.
Return Value
Type: bool
Returns a boolean value: True if the relationship was successfully created (both nodes were found and the relationship was established), False if the operation failed (nodes not found, database error, or any exception occurred). The function logs detailed information about success or failure.
Dependencies
neo4jloggingtypingtraceback
Required Imports
from typing import Dict, Any, Optional
import logging
from CDocs.db import get_driver
Conditional/Optional Imports
These imports are only needed under specific conditions:
import traceback
Condition: only used when an exception occurs for detailed error logging
OptionalUsage Example
from typing import Dict, Any, Optional
from CDocs.db import get_driver
import logging
# Assuming logger and get_driver are properly configured
# Example 1: Create a simple relationship without properties
success = create_relationship(
from_uid="user_123",
to_uid="document_456",
relationship_type="OWNS"
)
if success:
print("Relationship created successfully")
# Example 2: Create a relationship with properties
properties = {
"created_at": "2024-01-15T10:30:00",
"weight": 0.95,
"confidence": "high"
}
success = create_relationship(
from_uid="doc_001",
to_uid="doc_002",
relationship_type="REFERENCES",
properties=properties
)
# Example 3: Create a relationship in a knowledge graph
rel_props = {"since": "2020", "strength": 8}
result = create_relationship(
from_uid="person_alice",
to_uid="person_bob",
relationship_type="KNOWS",
properties=rel_props
)
Best Practices
- Always ensure both source and target nodes exist in the database before calling this function to avoid silent failures
- Use consistent naming conventions for relationship_type (typically uppercase with underscores, e.g., 'HAS_CHILD', 'BELONGS_TO')
- Check the return value to verify relationship creation succeeded before proceeding with dependent operations
- Consider adding timestamps or metadata to the properties dictionary for audit trails
- Be aware that the function uses dynamic Cypher query construction with f-strings for relationship_type, so ensure relationship_type is sanitized if coming from user input
- The function looks for nodes using the 'UID' property (uppercase), ensure your nodes have this property set
- Monitor logs for warnings and errors as the function provides detailed logging for debugging
- Handle the False return value appropriately in your application logic to manage failed relationship creation
- Consider wrapping multiple relationship creations in a transaction for atomicity if using this function repeatedly
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_relationship_with_retry 76.9% similar
-
function create_node_with_relationship 69.0% similar
-
function get_related_nodes 65.8% similar
-
function create_references_medicationtypes_relationship 63.9% similar
-
function create_node_with_uid 63.6% similar