工作中需要將 A 圖數據庫的數據完全導出,並插入到 B 圖數據庫中。查找資料,好多都是通過導入,導出 CSV 文件來實現。然而,經過仔細研究發現,導出的節點/關系 都帶有 id
屬性 ,因為 A B 兩個庫的節點和關系是各自生成的,它們數據的 id
有重復。因此我擔心通過CSV 的方式插入數據庫 會造成數據的覆蓋或者某些數據導入不成功之類的問題,所以,就一直想找一種方式,通過 命令的方式來導入導出數據。也就是說:把 數據庫 A 中的節點/關系的創建命令導出來,在 B 中運行,從而會自動生成新的節點和關系,這樣就不會有 id
沖突的問題。經過查找資料,步驟如下:
Neo4j 圖數據庫通過命令導入導出數據庫
首先 閱讀一下該文檔
https://github.com/jexp/neo4j-shell-tools#cypher-import
一 安裝 neo4j-shell-tools
cd /path/to/neo4j-community-3.0.1
curl http://dist.neo4j.org/jexp/shell/neo4j-shell-tools_3.0.1.zip -o neo4j-shell-tools.zip
unzip neo4j-shell-tools.zip -d lib
二 重啟數據庫
cd /path/to/neo4j-community-3.0.1
sudo ./bin/neo4j restart
三 關閉數據庫,導出命令
suo ./neo4j stop
sudo ./neo4j-shell -path /opt/neo4j/data/databases/graph.db
會顯示如下內容:
an@an-virtual-machine:/opt/neo4j/bin$ sudo ./neo4j-shell -path /opt/neo4j/data/databases/graph.db
NOTE: Local Neo4j graph database service at '/opt/neo4j/data/databases/graph.db'
Welcome to the Neo4j Shell! Enter 'help' for a list of commands. Please note that neo4j-shell is deprecated and to be replaced by cypher-shell.
neo4j-sh (?)$
四 導出命令
neo4j-sh (?)$ export-cypher -r -o /home/an/sisi.cypher match(n)-[r]-(m)return n,r,m
命令運行完畢,會顯示如下輸出,並生成相應文件 /home/an/sisi.cypher.
經測試,(n)-[r]-(m) 雖然沒有指定方向,但是由於程序會生成一些特殊的label,從而確保不會出現雙方向重復匹配情況。能夠確保數據的單一性。
Wrote Nodes 0. 100%: nodes = 167276 rels = 1915138 properties = 0 time 15891 ms total 15891 ms
Wrote Relationships 1. 100%: nodes = 167276 rels = 2082410 properties = 190061 time 3139 ms total 19030 ms
Wrote to Cypher-file /home/an/sisi.cypher 2. 100%: nodes = 167276 rels = 2082410 properties = 190061 time 2 ms total 19032 ms
五 修改導出的命令文件
導出的命令文件內容是 一些 cypher 命令,和一些事務相關命令。這些命令是要在 cypher-shell
中運行的,因此要適合它的要求。
修改內容如下:
1. begin => :begin
2. commit => :commit
3. 刪掉 schema await 語句
六 打開數據庫,運行命令
打開數據庫,並進入 cypher-shell
界面
sudo ./bin/neo4j start
sudo ./cypher-shell -u neo4j -p neo4j //用戶名 密碼
顯示如下:
an@an-virtual-machine:/opt/neo4j/bin$ sudo ./cypher-shell -u neo4j -p root
Connected to Neo4j 3.2.0 at bolt://localhost:7687 as user neo4j.
Type :help for a list of available commands or :exit to exit the shell.
Note that Cypher queries must end with a semicolon.
neo4j>
為什么之前要修改導出的命令文件,在begin和commit前加 : ,是因為如下原因:
neo4j> :help
Available commands:
:begin Open a transaction
:commit Commit the currently open transaction
:exit Exit the logger
:help Show this help message
:history Print a list of the last commands executed
:param Set the value of a query parameter
:params Prints all currently set query parameters and their values
:rollback Rollback the currently open transaction
這里如果發現無法啟動數據庫,就看一看剛才打開的 neo4j-shell 終端有沒有關閉,如果沒有關閉,首先關閉該終端,然后在重啟數據庫。
七 運行命令
將導出文件sisi.cypher 中的 cypher 命令 貼入
cypher-shell` 終端並運行即可。
導出的文件應該是 :begin
為起始行,:commit
為結束行。
如果,你有更好的方式來實現類似的需求,請一定要告訴我,不勝感激。