简体   繁体   中英

Cypher to connect matched nodes based on specific relationship

If I do:

MATCH (x:NODE {x.name: "Node1"})-[r:REL1]-(y:NODE) return x,r,y

How do I then find all the REL1 relationships amongst the set of x and y nodes?

EDIT:

Based on the answers I think the question wasn't clear.

Example graph:

create (:T1 {name:1}), (:T1 {name:2}), (:T1 {name:3}), (:T1 {name:4}), (:T1 {name:5}), (:T1 {name:6}), (:T1 {name:7})
match (a:T1 {name:1}), (b:T1 {name:2}) create (a)-[r:REL1]->(b)
match (a:T1 {name:1}), (b:T1 {name:3}) create (a)-[r:REL1]->(b)
match (a:T1 {name:5}), (b:T1 {name:4}) create (a)-[r:REL1]->(b)
match (a:T1 {name:5}), (b:T1 {name:3}) create (a)-[r:REL1]->(b)
match (a:T1 {name:5}), (b:T1 {name:2}) create (a)-[r:REL1]->(b)
match (a:T1 {name:5}), (b:T1 {name:1}) create (a)-[r:REL1]->(b)
match (a:T1 {name:7}), (b:T1 {name:6}) create (a)-[r:REL2]->(b)
match (a:T1 {name:7}), (b:T1 {name:5}) create (a)-[r:REL2]->(b)
match (a:T1 {name:7}), (b:T1 {name:4}) create (a)-[r:REL2]->(b)
match (a:T1 {name:7}), (b:T1 {name:3}) create (a)-[r:REL2]->(b)

I'm going to find everything that has a REL1 relationship with node name:5 . I want to also find all the REL1 relationships amongst the returned nodes.

So I should get

5->4
5->3
5->2
5->1
1->2
1->3

But not

7->5
7->4
7->3

Because those are REL2 relationships.

So I think I can do it like this:

match (a:T1 {name: 5})-[b:REL1]->(c:T1) return a,b,c
union match (a:T1)-[b:REL1]-(c:T1) return a,b,c

But the problem is that the graph I'm working with is really large, so this seems quite inefficient. I'd prefer to be able to

  1. Select a set of nodes (everything connected to 5 )
  2. Find all the connections amongst those nodes

如果需要找出x和y节点集中的所有REL1关系,则从x节点中删除条件。

MATCH (x:NODE)-[r:REL1]-(y:User) return x,r,y

我们正确地使用双向,以任何一种方式查找关系,但是当您尝试查找所有关系时,您仅选择一个关系REL1,从关系[]中删除标签,因此可以使用以下查询并返回*,它将返回所有使用的变量。

MATCH (x:NODE {x.name: "Node1"})-[r]-(y:NODE) return *

To get all the distinct node pairs connected by one or more REL1 relationships, just do this:

MATCH (a:T1)-[:REL1]->(c:T1)
RETURN DISTINCT a, c

The result would be:

╒══════════╤══════════╕
│"a"       │"c"       │
╞══════════╪══════════╡
│{"name":1}│{"name":2}│
├──────────┼──────────┤
│{"name":1}│{"name":3}│
├──────────┼──────────┤
│{"name":5}│{"name":1}│
├──────────┼──────────┤
│{"name":5}│{"name":2}│
├──────────┼──────────┤
│{"name":5}│{"name":3}│
├──────────┼──────────┤
│{"name":5}│{"name":4}│
└──────────┴──────────┘

If you also want the relationship(s) between each pair, you can do this:

MATCH (a:T1)-[r:REL1]->(c:T1)
RETURN a, c, COLLECT(r) AS rels

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM