Total Pageviews

2018/09/09

[Neo4j] Importing using Load CSV

假設我想要在 neo4j 建立起下圖的關係

由關係圖可以看出會有七個節點,包含
  • 哆啦A夢
  • 大雄
  • 靜香
  • 小夫
  • 胖虎
  • 小叮鈴
  • 玉子 (大雄的媽媽)
  • 伸助 (大雄的爸爸)

這七個人 (nodes) 之間的有九個關係:

  • 大雄的寵物是哆啦A夢
  • 大雄的配偶是靜香
  • 大雄的朋友是小夫
  • 大雄的朋友是胖虎
  • 小夫的朋友是胖虎
  • 哆啦A夢的妹妹是小叮鈴
  • 大雄的爸爸是伸助
  • 大雄的媽媽是玉子
  • 伸助的配偶是玉子

分析與執行步驟如下:


步驟如下:
(1) Prepare CSV file for nodes with UTF-8 encoding and store in neo4j-community-3.3.3\import

(2) Prepare CSV file for relationships with UTF-8 encoding and store in neo4j-community-3.3.3\import

(3) Prepare"load csv" command to load nodes and execute from neo4j browser
using periodic commit 
load csv with headers from
"file:///nodes.csv"
as nodes
create(:Person {id:nodes.node, name:nodes.name, gender:nodes.gender})

產生節點如下:


(4) Prepare"load csv" command to create relationships and execute from neo4j browser
using periodic commit 
load csv with headers from
"file:///relationships.csv"
as line
match (from:Person), (to:Person) where from.id=line.From and to.id=line.To 
create (from)-[:REL {type: line.`Relation Type`}]->(to)

建立關係後如下:


由於,我們期待的圖形是下圖,故會執行步驟 5, 6 來做關係的 rename

(5) Execute additional "cleanup" step for Labels and RelTypes
根據步驟 4 所建立的關係,依據關係的屬性,加以rename,重複建立一條有關係
//Create duplicate relationship with appropriate type
MATCH (n1)-[r1:REL{type:'SPOUSE_OF'}]->(m1),
      (n2)-[r2:REL{type:'PET_OF'}]->(m2),
      (n3)-[r3:REL{type:'FRIEND_OF'}]->(m3),
      (n4)-[r4:REL{type:'SISTER_OF'}]->(m4),
      (n5)-[r5:REL{type:'MOTHER_OF'}]->(m5),
      (n6)-[r6:REL{type:'FATHER_OF'}]->(m6)
merge (n1)-[:SPOUSE_OF]->(m1)
merge (n2)-[:PET_OF]->(m2)
merge (n3)-[:FRIEND_OF]->(m3)
merge (n4)-[:SISTER_OF]->(m4)
merge (n5)-[:MOTHER_OF]->(m5)
merge (n6)-[:FATHER_OF]->(m6)

建立新的關係後,圖形如下:

(6) Remove duplicate relationships
此步驟將會清理多餘的關係,將原本所建立的 REL 關係予以刪除
//Remove duplicate relationships
match ()-[r:REL]-() delete r;

刪除後,圖形如下:


No comments: