I have a requirement that in my database some nodes should have at most one relationship of a given type. For example, nodes with the label Heart should be connected via has to at most one node of label Body.
With the following query I can find all nodes with connections which don't respect this rule:
MATCH (n:Heart) WHERE (:Body)-[:has]-(n)-[:has]-(:Body) RETURN n
I'd like though, to write a statement to remove the "extra" relationships. Right now I've got a query to remove the nodes composing these "extra" relationships, but it also removes the nodes I'd like to keep (one of each).
MATCH (b1:Body)-[:has]-(n)-[:has]-(b2:Body) DETACH DELETE b1, b2
This also doesn't group relationships by the center node, so I can't really remove all nodes except one, as it would not have the desired effect.
Does anyone know how can I write a statement that will remove all "extra" relationships until only one relationship has remains for each Heart node? Preferably the oldest one.
IF (and this is a big if) I'm understanding this correctly, you don't want a zebra heart attached to an elephant body. If that's the case, then I think something like this might work...
MATCH (b1:Body)-[:has]-(h:Heart)-[:has]-(b2:Body)
WHERE b1.animal <> b2.animal
return n
This should provide a resultset where the animal properties of the 2 attached bodies are not equal.