Search code examples
collectionsarangodbaqlnosql

How to remove collection or edge document using for loop in ArangoDB?


I'm using the latest ArangoDB 3.1 on Windows 10.

Here I want to remove the collection document and edge document using the for loop. But I'm getting an error like document not found (vName).

vName contains the many collection names. But I dunno how to use it in for loop.

This is the AQL I am using to remove the documents from the graph:

LET op = (FOR v, e IN 1..1 ANY 'User/588751454' GRAPH 'my_graph'
  COLLECT vid = v._id, eid = e._id
  RETURN { vid, eid }
)

FOR doc IN op
  COLLECT vName = SPLIT(doc.vid,'/')[0],
            vid = SPLIT(doc.vid,'/')[1],
          eName = SPLIT(doc.eid,'/')[0],
            eid = SPLIT(doc.eid,'/')[1]
  REMOVE { _key: vid } in vName

Return output im getting from the AQL (Web UI screenshot)


Solution

  • vName is a variable introduced by COLLECT. It is a string with the collection name of a vertex (extracted from vid / v._id). You then try to use it in the removal operation REMOVE { ... } IN vName.

    AQL does not support dynamic collection names however, collection names must be known at query compile time:

    Each REMOVE operation is restricted to a single collection, and the collection name must not be dynamic.

    Source: https://docs.arangodb.com/3.11/aql/high-level-operations/remove/

    So, you either have to hardcode the collection into the query, e.g. REMOVE { ... } IN User, or use the special bind parameter syntax for collections, e.g. REMOVE { ... } IN @@coll and bind parameters: {"@coll": "User", ...}.

    This also means that REMOVE can only delete documents in a single collection.

    It's possible to workaround the limitation somewhat by using subqueries like this:

    LET x1 = (FOR doc IN User REMOVE aa IN User)
    LET x2 = (FOR doc IN relations REMOVE bb IN relations)
    RETURN 1
    

    The variables x1 and x2 are syntactically required and receive an empty array as subquery result. The query also requires a RETURN statement, even if we don't expect any result.

    Do not attempt to remove from the same collection twice in the same query though, as it would raise a access after data-modification error.