user1844634
user1844634

Reputation: 1263

Neo4j returning duplicate nodes while traversing

While querying the ne04j for the traversing order. it's traversing multiple times few nodes. I am attaching the cypher query to create nodes and relationships and results it returns. Any help is appreciated.

CREATE (a:Package {name:'A'})
CREATE (b:Package {name:'B'})
CREATE (c:Package {name:'C'})
CREATE (d:Package {name:'D'})
CREATE (e:Package {name:'E'})
CREATE (f:Package {name:'F'})
CREATE (g:Package {name:'G'})
CREATE (h:Package {name:'H'})
CREATE (i:Package {name:'I'})
CREATE (o:Package {name:'O'})
CREATE (z:Package {name:'Z'})
CREATE (j:SEG2 {name:'India'})
CREATE (k:SEG1 {name:'Natural Account'})
CREATE (l:SEG3 {name:'Engineering'})
CREATE (m:SEG4 {name:'Currency'})


create (a)-[:DEPENDS_ON]->(b)
create (a)-[:DEPENDS_ON]->(d)
create (d)-[:DEPENDS_ON]->(e)
create (b)-[:DEPENDS_ON]->(c)
create (b)-[:DEPENDS_ON]->(f)
create (b)-[:DEPENDS_ON]->(g)
create (h)-[:DEPENDS_ON]->(g)
create (i)-[:DEPENDS_ON]->(a)
create (z)-[:DEPENDS_ON]->(a)
create (i)-[:DEPENDS_ON]->(z)
create (o)-[:DEPENDS_ON]->(i)
create (j)-[:MAP_TO]->(a)
create (k)-[:MAP_TO]->(a)
create (l)-[:MAP_TO]->(a)
create (m)-[:MAP_TO]->(a)
return a,b,c,d,e,f,g,h,i,j,k,l,m,o,z

cypher query :

MATCH (s3:SEG3{name:'Engineering'})-[:MAP_TO]->(ANODE:Package{name:'A'}) 
WITH ANODE 
MATCH (s4:SEG4{name:'Currency'})-[:MAP_TO]->(ANODE)  
MATCH (GG)-[:DEPENDS_ON*0..]->(ANODE) 
RETURN collect(GG.name)

Result:

["A", "I", "O", "Z", "I", "O"]

I am expecting the

["A","Z", "I", "O"]

Upvotes: 2

Views: 79

Answers (1)

František Hartman
František Hartman

Reputation: 15086

This is because you can get to your result through multiple paths in your data. Based on the chat you need the order in which dependencies can be resolved. To get this order you can sort by maximum path length from root:

MATCH (s3:SEG3{name:'Engineering'})-[:MAP_TO]->(ANODE:Package{name:'A'}),
  (s4:SEG4{name:'Currency'})-[:MAP_TO]->(ANODE),
  p=(GG)-[:DEPENDS_ON*0..]->(ANODE) 
WITH GG.name as name,max(length(p)) as l
ORDER BY l
RETURN collect(name)

Also note that you don't have to repeat the MATCH clause for every part of the pattern.

Upvotes: 1

Related Questions