You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 Department with a name property (e.g., 'D1', 'D1.A1', 'D1.A1.B1')
  • Parent departments connect to child departments via a PARENT_OF relationship (so (parent:Department)-[:PARENT_OF]->(child:Department))
  • Departments link to their users via a HAS_USER relationship (so (dept:Department)-[:HAS_USER]->(user:User)), with users having a name property 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:

  1. Path Matching: The [:PARENT_OF*] matches any number of consecutive PARENT_OF relationships, capturing the full hierarchy from D1 down to D1.A1.B1. The nodes(path) function pulls out all departments on this exact path.
  2. Unwind & User Matching: We break down the list of departments to find every user linked to each department in the path.
  3. 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 PARENT relationship), 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 (like id), swap out the property in the MATCH clauses.
  • If users point to departments via a BELONGS_TO relationship instead, adjust the user match to (user:User)-[:BELONGS_TO]->(dept).

内容的提问来源于stack exchange,提问作者Yogi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:52:34