park
park

Reputation: 11

when delete document in another collection How to delete edge collection document together?

I am practicing arangodb in company. When I want to express the following relation between the user and the user, I want to delete the data of the corresponding following relation when one user is deleted.

user collection

{
    "_key": "test4",
    "_id": "users/test4",
    "_rev": "_V8yGRra---"
  },
  {
    "_key": "test2",
    "_id": "users/test2",
    "_rev": "_V8whISG---"
  },
  {
    "_key": "test1",
    "_id": "users/test1",
    "_rev": "_V8whFQa---"
  },
  {
    "_key": "test3",
    "_id": "users/test3",
    "_rev": "_V8yoFWO---",
    "userKey": "test3"
  }

follow collection[edge]

{
    "_key": "48754",
    "_id": "follow/48754",
    "_from": "users/test1",
    "_to": "users/test2",
    "_rev": "_V8wh4Xe---"
  }
  {
    "_key": "57447",
    "_id": "follow/57447",
    "_from": "users/test2",
    "_to": "users/test3",
    "_rev": "_V8yHGQq---"
  }

Upvotes: 1

Views: 402

Answers (2)

Maximilian Kernbach
Maximilian Kernbach

Reputation: 571

First you should create a graph with your vertex and edge collection. Working with graphs you can use the REST API to remove a vertex. This way all edges pointing to this vertex and the vertex itself get removed.

You can find the documentation including an example under https://docs.arangodb.com/3.11/develop/http/graphs/named-graphs/#remove-a-vertex

It is also possible to achieve this with an AQL query, for example deleting test1 from the users collection:

LET keys = (
  FOR v, e IN 1..1 ANY 'users/test1' GRAPH 'your-graph-name' RETURN e._key)
    LET r = (FOR key IN keys REMOVE key IN follow) REMOVE 'test1' IN users

A graph traversal is used to get _key attributes of all edges pointing to test1, then these edges are removed from the follow collection and test1 is removed from the users collection.

Upvotes: 0

peak
peak

Reputation: 116690

If used properly, the ArangoDB system ensures the integrity of named graphs (GRAPHs).

To delete a specific user (say "users/test4") and the corresponding edges in follow manually, an AQL query along the following lines should suffice to delete the edges:

for v,e IN 1..1 ANY "users/test4" follow
  REMOVE e IN follow
  COLLECT WITH COUNT INTO counter
  RETURN counter

Assuming "users/test4" is not referenced elsewhere, the node can then safely be deleted, e.g. by

 REMOVE "test4" in users

The important point here is that when manually deleting nodes, all the relevant edge collections must be identified and managed explicitly.

Upvotes: 1

Related Questions