Search code examples
arangodbaql

Many to many AQL query


I have 2 collections and one edge collection. USERS, FILES and FILES_USERS. Im trying to get all FILES documents, that has the field "what" set to "video", for a specific user, but also embed another document, also from the collection FILES, but where the "what" is set to "trailer" and belongs to the "video" into the results.

I have tried the below code but its not working correctly, im getting a lot of duplicate results...its a mess. Im definitely doing it wrong.

 FOR f IN files
 FILTER f.what=="video"

 LET trailer = (
    FOR f2 IN files
      FILTER f2.parent_key==f._key
      AND f2.what=="trailer"
      RETURN f2
   )


  FOR x IN files_users
    FILTER x._from=="users/18418062"
    AND x.owner==true
    RETURN DISTINCT {f,trailer}

Solution

  • There may be a better way to do this with graph query syntax, but try this. Adjust the UNIQUE functions based on your data-model.

    LET user_files = UNIQUE(FOR u IN FILES_USERS 
                             FILTER u._from == "users/18418062" AND u.owner 
                             RETURN u._to)
    
    FOR uf IN user_files
     FOR f IN files 
     FILTER f._key == uf AND f.what == "video"
    
     LET trailers = UNIQUE(FOR t IN files 
                            FILTER t.parent_key == f._key AND t.what == "trailer" 
                            RETURN t)
    
    RETURN {"video": f, "trailers": trailers}