1. 程式人生 > >Neo4j系列-解讀《權力的遊戲》上

Neo4j系列-解讀《權力的遊戲》上

1.匯入資料

在githut下載資料CSV檔案:https://github.com/mathbeveridge/asoiaf/blob/master/data/asoiaf-all-edges.csv

將其儲存在當前庫的import資料夾

LOAD CSV WITH HEADERS FROM "file:///asoiaf-all-edges.csv" AS row MERGE (src:Character {name: row.Source}) MERGE (tgt:Character {name: row.Target}) MERGE (src)-[r:INTERACTS]->(tgt)SET r.weight = toInt(row.weight)

2. 檢視《權利的遊戲》圖

MATCH p=(:Character)-[:INTERACTS]-(:Character)
RETURN p
LIMIT 50

3.人物數量

MATCH (c:Character) RETURN count(c)

4.概要統計

MATCH (c:Character)-[:INTERACTS]->()
WITH c, count(*) AS num
RETURN min(num) AS min, max(num) AS max, avg(num) AS avg_characters, stdev(num) AS stdev

5.圖(網路)的直徑

MATCH (a:Character), (b:Character) WHERE id(a) > id(b)
MATCH p=shortestPath((a)-[:INTERACTS*]-(b))
WITH length(p) AS len, p
ORDER BY len DESC LIMIT 4
RETURN len, extract(x IN nodes(p) | x) AS path

6.最短路徑

MATCH (catelyn:Character {name:"Catelyn-Stark"}), (drogo:Character {name:"Drogo"})
MATCH p=shortestPath((catelyn)-[:INTERACTS*]-(drogo))
RETURN p

7.所有最短路徑

MATCH (catelyn:Character {name:"Catelyn-Stark"}), (drogo:Character {name:"Drogo"})
MATCH p=allShortestPaths((catelyn)-[:INTERACTS*]-(drogo))
RETURN p

8.關鍵節點

如果一個節點位於其它兩個節點所有的最短路徑上,即稱為關鍵節點。下面我們找出網路中所有的關鍵節點:

MATCH (a:Character), (b:Character) WHERE id(a) > id(b)
MATCH p=allShortestPaths((a)-[:INTERACTS*]-(b)) WITH collect(p) AS paths, a, b
UNWIND nodes(head(paths)) as c // first path
WITH * WHERE NOT c IN [a,b] AND all(path IN tail(paths) WHERE c IN nodes(path))
RETURN a.name, b.name, c.name AS PivotalNode, length(head(paths)) as pathLength, length(paths) as pathCount SKIP 490 LIMIT 10

拿"Eustace-Brune"和"Cressen"校驗,檢視兩個節點的最短路徑,看到結果剛好就是"Dick-Crabb"和"Renly-Baratheon":

MATCH (a:Character {name: "Eustace-Brune"}), (b:Character {name: "Cressen"})
MATCH p=allShortestPaths((a)-[:INTERACTS*]-(b))
RETURN p