使用AQL进行图形查询

时间:2018-06-05 22:14:59

标签: graph arangodb aql

我有3个集合,第一个是列表(顶点),第二个是用户(顶点),第三个是活动(边缘)。我计划在活动集合的列表中存储任何类型的活动(例如like,comment,flag等)。 假设我需要获取任何用户的所有列表以及他创建的每个列表上的每个事件的计数,例如在单个查询中的每个列表上没有像like,comments,flag。我怎么做? 我一直在探索arangodb文档2天,但无法弄清楚如何编写这样的查询。 enter image description here

1 个答案:

答案 0 :(得分:1)

如果每个单独的活动都表示为两个顶点集合之间的边缘,那么找到一个用户,检索它的邻居(列表顶点)并按类型对边缘进行分组(边缘属性?):

FOR u IN users
  FILTER u._key == "john"
  FOR v, e IN 1..1 OUTBOUND u activities
    // v is a list vertex document
    // e is an activity edge document
    COLLECT list = v._id, type = e.type, user = u._id
    WITH COUNT INTO count
    RETURN { list, user, type, count }

我的测试数据的结果:

list        | user       | type    | count
------------|------------|---------|------
lists/john1 | users/john | comment | 1
lists/john1 | users/john | modify  | 3
lists/john1 | users/john | vote    | 1
lists/john2 | users/john | delete  | 1
lists/john2 | users/john | like    | 1
lists/john2 | users/john | modify  | 2
lists/john2 | users/john | vote    | 2

如果要保留列表和用户文档,可以执行以下操作:

FOR u IN users
  FILTER u._key == "john"
  FOR v, e IN 1..1 OUTBOUND u activities
    COLLECT list = v._id, type = e.type
    AGGREGATE count = LENGTH(1) INTO groups
    RETURN {
        list: groups[0].v,
        user: groups[0].u,
        type,
        count
    }

对于大量数据,以下内容可能会占用较少的内存,因为它可以避免跟踪组并查找必要的文档:

FOR u IN users
  FILTER u._key == "john"
  FOR v, e IN 1..1 OUTBOUND u activities
    COLLECT list_id = v._id, user_id = u._id, type = e.type
    WITH COUNT INTO count
    RETURN {
        list: DOCUMENT(list_id),
        user: DOCUMENT(user_id),
        type,
        count
    }