RomanMitasov
RomanMitasov

Reputation: 1021

Cypher - given relationship, get the nodes

If I do the query

MATCH (:Label1 {prop1: "start node"}) -[relationships*1..10]-> ()
UNWIND relationships as relationship
RETURN DISTINCT relationship

How do I get nodes for each of acquired relationship to get result in format:

╒════════╤════════╤═══════╕
│"from"  │"type"  │"to"   │
╞════════╪════════╪═══════╡
├────────┼────────┼───────┤
└────────┴────────┴───────┘

Is there a function such as type(r) but for getting nodes from relationship?

Upvotes: 1

Views: 200

Answers (2)

Vincent Rupp
Vincent Rupp

Reputation: 655

RomanMitasov and ray have working answers above.

I don't think they quite get at what you want to do though, because you're basically returning every relationship in the graph in a sort of inefficient way. I say that because without a start or end position, specifying a path length of 1-10 doesn't do anything.

For example:

CREATE (r1:Temp)-[:TEMP_REL]->(r2:Temp)-[:TEMP_REL]->(r3:Temp)

Now we have a graph with 3 Temp nodes with 2 relationships: from r1 to r2, from r2 to r3.

Run your query on these nodes:

MATCH (:Temp)-[rels*1..10]->(:Temp)
UNWIND rels as rel
RETURN startNode(rel), type(rel), endNode(rel)

And you'll see you get four rows. Which is not what you want because there are only two distinct relationships.

You could modify that to return only distinct values, but you're still over-searching the graph.

To get an idea of what relationships are in the graph and what they connect, I use a query like:

MMATCH (n)-[r]->(m)
RETURN labels(n), type(r), labels(m), count(r)

The downside of that, of course, is that it can take a while to run if you have a very large graph.

If you just want to see the structure of your graph: CALL db.schema.visualization()

Best wishes and happy graphing! :)

Upvotes: 2

RomanMitasov
RomanMitasov

Reputation: 1021

Yes, such functions do exist!

  • startNode(r) to get the start node from relationship r
  • endNode(r) to get the end node

Here's the final query:

MATCH () -[relationships*1..10]-> ()
UNWIND relationships as r
RETURN startNode(r) as from, type(r) as type, endNode(r) as to

Upvotes: 0

Related Questions