Adding relationship to existing nodes with Cypher

Paul Grenyer picture Paul Grenyer · Dec 8, 2013 · Viewed 61.5k times · Source

I'm trying out Neo4j for the first time. I'm using the 2.0-RC1 community edition.

I've created some nodes:

MERGE (u:User{username:'admin',password:'admin'})
MERGE (r1:Role{name:'ROLE_ADMIN'})
MERGE (r2:Role{name:'ROLE_WEB_USER'})
MERGE (r3:Role{name:'ROLE_REST_USER'})

and now I want to add relationships between the nodes. However, I don't want to clear out the existing database created with the script above, add the statements and run it again. I want to add relationships to the existing nodes. Google helped me find this:

START n=node(*), m=node(*)  
where has(n.username) and has(m.name) and n.username = 'admin' 
and m.name = 'ROLE_WEB_USER' 
create (n)-[:HAS_ROLE]->(m)

Which works fine (even though I don't understand all the syntax). However, I am aware that this finds any node with a username property and any node with a name property, instead of using labels to check that it has the right type of node.

How can I do the same using labels?

Answer

Stefan Armbruster picture Stefan Armbruster · Dec 8, 2013

In Neo4j 2.0 you can create schema indexes for your labels and the properties you use for lookup:

CREATE INDEX ON :User(username)
CREATE INDEX ON :Role(name)

To create relationships you might use:

MATCH (u:User {username:'admin'}), (r:Role {name:'ROLE_WEB_USER'})
CREATE (u)-[:HAS_ROLE]->(r)

The MATCH will use an index if possible. If there is no index, it will lookup up all nodes carrying the label and see if the property matches.

N.B. the syntax above will only work with Neo4j 2.0.0-RC1 and above.