简体   繁体   中英

Can't delete neo4j nodes with a relationship using py2neo

I'm learning neo4j through the py2neo module. Modifying the example , I'm confused on why I'm getting an error here. If I want to delete all nodes of the Person type, why can I not iterate through the graph and remove the ones that match my criteria? If the relationship between the nodes is removed, the code runs fine.

from py2neo import Node, Relationship, Graph

g = Graph("http://neo4j:test@localhost:7474/db/data/")
g.delete_all()

alice = Node("Person", name="Alice")
bob   = Node("Person", name="Bob")
g.create(Relationship(alice, "KNOWS", bob)) # Works if this is not present

for x in g.find("Person"):
    print x
    g.delete(x)

This fails with the error:

  File "start.py", line 12, in <module>
    g.delete(x)
  ...
py2neo.error.TransactionFailureException: Transaction was marked as successful, but unable to commit transaction so rolled back.

You need to first delete the relationships before deleting nodes.

This is the standard behavior in Neo4j and prevents orphan relationships.

You can do this by issuing a Cypher query :

graph.cypher.execute("MATCH (n:Person) OPTIONAL MATCH (n)-[r]-() DELETE r,n")

or (but not 100% sure you can without knowing the rel types and end nodes) with py2neo Store :

    store = Store(g)
    rels = store.load_related(alice)
    for r in rels
    g.delete(r)

    g.delete(alice)

The normal script for store load_related is :

store.load_related(alice, "LIKES", Person)

Per the documentation this should work as a simple CYPER query:

When you want to delete a node and any relationship going to or from it, use DETACH DELETE.

MATCH (n:Person)
DETACH DELETE n

http://neo4j.com/docs/stable/query-delete.html#delete-delete-a-node-with-all-its-relationships

i think this question has been completely resolved with py2neo version 3.

see manual: http://py2neo.org/v3/database.html#the-graph

where you can run the delete method on entire subgraphs (incl nodes).

It works nicely for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM