简体   繁体   中英

Ensuring data integrity with 1:n connections in arangodb (delete orphan vertex automatically)

Say I have a users document group and another document group sessionTokens that store the session the users have. Each user can have multiple tokens but a token can only belong to one user. The association is done through edges.

Now if I use graph functions I can delete a token and the edge between the user and the token gets deleted automatically, and that is great. But what if I want to make sure that if a user is deleted, I want all their session tokens (vertices) to be deleted automatically as well (or else they will be orphan tokens)? Do I have to handle this in application code? Or is there a declarative way to ensure this type of integrity?

According to the docs ,

Deleting vertices with associated edges is currently not handled via AQL while the graph management interface and the REST API for the graph module offer a vertex deletion functionality.

That said, there are ways to cheat the system, somewhat. For instance, you can modify several collections at once. Therefore, you could collect the _key values for all the nodes and edges related to the vertex you're removing, then remove each of those in turn.

FOR u IN users
    FOR v,e IN 1 INBOUND u users_sessionTokens
        COLLECT del_users = u._key, del_edges = e._key, del_sessionTokens = v._key
        LET vx = (
            FOR d IN del_sessionTokens
                REMOVE d IN sessionTokens
        )
        LET ex = (
            FOR d IN del_edges
                REMOVE d IN users_sessionTokens
        )
        LET ux = (
            FOR d IN del_users
                REMOVE d IN users
        )

It's not necessarily the best implementation, but might work well wrapped in a transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM