Neo4j returns all nodes and relationships that exist in a specific subgraph
I would like to point to a node and return all relationships that node has, along with any other relationships that connect the rest of the nodes.
An example of what I would like to return is:
Eric, PARENT_OF, Mia Eric, PARENT_OF, Peter Mia, SIBLING_OF, Peter Mia, SPOUSE_OF, Mark ...
Assuming the specified node is equal Eric
, they should return all relationships that are directly related to it, as well as relationships that are not related to Eric
, but related to some of its connected nodes.
+3
source to share
1 answer
I simulated your scenario with this dataset:
CREATE (eric:Person {name:'Eric'})
CREATE (mia:Person {name:'Mia'})
CREATE (peter:Person {name:'Peter'})
CREATE (mark:Person {name:'Mark'})
CREATE (eric)-[:PARENT_OF]->(mia)
CREATE (eric)-[:PARENT_OF]->(peter)
CREATE (mia)-[:SIBLING_OF]->(peter)
CREATE (mia)-[:SPOUSE_OF]->(mark)
The following query should work to achieve your goal:
MATCH (root:Person {name:'Eric'})-[r*1..3]->(a:Person)
UNWIND r AS rs
RETURN DISTINCT startNode(rs).name, type(rs), endNode(rs).name
As a result:
╒════════════════════╤════════════╤══════════════════╕
│"startNode(rs).name"│"type(rs)" │"endNode(rs).name"│
╞════════════════════╪════════════╪══════════════════╡
│"Eric" │"PARENT_OF" │"peter" │
├────────────────────┼────────────┼──────────────────┤
│"Eric" │"PARENT_OF" │"Mia" │
├────────────────────┼────────────┼──────────────────┤
│"Mia" │"SIBLING_OF"│"peter" │
├────────────────────┼────────────┼──────────────────┤
│"Mia" │"SPOUSE_OF" │"Mark" │
└────────────────────┴────────────┴──────────────────┘
+3
source to share