cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Online training Creating Relationships. Got confused with Check your understanding (question 3)

Hi there. Got confused with question 3:

Assuming the nodes are successfully retrieved, how many relationships are created?
MATCH (a:Person), (m:Movie)
WHERE a.name = 'Tom Jones' AND m.title = 'Life is Wonderful'
CREATE (a)-[rel:ACTED_IN]->(m)
CREATE (a)-[rel:ACTED_IN {roles: ['The Villain']}]->(m)
CREATE (a)-[rel:ACTED_IN {roles: ['The Villain','Joe']}]->(m)

The right answer is 3. But when I ran the code I got error: Variable rel already declared (line 4, column 13 (offset: 132))
"CREATE (a)-[rel:ACTED_IN {roles: ['The Villain']}]->(m)"

So basically this code creates 0 relationships, not 3. Correct?

3 REPLIES 3

sam_gijare
Graph Buddy

If All the relationships are specified and is already retrieved then nothing needs to be created but this is conditional. If something is removed/deleted or detached then the entity that is removed/deleted/detached needs to be reattached or (created again and attached).

clem
Graph Steward

Variables are a bit tricky in Neo4J.

They get created when first referenced in CREATE or MATCH, so that they can be used later.

The problem (I'm guessing an oversight when creating the question), is that the second CREATE:

CREATE (a)-[rel:ACTED_IN {roles: ['The Villain']}]->(m)

is implicitly trying to create a new variable rel (as a ACTED_IN relationship type) when rel was already created in the previous CREATE statement. This is an error!

Since the variable rel is never referred to again in the query, the proper Cypher code for this question is:

MATCH (a:Person), (m:Movie)
WHERE a.name = 'Tom Jones' AND m.title = 'Life is Wonderful'
CREATE (a)-[:ACTED_IN]->(m)  // you could use rel one time here: CREATE (a)-[rel:ACTED_IN]->(m) 
CREATE (a)-[:ACTED_IN {roles: ['The Villain']}]->(m) // Don't use rel again!
CREATE (a)-[:ACTED_IN {roles: ['The Villain','Joe']}]->(m)

In which case, the answer of 3 is correct.

So, this is an error in the question. Do you have the URL?

(And good for you, for actually trying to query!)

[added]
This is another possibility is to use three different rel variables (which could be used later elsewhere but aren't in this query):

MATCH (a:Person), (m:Movie)
WHERE a.name = 'Tom Jones' AND m.title = 'Life is Wonderful'
CREATE (a)-[rel1:ACTED_IN]->(m)
CREATE (a)-[rel2:ACTED_IN {roles: ['The Villain']}]->(m)
CREATE (a)-[rel3:ACTED_IN {roles: ['The Villain','Joe']}]->(m)

Good catch @sam_gijare !

I will update the question based upon @clem 's suggestion.

Elaine