sandor
sandor

Reputation: 671

Creating relationships between Neo4j nodes

I have nodes with two labels: Country and Continent.

Each country has a property called continent_code and I want to create a relationship between all the countries and their corresponding continent.

What I could achieve is only to create the relationships for a given continent like this:

MATCH (u:Country {continent_code:"NORAM"}), (a:Continent {code:"NORAM"})
MERGE (u)-[r:IS_COUNTRY_OF]->(a)
RETURN u, a, r  

Now what I would like to do is something more like this:

MATCH (u:Country {continent_code: a:Continent.code})
MERGE (u)-[r:IS_COUNTRY_OF]->(a)
RETURN u, a, r 

Obviously this is not working, but I have no idea how to fix it, I am not even sure if it is possible in Neo4j/cypher.

Thanks for your help!

Upvotes: 2

Views: 188

Answers (3)

stdob--
stdob--

Reputation: 29172

Simple combine MATCH and MERGE:

MATCH (u:Country) WHERE LENGTH(u.continent_code)>0
MERGE (a:Continent {code: u.continent_code})
MERGE (u)-[r:IS_COUNTRY_OF]->(a)
RETURN u,r,a

Upvotes: 2

cybersam
cybersam

Reputation: 66989

This might be what you want:

MATCH (u:Country)
WITH u.continent_code AS cc, COLLECT(u) AS countries
MERGE (a:Continent { code: cc })
FOREACH (c IN countries | MERGE (c)-[r:IS_COUNTRY_OF]->(a))
RETURN cc, countries;

It aggregates all the countries with the same continent code, uses MERGE to make sure the required Continent nodes exist, does a MERGE on each Country to make sure it has a relationship to its Continent, and returns each continent code with a collection of its countries.

Upvotes: 3

wwixon
wwixon

Reputation: 45

I think a simple search for the country and continent and creation of the relationship would work if I correctly understand your question. Your property(continent_code) on the Country node is not really needed with the relationship(IS_COUNTRY_OF) created between the Country and the Continent nodes.

MATCH (ctry:Country),(cont:Continent)
WHERE ctry.name = 'Some Country Name' AND cont.name = 'Some Cont Name'
CREATE (ctry)-[r:IS_COUNTRY_OF]->(cont)
RETURN ctry, r, cont

Upvotes: 0

Related Questions