在COLLECT中使用INTO,同时还要使用AGGREGATE。能做到吗

时间:2019-07-12 21:25:28

标签: arangodb

我正在使用的文档的形状类似于此:

{
 "survey_id": 123,
  "numerical_answers": [
    {
      "component_id": 345,
      "number": 5,
    },
    {
      "component_id": 346,
      "number": 5,
    }
  ]
}

ArangoDB的输出应如下所示:

[
  {
    "component_id": 345,
    "distribution": [
      {
        "component_id": 345,
        "score": null,
        "total": 42
      },
      {
        "component_id": 345,
        "score": 1,
        "total": 76
      },
      {
        "component_id": 345,
        "score": 2,
        "total": 37
      },
      {
        "component_id": 345,
        "score": 3,
        "total": 40
      },
      {
        "component_id": 345,
        "score": 4,
        "total": 93
      },
      {
        "component_id": 345,
        "score": 5,
        "total": 212
      }
    ],
    "total": 500,
    "avg": 3.404
  }
]

我的AQL如下:

FOR doc IN @@collection
  FILTER doc.`survey_id` == @survey_id

  LET componentScoreGroup = {
    component_id: @component_id,
    score: FIRST(doc.numerical_answers[* filter CURRENT.component_id == @component_id return CURRENT.number])
  }

  COLLECT component_id = componentScoreGroup.component_id, score = componentScoreGroup.score WITH COUNT INTO total

  LET distribution = {
    component_id: component_id,
    score: score,
    total: total
  }

  COLLECT component_id2 = distribution.component_id into groups keep distribution

  LET finalTotal = sum(groups[*].distribution.total), 
      summedScore = sum(groups[* return CURRENT.distribution.score * CURRENT.distribution.total])

  RETURN {
    component_id: component_id2,
    distribution: groups[*].distribution,
    total: finalTotal,
    avg: summedScore / finalTotal
  }

我想在AGGREGATE中使用性能更高的COLLECT语法,但是我不确定是否可以,因为我也想在最终的返回结果中插入distribution的内容

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

这更接近您要寻找的东西吗?

FOR doc IN @@collection
  FILTER doc.survey_id == @survey_id

     LET componentScoreGroup = {
          component_id: @component_id,
          score: FIRST(doc.numerical_answers[* filter CURRENT.component_id == @component_id return CURRENT.number])
        }

    COLLECT id = componentScoreGroup.component_id
    AGGREGATE avg = AVG(componentScoreGroup.score),
              total = SUM(componentScoreGroup.score)
    INTO group
    return { "id" : id , "avg" : avg , "total" : total, "number" : LENGTH(group), "group" : group}