知识库

将(子)图导出到 Cypher 脚本并再次导入

通常您希望将完整的(或部分)数据库导出到文件并再次导入,而无需复制实际的数据库文件。如果您想执行后者,请使用 neo4j-admin dump/load

以下介绍两种从您的数据库或 Cypher 语句创建 Cypher 脚本文件的方法。这也可以用于降级(较小的)数据库。

格式

关于这些工具写入的格式的一些说明

  • 重新创建索引和约束

  • 每个节点(CREATE)/ 关系(2x MATCH + CREATE)的简单语句

  • 可选地,您可以配置导出以使用 MERGE 而不是 CREATE

  • 数据创建以批次进行(默认情况下为 40k),可选地用 :begin:commit 括起来

  • 使用现有的约束进行节点查找

  • 如果该标签上不存在约束,则使用人工约束+属性(UNIQUE IMPORT LABEL.UNIQUE IMPORT ID),其中属性值为节点 ID,在节点创建时

  • 最后以批次清理人工标签+属性+约束

APOC

您可以安装 APOC 过程库。

然后使用 apoc.export.cypher.* 过程从您的图形或数据创建 export.cypher 文件。文档 中有更多内容,但下面是一些示例。

这些过程具有配置选项,用于为不同的输出生成格式,以及将节点、关系和架构脚本拆分为不同的文件。

请注意,您必须首先在 neo4j.conf 中启用写入和读取文件的功能。
apoc.export.file.enabled=true
apoc.import.file.enabled=true
// exports the whole database incl. indexes as cypher statements to the provided file
CALL apoc.export.cypher.all('/tmp/export.cypher',{format:'cypher-shell'})

// exports given nodes and relationships incl. indexes as cypher statements to the provided file
MATCH path = (p1:Person)-[r:KNOWS]->(p2:Person)
WITH collect(p1)+collect(p2) as export_nodes, collect(r) as export_rels
CALL apoc.export.cypher.data(export_nodes,export_rels,'/tmp/export.cypher',{format:'cypher-shell'})
YIELD file, source, format, nodes, relationships, properties, time
RETURN nodes, relationships, time;

// exports given graph object incl. indexes as cypher statements to the provided file
...
CALL apoc.graph.fromPaths([paths],'export_graph',{}) YIELD graph
CALL apoc.export.cypher.graph(graph,'/tmp/export.cypher',{format:'cypher-shell'}) YIELD time
RETURN time;

// exports nodes and relationships from the cypher statement incl. indexes as cypher statements to the provided file
CALL apoc.export.cypher.query(
'MATCH (p1:Person)-[r:KNOWS]->(p2:Person) RETURN *',
'/tmp/export.cypher',{format:'cypher-shell'});

使用 cypher-shell 导入

如果您使用 cypher-shell 格式导出文件,它将包含在 shell 中用于事务的正确语法。

然后,您也可以使用 cypher-shell 导入它们。

$ cat /tmp/export.cypher | ./bin/cypher-shell -u neo4j -p password

导出文件示例

// create nodes
:begin
CREATE (:`UNIQUE IMPORT LABEL` {`UNIQUE IMPORT ID`:0});
CREATE (:`User` {`age`:43, `name`:"User1"});
:commit

// add schema
:begin
CREATE INDEX ON :`User`(`age`);
CREATE CONSTRAINT ON (node:`User`) ASSERT node.`name` IS UNIQUE;
CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT node.`UNIQUE IMPORT ID` IS UNIQUE;
:commit

// wait for index completion
call db.awaitIndexes();

// create relationships
:begin
MATCH (n1:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`:0}), (n2:`User`{`name`:"User1"}) CREATE (n1)-[:`KNOWS` {`since`:2011}]->(n2);
:commit

// clean up temporary import keys (batched)
:begin
MATCH (n:`UNIQUE IMPORT LABEL`)  WITH n LIMIT 1000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`;
:commit
:begin
DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT node.`UNIQUE IMPORT ID` IS UNIQUE;
:commit