0

using neo4j I'm trying to find max depth in this graph:

graph

Using this query I find deph value 20 (because I have this bidirectional relationship):

MATCH p=(u:User)-[:Amico*]->(f:User)
RETURN p, length(p) order by length(p) desc limit 1

How can I have the true value of this depth?

Francesco Bocci
  • 827
  • 8
  • 19
  • Does this answer your question? [How do find the longest path in a cyclic Graph between two nodes?](https://stackoverflow.com/questions/2679081/how-do-find-the-longest-path-in-a-cyclic-graph-between-two-nodes) – dbl Oct 18 '20 at 10:53
  • It's a good Idea, But I don't know how to write it in Cypher. – Francesco Bocci Oct 18 '20 at 11:08
  • My bad, though you are missing the theoretical part... – dbl Oct 18 '20 at 11:19
  • Either way my initial comment was to use `dfs`, yet `bfs` was used in the accepted answer from the thread above. [docs DFS tutorial](https://neo4j.com/docs/graph-data-science/current/algorithms/dfs/) && [docs BFS tutorial docs](https://neo4j.com/docs/graph-data-science/current/algorithms/bfs/) – dbl Oct 18 '20 at 11:36
  • Yet [another link](https://neo4j.com/developer/kb/achieving-longestpath-using-cypher/) from their docs that seems related. – dbl Oct 18 '20 at 11:42
  • 1
    By the way, Neo4j can traverse a relationship in either direction equally efficiently. If 2 relationships in opposite directions are always paired together, that implies a bad data model (which requires unnecessary storage overhead and overly-complex code-- as you are seeing). For more info, see the Note at the bottom of [this answer](https://stackoverflow.com/a/60645114/974731). If you only had a single relationship between every pair of nodes, your original query (except with an undirected relationship) should have worked. – cybersam Oct 19 '20 at 18:44

1 Answers1

1

I guess you could solve it by only considering paths in which each node only appears once. Neo4j's apoc library offers a function for that:

MATCH p=(u:User)-[:Amico*]->(f:User)
WHERE NOT apoc.coll.containsDuplicates(nodes(p))
RETURN p, length(p) order by length(p) desc limit 1
Graphileon
  • 5,275
  • 3
  • 17
  • 31