1

In Neo4j, using Cypher, I want to run the below query for numbers 1 through 14 (i.e., quantity1 to quantity14):

LOAD CSV WITH HEADERS FROM '<path>' AS row 
WITH row WHERE row.quantity1 IS NOT NULL
MATCH (m:main {main_id: row.main}) 
MERGE (q:quantity {quantity : row.quantity1}) 
MERGE (m)-[:main_has_quantity]->(q);

What the command does: The command reads a CSV, creates the quantity node (if it is not null and if it doesn't already exist) and then creates a relationship between the quantity node and it's corresponding main node. I want to do this for columns quantity1 through quantity14 in the CSV.

I tried to use UNWIND and FOREACH but both commands throw errors:

LOAD CSV WITH HEADERS FROM '<path>' AS row 
UNWIND range(1,14) as i
WITH row WHERE row.quantity+toString(i) IS NOT NULL 
MATCH (m:main {main_id: row.main}) 
MERGE (q:quantity {quantity : row.quantity+toString(i)}) 
MERGE (m)-[:main_has_quantity]->(q);

I got the error:

Variable i not defined (line 5, column 37 (offset: 246)) "MERGE (q:quantity {quantity : row.quantity+toString(i)})"

I used FOREACH in place of UNWIND but that did not work because I cannot use WITH clause inside FOREACH.

How best to achieve the result I am looking for?

P.S. I am using the Neo4j community version.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
kumarais
  • 11
  • 1

1 Answers1

0

I think you need to use squarw brackets here to be able to select dynamic properties

LOAD CSV WITH HEADERS FROM '<path>' AS row 
UNWIND range(1,14) as i
WITH row WHERE row['quantity'+toString(i)] IS NOT NULL 
MATCH (m:main {main_id: row.main}) 
MERGE (q:quantity {quantity : row['quantity'+toString(i)]}) 
MERGE (m)-[:main_has_quantity]->(q);
Tomaž Bratanič
  • 6,319
  • 2
  • 18
  • 31