Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding relationship to existing nodes with Cypher

Tags:

neo4j

cypher

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?

like image 731
Paul Grenyer Avatar asked Dec 08 '13 16:12

Paul Grenyer


People also ask

How do you create a relationship between existing nodes in Neo4j?

To create a relationship between two nodes, we first get the two nodes. Once the nodes are loaded, we simply create a relationship between them. The created relationship is returned by the query.

When you create a relationship in Cypher You must specify a direction True or false?

Syntax: Creating relationships When you create the relationship, it must have direction. You can query nodes for a relationship in either direction, but you must create the relationship with a direction.

Which clause is used to add new properties to an existing node or relationship?

SET clause is used to add new properties to an existing Node or Relationship.


1 Answers

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.

like image 162
Stefan Armbruster Avatar answered Oct 12 '22 02:10

Stefan Armbruster