skip to Main Content

I am trying to detect cycles in a graph created on postgreSQl and Apache AGE using WITH RECURSIVE method. Can someone guide me why my cypher query would not be able to detect cycles? I have using this reference. Below is my trying code:

WITH RECURSIVE dependency_path AS (
  SELECT module_id, dependency_id, ARRAY[module_id] AS path
  FROM dependencies
  UNION ALL
  SELECT dp.module_id, d.dependency_id, path || dp.module_id
  FROM dependency_path dp, dependencies d
  WHERE dp.dependency_id = d.module_id
  AND NOT (dp.path @> ARRAY[d.dependency_id])
)
SELECT path || dependency_id AS cycle
FROM dependency_path
WHERE module_id = dependency_id
AND path @> ARRAY[dependency_id];

2

Answers


  1. The point in code from should be changed to join

    FROM dependency_path dp, dependencies d
    

    should be changed to

    JOIN dependencies d ON dp.dependency_id = d.module_id
    

    To ensure that the join is properly performed.
    and the next line should be changed from

    AND NOT (dp.path @> ARRAY[d.dependency_id])
    

    to

    WHERE NOT (dp.path @> ARRAY[d.dependency_id])
    

    This thing will make sure the condition is applied correctly.
    With these changes the recursive function to detect cycles in graph should work.

    Login or Signup to reply.
  2. In order to detect the cycle, use this code

    MATCH path=(n)-[*]->(n)
    RETURN path
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search