Have both an alias and a variable?

Very simply, if I have a query that does an operation (like sum), is there a way to both return that value, but also save as a variable for later use?

Right now I have the following:

payments(func: has(paymentType)) @normalize  {
    name : name
    ~paymentType @filter(uid(payments)) {
      payment as amount
    }
    paymentsTotal: sum(val(payment))
    pt as sum(val(payment))
  }

  totals() {
    paymentsTotal: sum(val(pt))
  }

That works fine, (I get payments by paymentType, and also a total of all payments together) but what bothers me is the repetition of (sum(val(payment)). Is there a way to only call that once? Sometime like:

pt AS paymentsTotal: sum(val(pt))

Though that obviously doesn’t work.

Hi!

Not sure what bothers you from what you wrote. Each query block will iterate the set of nodes and compute the sum as provided. That is, pt as sum(val(payment)) will be closely linked to a nodes context. That’s why they repeat. It’s an aggregation behavior. The aggregation docs explains this.

As I explained above, only if you have only one Node as parent. or using the aggregation block for this.

Btw you could make the payments block as “var” instead a query block. Seems to me you just need the sum of amount.

Actually the docs show the syntax for this.

https://docs.dgraph.io/query-language/#alias

  • aliasName : varName as ...

paymentsTotal : pt as sum(val(pt))

But I feel like something is missing. Because I didn’t understand what the issue is.

1 Like

Hey Michel

You managed to both provide with the solution I came up with:

Btw you could make the payments block as “var” instead a query block. Seems to me you just need the sum of amount.

But also directly answer my question:

Actually the docs show the syntax for this.

https://docs.dgraph.io/query-language/#alias

  • aliasName : varName as ...

paymentsTotal : pt as sum(val(pt))

Which is exactly the answer I was looking for. The answer was right there in the docs, but I didn’t know where to look yet. A big part of this process is learning how to think, and what to ask. Thanks for your help!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.