3
votes

My graph looks like this

medium-[:firstChapter]->chapter1-[:nextChapter]->chapter2_to_N

there is only one node connected via :firstChapter and then several nodes may follow, connected via :nextChapter

I tried to match all nodes that are either connected via relationship :firstChapter to medium or connected via :nextChapter from one chapter to another

The query I tried looks like this

start n=node(543) match n-[:firstChapter|nextChapter*]->m return m;

node(543) is the node medium. Surprisingly, this query returns all nodes in the path, even though the nodes are not connected to n (=medium node) If I leave out the * sign after nextChapter, only the first node with the :firstChapter relationship is returned (chapter1), which seems to be correct.

start n=node(543) match n-[:firstChapter|nextChapter*]->m return m;

Why does the query above return nodes not connected to n? As far as I understand it, the * sign usually returns nodes that are an unlimited number of relationships away, right?

What is the best way to match all nodes of a path (only once) that are either connected via :firstChapter or :nextChapter to a start node? In this case all chapters

The query above serves that purpose, but I don't think the output is correct...

EDIT: Added a diagramm to clarify. As you can see, the first chapter may only be reached via :firstChapter, So it is still unclear, why the query above returns ALL chapter nodes Graph Diagram

2

2 Answers

8
votes

Try doing match p=n-[:firstChapter|nextChapter*]->m to see what p is. Hopefully that provides some insight about how they are connected.

What you might be looking for in the end is:

start n=node(543) 
match n-[:firstChapter|nextChapter*]->m 
return collect(distinct m);

To get a collection of distinct chapter nodes that follow n.

update Here's another one--didn't actually test it but it might get you closer to what you want:

start n=node(543)
match n-[:firstChapter]->f-[:nextChapter*]-m
return f + collect(distinct m);
2
votes

Using the * operator, the query looks for all relationships along the line for both relationship types, :firstChapter and :nextChapter (not just :nextChapter). Your chapter data for node(543) likely contains some relationships to chapter nodes not in the 543 chain and the query is returning them.

Consider adding an extra relationship using type :nextChapter to connect the start node to the first chapter, and check the relationships that exist on your chapters.

Then run:

start n=node(543) 
match n-[:nextChapter*]->m 
return m;

and see if you still get extra results. If so, you could run the following, bumping up n each time until you find the node that has the extra relationship(s) - (though I'm sure there are other ways!)

start n=node(543) 
match n-[:nextChapter*1..n]->m 
return m;