如何用Cypher查询部门树中两节点间的节点及关联用户
Cypher Query to Fetch Path Departments and Their Associated Users
Got it, let's work through this problem step by step. First, I'll make some reasonable assumptions about your graph model (since you didn't specify it explicitly):
- Department nodes have a label
Departmentwith anameproperty (e.g., 'D1', 'D1.A1', 'D1.A1.B1') - Parent departments connect to child departments via a
PARENT_OFrelationship (so(parent:Department)-[:PARENT_OF]->(child:Department)) - Departments link to their users via a
HAS_USERrelationship (so(dept:Department)-[:HAS_USER]->(user:User)), with users having anameproperty like 'U1', 'U2', 'U4'
Here's the Cypher query that will deliver exactly the results you need:
// Match the full hierarchy path from root department D1 to target department D1.A1.B1 MATCH path=(root:Department {name: 'D1'})-[:PARENT_OF*]->(target:Department {name: 'D1.A1.B1'}) // Extract all department nodes along the matched path WITH nodes(path) AS pathDepartments // Unwind the list to process each department individually UNWIND pathDepartments AS dept // Match all users associated with each department in the path MATCH (dept)-[:HAS_USER]->(user:User) // Collect unique departments and users to avoid duplicate entries WITH COLLECT(DISTINCT dept.name) AS departments, COLLECT(DISTINCT user.name) AS users // Return the final result sets RETURN departments, users
Breakdown of how this works:
- Path Matching: The
[:PARENT_OF*]matches any number of consecutivePARENT_OFrelationships, capturing the full hierarchy from D1 down to D1.A1.B1. Thenodes(path)function pulls out all departments on this exact path. - Unwind & User Matching: We break down the list of departments to find every user linked to each department in the path.
- Collect Results: Using
COLLECT(DISTINCT)ensures we don't get duplicate entries (a safe practice even if your data doesn't have overlaps right now).
Quick adjustments for different graph models:
- If your parent-child relationship is reversed (child departments point to parents with a
PARENTrelationship), update the path match to:MATCH path=(target:Department {name: 'D1.A1.B1'})-[:PARENT*]->(root:Department {name: 'D1'}) - If your department uses an identifier other than
name(likeid), swap out the property in theMATCHclauses. - If users point to departments via a
BELONGS_TOrelationship instead, adjust the user match to(user:User)-[:BELONGS_TO]->(dept).
内容的提问来源于stack exchange,提问作者Yogi
相关产品推荐
相关产品推荐

