Skip to content

Relationship API Reference

The Relationship class is used to define relationships between NodeModel classes in the OGM.

Features

  • Bidirectional Support: Define the same relationship on both node types for intuitive querying
  • Automatic Direction Detection: GraphIO automatically detects reverse relationships and generates appropriate Cypher queries
  • Relationship Properties: Support for properties on relationships with filtering capabilities
  • Type Safety: Full integration with Pydantic validation and Python type hints

Bidirectional Relationships

GraphIO supports bidirectional relationship definitions, allowing you to query relationships from both directions using the same relationship definition:

class Author(NodeModel):
    _labels = ['Author']
    _merge_keys = ['name']
    name: str

    # Forward relationship
    books: Relationship = Relationship('Author', 'WROTE', 'Book')

class Book(NodeModel):
    _labels = ['Book']
    _merge_keys = ['isbn']
    title: str
    isbn: str

    # Reverse relationship - same definition, automatically detected
    author: Relationship = Relationship('Author', 'WROTE', 'Book')

# Usage - query from either direction
author = Author.match(Author.name == "Isaac Asimov").first()
books = author.books.match().all()  # Forward

book = Book.match(Book.title == "Foundation").first()
author = book.author.match().first()  # Reverse - same relationship!

Key Points: - Both relationships create the same structure in Neo4j: (Author)-[:WROTE]->(Book) - GraphIO automatically detects when you're querying from the target side - Self-referencing relationships (e.g., Person -> Person) work normally (no reverse detection) - No performance impact - same underlying database relationships

Class Definition

Relationship

Relationship(source: str, rel_type: str, target: str, parent=None, **data)

Bases: BaseModel

match

match(*filter_ops)

Match and return instances of the target node with filtering capabilities. Returns a query builder for deferred execution.

Usage:

all_friends = person.knows.match().all()

best_friend = person.knows.filter(RelField("score") == 100).match(Person.age > 25).first()

filter

filter(*filter_ops)

Filter relationships based on relationship properties and return a query builder.

Usage: person.knows.filter(RelField("score") > 90).match(Person.age > 50)

Parameters:

Name Type Description Default
filter_ops

FilterOp objects for complex filtering on relationship properties

()

Returns:

Type Description

Query with relationship filters applied

add

add(node: Any, properties: dict = None)

Add a target node to this relationship

dataset

dataset()

relationshipset

relationshipset()