Sham
Sham

Reputation: 33

Neo4j - Using Cypher start at a node and Traverse graph to a specified depth and find nodes and relationships

I have a simple graph in which I am trying to start at a particular node and traverse a depth of 2. From this traversal I am trying to extract the names of nodes and relationships.

This is my query,

    START n=node(5)
    MATCH p=(n)-[r:Relation*0..2]-(m)
    RETURN n.name,r.name,m.name;

I get this error:

    Type mismatch: expected Map, Node or Relationship but was Collection<Relationship> (line 3, column 15)

In the error description, it points a ^ symbol to r.name

Can Someone help me understand this issue. My goal is to get the names of relationships along way..

From what I have understood, the r is being returned as a collection. Is there a way to display the individual names within the collection?

Upvotes: 3

Views: 2917

Answers (1)

Jim Biard
Jim Biard

Reputation: 2272

Sham,

As you noted, the problem is that 'r' is a collection of relationships that may have 0, 1, or 2 elements. You can use the reduce function to create a string of the relationship names and return that string.

START n=node(5)
MATCH (n)-[r:Relation*0..2]-(m)
WITH n, m, reduce(s = '', rel IN r | s + rel.name + ',') as rels
RETURN n.name, m.name, rels;

Grace and peace,

Jim

Upvotes: 8

Related Questions