Question

please i can't check and create a node plus a relationship to pre-existing node.

i need to check if node pre-existing in my Neo4j database and create a node plus relationship to this node.

Thank you

Was it helpful?

Solution 2

Check out the py2neo docs for the Cypher support and use just a merge query like this:

MERGE (user:User {name:"John"}) // get-or-crate
MERGE (friend:User {name:"Jane"}) // create friend
MERGE (user)-[r:KNOWS]->(friend) // create relationship
RETURN user,r,friend

OTHER TIPS

Here's how you'd merge existing data with data that you create on the fly using Cypher 2.0, the native language to Neo4j:

MERGE ({ name: "Jane" })-[r:KNOWS]->({ name: "John" })

In fact none of these data need pre-exist. It will all be created on the fly, relationships and all. However there's not much checking going on, and if you make a small mistake, it's easy to create duplicate entries this way. Thus it's good practice to check things beforehand.

Here's how you'd use Cypher to check whether a node already exists:

MATCH (n:SomeNode {some_field: "some_discrete_data"}) RETURN n;

In your case it would probably be something like:

MATCH (n {id: 1}) RETURN n;

If there is a node with a field containing the data you need (in this case I've assumed it is {id: 1}, but you might of course want something else), it will be returned. And if not, it will return 0 nodes.

Warning: If you do not describe the data you need, i.e. {id: 1}, all the nodes in the database will be returned, and you might not want that.

However you can't make a relationship with just one node. You need at least two nodes to create a relationship between them. So we'll create another:

CREATE (:OtherNode {id: 2});

To make a relationship with this new node to the pre-existing one, you need to find them with MATCH, and then create the relationship. Here's an example:

MATCH (node1 {id: 1}), (node2 {id: 2})
CREATE (node1)<-[:LIKES]-(node2);

The <- denotes that node2 will have a directional relationship to the already pre-existing node1.

However you can do this process in just one step; that is check if a node already exists, and add a new node plus relationship between the new and the pre-existing node all at the same time! You can do this with the UNIQUE keyword:

MATCH (node1 {id: 1})
CREATE UNIQUE (node1)<-[:LIKES]-(node2 {id: 2});

As long as node1 already exists, node2 and its relationship to node1 will be created if they don't already exist. However if node1 doesn't exist, nothing will happen. IMHO that's a nice safety feature if you want to avoid duplicates.

As for the Python-spesific API, you'd have to check the documentation for the language driver relevant to the programming language you use. Most drivers accept Cypher in some form or another. Here's the relevant part regarding Python: http://book.py2neo.org/en/latest/cypher/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top