繁体   English   中英

Neo4j 用属性分组节点

[英]Neo4j group nodes with property

在 Neo4j 中,我想创建一个查询,该查询返回按公共属性分组的节点而不改变我的图形。 例如,如果我有下面的图表,其中每个人都拥有与公司中他的部门相对应的财产: 在此处输入图像描述

我希望我的查询返回如下图,其中节点被属性替换,并且边的权重对应于关系的数量:

在此处输入图像描述

你知道如何进行吗? 我看着 APOC 节点崩溃没有成功。

谢谢

也可以使用 Cypher。 我在本地使用以下 Cypher 查询创建了您的图表:

MERGE (p:Person{name: 'Alex', department: 'HR'})
MERGE (p1:Person{name: 'John', department: 'HR'})
MERGE (p2:Person{name: 'Kate', department: 'IT'})
MERGE (p3:Person{name: 'Mike', department: 'Sales'})
MERGE (p1)-[:R]->(p3)
MERGE (p1)-[:R]->(p2)
MERGE (p2)-[:R]->(p1)
MERGE (p)-[:R]->(p2)

现在,要将其转换为所需的图形,您可以尝试以下 Cypher 查询:

MATCH (p:Person)
WITH distinct p.department AS departmentName
MERGE (d:Department{name: departmentName}) <-- First create all the distinct department nodes
WITH COLLECT(departmentName) AS departments
UNWIND departments AS departmentName
MATCH (p:Person{department:departmentName})
OPTIONAL MATCH (p)<-[:R]-(p1:Person)
WITH departmentName, p1 WHERE p1 IS NOT NULL
WITH departmentName, p1.department AS sourceDepartment, count(distinct p1) AS relCount <-- For each department find out the number of distinct incoming relations, with respect to each department
MATCH (d1:Department{name: departmentName})
MATCH (d2:Department{name: sourceDepartment})
MERGE (d1)<-[:R{count: relCount}]-(d2) <-- Create the relationships between department and store the count in the relationship

要检查部门节点并验证它们,请运行以下命令:

MATCH (n:Department) RETURN n

最后,如果需要,您可以删除所有Person节点,如下所示:

MATCH (n:Person) DETACH DELETE n

如果你想“在不改变图形的情况下返回节点”,go 的方法是通过所谓的虚拟节点和关系。 这些节点/rels 像真实的一样嘎嘎作响,但仅存在于 memory 中。

任何其他机制(包括崩溃)都会改变图形。

更多关于虚拟节点/rels的信息可以在这里找到: https://neo4j.com/labs/apoc/4.4/virtual/

上述方法可以与纯 Neo4j 工具一起使用。 如果您需要更高级的交互,还有其他可视化层(例如 Graphileon:公开我为他们工作)提供更多可能性。

这是使用 apoc.nodes.collapse 返回子图的方法。

MATCH (p:Person)-[:R]->(c:Person)
WITH c, collect(p) as subgraph 
CALL apoc.nodes.collapse(subgraph,{properties:'combine', countMerge:false}) 
YIELD from, rel, to WHERE to is not null
RETURN from, rel, to 

结果:

在此处输入图像描述

可以通过这种方式创建具有关系权重的节点。 不幸的是, apoc.nodes.collapse 没有返回您描述的关系权重。 但是 apoc.collapse 可以使用 countMerge:true 计算合并的节点数。

MATCH (p:Person)-[:R]->(c:Person)
WITH c, collect(p) as subgraph, count(distinct p) AS relweight
WITH c.department as relto, [s in subgraph|s.department][0] as relfrom, relweight 
MERGE (d1:Department {name: relfrom})
MERGE (d2:Department {name: relto})
MERGE (d1)-[r:newR{wt: relweight}]->(d2)
RETURN d1, d2, r

结果:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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