dgraph-io/dgraph · error

Invalid variable aggregation. Check the levels.

Error message

Invalid variable aggregation. Check the levels.

What it means

During variable aggregation (math/aggregation over value variables), Dgraph must find the sibling subgraph that carries the variable needed for aggregation. If no sibling subgraph matching the needed variable exists, the aggregation level is invalid and this error is thrown. It indicates the variable referenced in an aggregation was not produced at a compatible level of the query graph.

Source

Thrown at query/query.go:1099

	var relSG *SubGraph
	for _, ch := range parent.Children {
		if sg == ch {
			continue
		}
		for _, v := range ch.Params.FacetVar {
			if v == needsVar {
				relSG = ch
			}
		}
		for _, cch := range ch.Children {
			// Find the sibling node whose child has the required variable.
			if cch.Params.Var == needsVar {
				relSG = ch
			}
		}
	}
	if relSG == nil {
		return nil, errors.Errorf("Invalid variable aggregation. Check the levels.")
	}

	vals := doneVars[needsVar].Vals
	mp = types.NewShardedMap()
	// Go over the sibling node and aggregate.
	for i, list := range relSG.uidMatrix {
		ag := aggregator{
			name: sg.SrcFunc.Name,
		}
		for _, uid := range list.Uids {
			if val, ok := vals.Get(uid); ok {
				if err := ag.Apply(val); err != nil {
					return nil, errors.Errorf("Error in applying aggregation %s", err)
				}
			}
		}
		v, err := ag.Value()
		if err != nil && err != ErrEmptyVal {

View on GitHub (pinned to 759e242be6)

Solutions

  1. Verify the variable is defined with 'as var' or 'as val' at the same level the aggregation consumes it
  2. Check for typos in the variable name
  3. Restructure the query so the aggregation's sibling node emits the needed variable
  4. Run the query without aggregation first to confirm the variable is populated

Example fix

// before
{
  me(func: eq(name, "a")) {
    friend { u as count(uid) }
    total as sum(val(friend))  # no such val(friend) at this level
  }
}
// after
{
  me(func: eq(name, "a")) {
    friend as friend_of { c as count(uid) }
    total as sum(val(c))
  }
}
Defensive patterns

Strategy: validation

Validate before calling

// Ensure every val(x) consumer has a matching 'as x' emitter in the query text
for _, agg := range []string{"val(a)", "val(t)"} {
    name := strings.TrimSuffix(strings.TrimPrefix(agg, "val("), ")")
    if !strings.Contains(query, "as "+name) && !strings.Contains(query, "var("+name+" as") {
        return fmt.Errorf("variable %s used in aggregation but never defined", name)
    }
}

Try / catch

if err != nil && strings.Contains(err.Error(), "Invalid variable aggregation") {
    return fmt.Errorf("query uses a variable that is not defined at the right level: %w", err)
}

Prevention

When it happens

Trigger: Using sum/min/max/avg over a variable whose name does not match any sibling node's Var (e.g. 'sum(val(x))' where x was never emitted as a variable at the right level); mismatched variable scoping inside nested filters or math blocks.

Common situations: Typo in variable name between emitter (as x) and consumer (val(x)); aggregating a variable defined only in a nested branch; copying a query fragment without the sibling node that defines the variable.

Related errors


AI-assisted analysis of dgraph-io/dgraph@759e242be6 (2026-09-01). Data as JSON: /api/errors/ca339da3e0af7cf7. Report an issue: GitHub.