在Ubuntu上用Node.js加载CSV到Memgraph时遇文件未找到错误
解决Memgraph通过Node.js导入CSV时文件未找到的问题
运行脚本出现如下错误:
Neo4jError: CSV file not found: file:…///updated_news.csv at captureStacktrace (/home/tbmu370/workspace/memgraph/sandbox/node_modules/neo4j-driver-core/lib/result.js:611:17) at new Result (/home/tbmu370/workspace/memgraph/sandbox/node_modules/neo4j-driver-core/lib/result.js:105:23) at Session._run (/home/tbmu370/workspace/memgraph/sandbox/node_modules/neo4j-driver-core/lib/session.js:229:16) at Session.run (/home/tbmu370/workspace/memgraph/sandbox/node_modules/neo4j-driver-core/lib/session.js:179:27) at insertNodes (/home/tbmu370/workspace/memgraph/sandbox/memcsv.js:50:21) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { constructor: [Function: Neo4jError] { isRetriable: [Function (anonymous)] }, code: ‘Memgraph.TransientError.MemgraphError.MemgraphError’, retriable: true }
代码中的核心错误
- LOAD CSV路径不匹配:Cypher查询里用
file:..///news.csv,但实际复制到Memgraph容器的是/updated_news.csv,且Memgraph的LOAD CSV必须使用容器内的绝对路径,格式为file:///开头。 - 逻辑冗余且冲突:已经用
csv-parser解析了本地CSV,却在循环里反复执行LOAD CSV,既重复读取文件,又会导致全量重复导入,完全没必要。 - Docker cp路径错误:
execSync里的源路径少了斜杠,/home/tbmu370workspace应为/home/tbmu370/workspace。 - 文件名称不一致:代码解析的是
news.csv,但复制到容器的是updated_news.csv,易造成混淆。
修正后的代码方案(推荐)
直接使用解析后的CSV数据批量插入,避免文件路径问题,同时提升导入效率:
const fs = require('fs'); const csv = require('csv-parser'); const neo4j = require('neo4j-driver'); const path = require("path"); // 解析CSV文件并返回Promise function parseCSVFile(filePath) { return new Promise((resolve, reject) => { const results = []; fs.createReadStream(filePath) .pipe(csv()) .on('data', (data) => results.push(data)) .on('end', () => resolve(results)) .on('error', (error) => reject(error)); }); } // 连接Memgraph并创建节点 async function createNodes() { const driver = neo4j.driver('bolt://localhost:7687'); const session = driver.session(); try { // 读取本地CSV文件(确保路径正确) const csvPath = path.join(__dirname, "../news.csv"); console.log(`Importing data from ${csvPath}`); const data = await parseCSVFile(csvPath); // 批量生成插入语句 for (const row of data) { const genre = JSON.parse(row.genre); const tags = JSON.parse(row.tags); const name = row.name; await session.run( `CREATE (news:News) SET news.genre = $genre, news.tags = $tags, news.title = $name`, { genre, tags, name } ); console.log(`Created node for ${name}, ${tags}, ${genre}`); } } catch (error) { console.error('Error:', error); } finally { await session.close(); await driver.close(); } } createNodes();
若坚持使用LOAD CSV方案
- 修正Docker复制命令,确保文件正确传入容器:
sudo docker cp /home/tbmu370/workspace/memgraph/news.csv ca5ef0b5c281:/news.csv - 修正Cypher查询的路径,且仅执行一次查询(不要放在循环里):
// 替换原循环内的代码 const query = ` LOAD CSV FROM "file:///news.csv" WITH HEADER IGNORE BAD AS row CREATE (news:News) SET news.genre = row.genre, news.tags = row.tags, news.title = row.name; `; await session.run(query);
内容的提问来源于stack exchange,提问作者Zet Hund Pet
相关产品推荐
相关产品推荐

