簡體   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