知识库

LOAD CSV 和/或 Import 引入时引号的解析

当使用 LOAD CSVneo4j-admin import 时,如果您的数据包含引号,则必须对其进行正确转义才能导入,否则可能会遇到错误

neo4j-admin import 错误

$ ./neo4j-admin import --database=hr.db --nodes:Staff hr.csv
Neo4j version: 3.3.0
Importing the contents of these files into /home/neo4j/neo4j-enterprise-3.3.0/data/databases/hr.db:
Nodes:
  :Staff
  /home/neo4j/neo4j-enterprise-3.3.0/bin/hr.csv

Available resources:
  Total machine memory: 4.95 GB
  Free machine memory: 4.46 GB
  Max heap memory : 989.88 MB
  Processors: 1
  Configured max memory: 3.14 GB

Nodes, started 2017-12-07 14:35:45.158+0000
[*>:??----------------------------------------------------------------------------------------]    0 ∆    0
Done in 159ms
Error in input data
Caused by:ERROR in input
  data source: BufferedCharSeeker[source:/home/neo4j/neo4j-enterprise-3.3.0/bin/hr.csv, position:59, line:2]
  in field: name:string:2
  for header: [id:int, name:string, supervisor:int]
  raw field value: 2
  original error: At /home/neo4j/neo4j-enterprise-3.3.0/bin/hr.csv:2 -  there's a field starting with a quote and whereas it ends that quote there seems to be characters in that field after that ending quote. That isn't supported. This is what I read: 'Bill"'

LOAD CSV 错误

LOAD CSV WITH HEADERS FROM "file:///hr.csv" AS row FIELDTERMINATOR ','  CREATE (n:Staff { staffid: toInt(row.id), staff_name: row.name});
At /home/neo4j/neo4j-enterprise-3.3.0/import/hr.csv:2 -  there's a field starting with a quote and whereas it ends that quote there seems to be characters in that field after that ending quote. That isn't supported. This is what I read: 'Bill"'

对于上述情况,我的 hr.csv 定义为

id:int,name:string,supervisor:int
1,Emil Eifrem,1
2,"Bill" William Smith,1
3,Dana Canzano,2

而错误发生在解析第 2 行,原因是该行以 " 开头。为了将上述内容导入 Neo4j 并使第 2 行被识别为 "Bill" William Smith,需要将数据重新格式化为

id:int,name:string,supervisor:int
1,Emil Eifrem,1
2,"""Bill"" William Smith",1
3,Dana Canzano,2

然后,数据将成功导入,作为证据

neo4j> match (n) return n;
+-----------------------------------------------------------------+
| n                                                               |
+-----------------------------------------------------------------+
| (:Staff {name: "Emil Eifrem", id: 1, supervisor: 1})            |
| (:Staff {name: "\"Bill\" William Smith", id: 2, supervisor: 1}) |
| (:Staff {name: "Dana Canzano", id: 3, supervisor: 2})           |
+-----------------------------------------------------------------+

请注意,CSV 数据的这种语法结构(相对于引号数据的包含)也成功地被 MS ExcelOpen Office Calc 处理