ArangoDB - 如何获得两个集合之间的关系

ArangoDB - How to get relations between 2 collections

我有 2 个顶点集合:

和 1 个边缘集合:

问题是当用户关注其他用户时,被关注的用户写了一些文章,如何根据用户关注获取文章?

您可以使用 db._query() 在 Foxx 中使用 AQL 的原生图遍历查询数据。

示例数据

用户:

{ "_key": "john-s", "gender": "m", "name": "John Smith" }

{ "_key": "jane.doe", "gender": "f", "name": "Jane Doe",
  "article_ids": [
    "salad-every-day",
    "great-aql-queries"
  ]
}

文章:

{
  "_key": "great-aql-queries",
  "title": "How to write great AQL queries"
},
{
  "_key": "salad-every-day",
  "title": "Delicious salads for every day"
}

用户关注:

{ "_from": "users/john-s", "_to": "users/jane.doe" }

查询

从关注者 John 开始,我们可以使用 AQL traversal 获取他关注的所有用户。这里只有简被关注:

FOR v IN OUTBOUND "users/john-s" userfollow
    RETURN v

Jane 撰写的文章的文档键存储在 Jane 用户文档本身中,作为一个字符串数组(当然你也可以用边来建模)。我们可以使用 DOCUMENT() 来获取文章和 return 它们:

FOR v IN OUTBOUND "users/john-s" userfollow
    RETURN DOCUMENT("articles", v.article_ids)

我们还可以 return John 关注的人 (Jane),删除每个用户的 article_ids 属性并合并到完整的文章文档中:

FOR v IN OUTBOUND "users/john-s" userfollow
    RETURN MERGE(UNSET(v, "article_ids"), {
        articles: DOCUMENT("articles", v.article_ids)
    })

结果如下所示:

[
  {
    "_id": "users/jane.doe",
    "_key": "jane.doe",
    "gender": "f",
    "name": "Jane Doe",
    "articles": [
      {
        "_key": "salad-every-day",
        "_id": "articles/salad-every-day",
        "title": "Delicious salads for every day"
      },
      {
        "_key": "great-aql-queries",
        "_id": "articles/great-aql-queries",
        "title": "How to write great AQL queries"
      }
    ]
  }
]