从CSV导入关系至Neo4j:无法创建多条关系
Fixing Isolated Node Pairs When Importing CSV to Neo4j
Alright, let's break down why you're seeing only disconnected node pairs instead of the interconnected graph you expected, and fix this step by step.
Core Issues
There are two key problems with your current Cypher query:
- Unclean node names from CSV whitespace: Your CSV has spaces after commas (like
name1, name2), soline[1]will include a leading space (e.g.,name2instead ofname2). Neo4j treats these as distinct node names, creating separate nodes forname2andname2—that's why your graph looks like isolated pairs. - Incorrect
MERGEscope: Your original query merges the entire path(u)-[:connected_to]->(q)as a single unit. This works if you only want to create a relationship if the entire path doesn't exist, but it doesn't properly ensure shared nodes are reused (especially when whitespace messes up node names).
Correct Import Queries
First, your constraint is already set up correctly—great job there:
CREATE CONSTRAINT ON (u:User) ASSERT u.name IS UNIQUE
Now use one of these queries based on your needs:
Option 1: Single Relationship Per Node Pair (Deduplicate)
Use this if you only want one connected_to relationship between any two nodes, even if your CSV has duplicate rows:
USING PERIODIC COMMIT LOAD CSV FROM '${file}' AS line WITH line LIMIT 50000 // Clean up whitespace to ensure consistent node names WITH trim(line[0]) AS nameA, trim(line[1]) AS nameB // First, merge each node individually to ensure they're reused MERGE (u:User {name: nameA}) MERGE (q:User {name: nameB}) // Merge the relationship to avoid duplicates MERGE (u)-[:connected_to]->(q)
Option 2: Preserve All Relationships (Including Duplicates)
Use this if your CSV has valid duplicate rows that you want to represent as multiple relationships between the same nodes:
USING PERIODIC COMMIT LOAD CSV FROM '${file}' AS line WITH line LIMIT 50000 WITH trim(line[0]) AS nameA, trim(line[1]) AS nameB MERGE (u:User {name: nameA}) MERGE (q:User {name: nameB}) // Create a new relationship for every CSV row CREATE (u)-[:connected_to]->(q)
Why This Works
- The
trim()function removes leading/trailing spaces from each CSV field, ensuringname2andname2are treated as the same node. - Merging nodes individually guarantees that existing nodes are reused instead of creating new ones for every row.
- Separating node and relationship operations gives you control over whether you want deduplicated or multiple relationships.
Extra Tips
- If your CSV uses a different delimiter (like tabs), add
FIELDTERMINATOR '\t'to theLOAD CSVline. - Adjust the
PERIODIC COMMITbatch size (e.g.,USING PERIODIC COMMIT 10000) if you're importing extremely large files to optimize performance. - Test with a small subset first (reduce the
LIMITvalue) to verify nodes and relationships are created correctly before full import.
内容的提问来源于stack exchange,提问作者Traveling Tech Guy
相关产品推荐
相关产品推荐

