I am trying to remove leaf nodes in Neo4j, but only those with a single incoming relationship. (I'm so close.)
I have a query that returns the exact node I wish to remove. However, when I replace the RETURN with DELETE, it removes more than the query returns. Here's the complete sequence:
neo4j-sh (?)$ match (n)-[r]->(p) return n, r, p ;
+------------------------------------------------------------+
| n | r | p |
+------------------------------------------------------------+
| Node[2164]{name:"a"} | :has[2616]{} | Node[2165]{name:"b"} |
| Node[2164]{name:"a"} | :has[2617]{} | Node[2166]{name:"c"} |
| Node[2166]{name:"c"} | :has[2619]{} | Node[2168]{name:"e"} |
| Node[2167]{name:"d"} | :has[2618]{} | Node[2165]{name:"b"} |
+------------------------------------------------------------+
This query is perfect:
neo4j-sh (?)$ match ()-[r:has]->(n)
> with n,count(r) as rel_cnt
> where rel_cnt = 1 and NOT (n)-->()
> return n.name, rel_cnt;
+------------------+
| n.name | rel_cnt |
+------------------+
| "e" | 1 |
+------------------+
But this delete removed 2 nodes and 3 relationships?
neo4j-sh (?)$ match ()-[r:has]->(n)
> with n, r, count(r) as rel_cnt
> where rel_cnt = 1 and NOT (n)-->()
> delete n, r;
+-------------------+
| No data returned. |
+-------------------+
Nodes deleted: 2
Relationships deleted: 3
This is all that's left
neo4j-sh (?)$ match (n)-[r]->(p) return n, r, p ;
+------------------------------------------------------------+
| n | r | p |
+------------------------------------------------------------+
| Node[2164]{name:"a"} | :has[2617]{} | Node[2166]{name:"c"} |
+------------------------------------------------------------+
neo4j-sh (?)$ match (n) return n;
+----------------------+
| n |
+----------------------+
| Node[2169]{name:"a"} |
| Node[2171]{name:"c"} |
| Node[2172]{name:"d"} |
+----------------------+
Why was node 'b' removed? It didn't show in the query results.