Neo4j中如何将共同好友的两人以MAY_KNOWS关系在图模式展示?
Solution: Show Virtual
MAY_KNOWS Relationship in Graph View Got it, let's get that virtual MAY_KNOWS relationship showing up in your Neo4j graph view! The issue with your original query is that it only returns the p1 and p2 nodes—Neo4j doesn't know you want to connect them with a custom relationship unless you explicitly define that in your return statement.
Modified Cypher Query (No APOC Needed)
This query constructs a virtual MAY_KNOWS relationship between p1 and p2 directly in the return, so Neo4j's graph view will render the connection:
MATCH (p1:Person)-[:IS_FRIEND_OF]->(commonFriend:Person) MATCH (p2:Person)-[:IS_FRIEND_OF]->(commonFriend) WHERE p1 <> p2 // Return the nodes AND the virtual MAY_KNOWS relationship RETURN DISTINCT p1, p2, p1-[:MAY_KNOWS]->p2 AS mayKnowsRel
Key Improvements:
DISTINCT: Prevents duplicateMAY_KNOWSrelationships ifp1andp2share multiple common friends (you'll only see one connection between them instead of one per common friend).- Explicit Relationship in Return: By including
p1-[:MAY_KNOWS]->p2in the return, you're telling Neo4j to visualize this connection as a relationship in graph mode, even though it's not stored in the database.
Optional: Use APOC for Richer Virtual Relationships
If you want to add properties to the virtual relationship (like the number of common friends), you can use Neo4j's APOC library (make sure it's enabled in your config):
MATCH (p1:Person)-[:IS_FRIEND_OF]->(commonFriend:Person) MATCH (p2:Person)-[:IS_FRIEND_OF]->(commonFriend) WHERE p1 <> p2 WITH p1, p2, COUNT(commonFriend) AS commonFriendCount // Create a virtual relationship with a property RETURN DISTINCT p1, p2, apoc.create.vRelationship(p1, 'MAY_KNOWS', {commonFriends: commonFriendCount}, p2) AS mayKnowsRel
How to Verify:
- Run the query in Neo4j Browser.
- Switch to the Graph view (top-left icon next to "Table").
- You'll now see
p1andp2nodes connected by aMAY_KNOWSrelationship, just like you wanted!
内容的提问来源于stack exchange,提问作者Στέργιος Μιναέμης
相关产品推荐
相关产品推荐

