Skip to content

[Feature request] Support bloodline (bidirectional) relationships in graph #265

@mpskovvang

Description

@mpskovvang

The bloodline is a powerful relationship in trees, but unfortunately, it is not implemented in graphs.

If possible, this feature would enable developers to query interconnected nodes more effectively and broaden the potential use cases for this package.

Suggested Implementation

I have minimal experience with recursive queries, but I believe the following SQL query could serve as a starting point for implementing this feature in a graph context:

WITH RECURSIVE laravel_cte AS (
    -- Anchor query: Start from node
    SELECT 
        source_id AS id, 
        target_id, 
        0 AS depth, 
        ARRAY[source_id, target_id] AS path
    FROM edges
    WHERE source_id = ? OR target_id = ?

    UNION ALL

    -- Recursive query: Continue tracing both directions while avoiding revisits
    SELECT 
        CASE WHEN edges.source_id = laravel_cte.id THEN edges.target_id ELSE edges.source_id END AS id,
        CASE WHEN edges.source_id = laravel_cte.id THEN edges.target_id ELSE edges.source_id END AS target_id,
        laravel_cte.depth + 1 AS depth, 
        laravel_cte.path || CASE WHEN edges.source_id = laravel_cte.id THEN edges.target_id ELSE edges.source_id END AS path
    FROM edges
    JOIN laravel_cte ON (edges.source_id = laravel_cte.id OR edges.target_id = laravel_cte.id)
    WHERE NOT CASE WHEN edges.source_id = laravel_cte.id THEN edges.target_id ELSE edges.source_id END = ANY(laravel_cte.path)
)

-- Final selection: Return distinct node IDs connected to 58
SELECT DISTINCT id
FROM laravel_cte;

However, I'm a bit concerned that the use of OR and CASE conditions within the recursive query may lead to performance bottlenecks, especially with large datasets

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions