Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

neo4j - Adding relationship to existing nodes with 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...