cancel
Showing results for 
Search instead for 
Did you mean: 

How to Create a Relationship to a Single node?

mochalla
Node Clone

Hi, Using Cypher Query, may I know to create a relationship like in the image below while importing csv?

mochalla_0-1663667666083.png

 

1 ACCEPTED SOLUTION

LOAD CSV WITH HEADERS FROM 'file:///distance.csv' AS row FIELDTERMINATOR ','
MERGE (a:Country {name: row.`Country 1`}) 
MERGE (b:Country {name: row.`Country 2`}) 
MERGE (a)-[r:HAS_DISTANCE]->(b) 
SET r.distance = row.`Distance (km)`

View solution in original post

10 REPLIES 10

mrksph
Node Clone

Hi @mochalla ,

If you want to create a relationship starting and ending in the same node you could do something like this:

MATCH (n:Node {id: "1"})
CREATE (n)-[:RELANTIONSHIP]->(n)

Note: you should use your own property on Node. You should also change the relationship name to a more according one. 

Regards

mochalla
Node Clone

For Example If my node label is Airport
And I have distance from one airport to another airport.
Now I want to show this in the format I mentioned

LOAD CSV WITH HEADERS FROM '///filename.csv' AS row

WITH row

MATCH (a:airport {name:row.`Airport Name```)
CREATE (a)-[:DISTANCE]->(a)

What error do you see?

I see no changes and no records.

mochalla
Node Clone

Here is the example data I am sharing.
In the node all the countries are included. Now I want to connect the distance of each country with the relationship. I don't want to create two nodes here.

Example Data

Untitled graph (3).png

// Create relationships
LOAD CSV WITH HEADERS FROM '///filename.csv' AS row
WITH row
MATCH (c:Country{name: row.`Country 1`})
MATCH (c:Country{name: row.`Country 2`})
CREATE (c)-[cc:DISTANCE]->(c)
SET cc.name = row.`Distance (km)`
RETURN row;

LOAD CSV WITH HEADERS FROM 'file:///distance.csv' AS row FIELDTERMINATOR ','
MERGE (a:Country {name: row.`Country 1`}) 
MERGE (b:Country {name: row.`Country 2`}) 
MERGE (a)-[r:HAS_DISTANCE]->(b) 
SET r.distance = row.`Distance (km)`

Getting this error
Invalid input 'r': expected whitespace, '.', node labels or rel types, '[', '^', '*', '/', '%', '+', '-', "=~", IN, STARTS, ENDS, CONTAINS, IS, '=', "<>", "!=", '<', '>', "<=", ">=", AND, XOR, OR or AS (line 2, column 198 (offset: 221))
"LOAD CSV WITH HEADERS FROM ''file:///distance.csv''row FIELDTERMINATOR ','"
^

I tested the query with your data and it works on my side.

Can you show your query?

MERGE (a:Country {name: row.`Country 1`}) 
MERGE (b:Country {name: row.`Country 2`}) 
MERGE (a)-[r:HAS_DISTANCE]->(b) 
SET r.distance = row.`Distance (km)`
It worked now. I tried with other data, it was showing the error I mentioned. But this worked wit the example data. Will try to figure it out. Thanks a lot.

Read all the details here to check if you have the right configuration to import files remotely.