0
votes

Using py2neo v4 to connect to my Neo4j database and I can't delete nodes via py2neo running a query that works fine in Cypher in the browser. Of course there is no real documentation for either Neo4j or py2neo, so hopefully I can get some help here. There are similar questions, but both Neo4j and py2neo have new versions since then, and those questions/answers are either for other specific cases or are obsolete methods.

First, I define this function:

def deleteNode(thisNodeID):
    graph.run("MATCH (n) where id(n) = $nodeID DETACH DELETE n", 
     parameters={"nodeID":thisNodeID})

Then I call the function like:

badObjectIDs = [268569,268535,268534]
for badID in badObjectIDs:
    deleteNode(badID)

This runs without any trouble, but doesn't delete anything and the nodes with those IDs are still in the database when I search via the browser.

I also tried using py2neo's graph.delete() method, but again I wasn't able to get anything to work because there is no description or examples in the documentation to get it to work. I couldn't even find a way to get nodes by IDs in the documentation. Somthing like

graph.delete(matcher.match("Person"))

should delete all the nodes with the "Person" label, but instead it throws an error

TypeError: No method defined to delete object <py2neo.matching.NodeMatch object at 0x0000026F52A8DC50>

So it's really just a basic question in using py2neo that should be explained clearly in the documentation or beginner tutorials, but again, there are no examples of using any of these methods anywhere I could find.

How do I remove nodes from my Neo4j database using py2neo?

2
NodeMatch is a collection of Node objects. You can't delete the collection, you'll need to iterate it and delete them individually.h0r53

2 Answers

0
votes

I was able to delete a node, with ID=20 like this:

from py2neo import Graph, Node, Relationship

# Create graph
graph = Graph(host="localhost", auth=("neo4j", <insert_password>))

# Create nodes
nicole = Node('Person', name='Nicole')
adam = Node('Person', name='Adam')

# Create relationship between 2 nodes
graph.create(Relationship(nicole, 'KNOWS', adam))

# Select node with id = 20
id_20 = graph.evaluate("MATCH (n) where id(n) = 20 RETURN n")

# Delete node
graph.delete(id_20)

As for the function, it should work with something like this:

def deleteNode(id):
    node = graph.evaluate("MATCH (n) where id(n) = {} RETURN n".format(id))
    graph.delete(node)

You can yield the id of any node IN THE GRAPH by doing this:

node = graph.evaluate("MATCH (n) where id(n) = {} RETURN n".format(id))
node.identity

Just to be clear, I'm using neo4j-driver version 1.6.2

0
votes

You have to .commit()

tx = graph.begin()
matcher = NodeMatcher(graph)
node = matcher.get(node_id)
tx.delete(node)
tx.commit()