2016-11-28 221 views
3

enter image description here查詢你喜歡誰,誰喜歡你,相互喜歡?

有沒有更好的方法來做到這一點比3個單獨的查詢?

MATCH (you:User {name: "Alexander"})-[:LIKES]->(youLike:User) 
RETURN youLike 

MATCH (likesYou:User)-[:LIKES]->(you:User {name: "Alexander"}) 
RETURN likesYou 

MATCH (mutualLike:User)-[:LIKES]->(you:User {name: "Alexander"})-[:LIKES]->(mutualLike:User) 
RETURN mutualLike 

回答

3

這是一次查詢。

基本上,先找到自己,選擇找到你喜歡的人並收集他們,選擇性地找到喜歡你的人並收集他們,然後返回兩個集合和這兩個交集。

通過匹配識別您的節點並重復使用它,您可以匹配一次而不是三次。

使用收集過濾器功能可以讓您找到兩個:LIKES人口的交集,而無需重新匹配這些節點。

OPTIONAL關鍵字允許查詢在:LIKES填充爲空時繼續。

MATCH (you:User {name: "Alexander"}) 
WITH you 
OPTIONAL MATCH(you)-[:LIKES]->(youLike:User) 
WITH you, collect(youLike) as youLike 
OPTIONAL MATCH (likesYou:User)-[:LIKES]->(you) 
WITH you, youLike, collect(likesYou) as likesYou 
RETURN you 
, youLike 
, likesYou 
, filter(n in youLike where n in likesYou) as mutualLike