dgraph-io/dgraph · error

Expected ( after math

Error message

Expected ( after math

What it means

The DQL parser found the 'math' keyword but the next lexer item was not '('. parseMathFunc requires math to be immediately followed by an opening parenthesis; anything else (space-separated token, brace, comma) fails parsing.

Source

Thrown at dql/math.go:164

}

func isMathFunc(f string) bool {
	// While adding an op, also add it to the corresponding function type.
	return f == "*" || f == "%" || f == "+" || f == "-" || f == "/" ||
		f == "exp" || f == "ln" || f == "cond" ||
		f == "<" || f == ">" || f == ">=" || f == "<=" ||
		f == "==" || f == "!=" ||
		f == "min" || f == "max" || f == "sqrt" ||
		f == "pow" || f == "logbase" || f == "floor" || f == "ceil" ||
		f == "since" || f == "dot"
}

func parseMathFunc(gq *GraphQuery, it *lex.ItemIterator, again bool) (*MathTree, bool, error) {
	if !again {
		it.Next()
		item := it.Item()
		if item.Typ != itemLeftRound {
			return nil, false, errors.Errorf("Expected ( after math")
		}
	}

	// opStack is used to collect the operators in right order.
	opStack := new(mathTreeStack)
	opStack.push(&MathTree{Fn: "("}) // Push ( onto operator stack.
	// valueStack is used to collect the values.
	valueStack := new(mathTreeStack)

loop:
	for it.Next() {
		item := it.Item()
		lval := strings.ToLower(item.Val)
		switch {
		case isMathFunc(lval):
			op := lval
			it.Prev()
			lastItem := it.Item()

View on GitHub (pinned to 759e242be6)

Solutions

  1. Wrap the expression in parentheses directly after math: math(a + b).
  2. Remove any characters between 'math' and '('.
  3. Check the aggregation block syntax: `total as math(count + 1)` inside a query.
  4. Validate the query with a minimal example first, then add complexity.

Example fix

// before
total as math count + 1
// after
total as math(count + 1)
Defensive patterns

Strategy: validation

Validate before calling

// 'math' must be immediately followed by '('
const re = /\bmath\s*\(/;
if (!re.test('total as math(count + 1)')) {
  throw new Error('math must be invoked as math(expression)');
}

Try / catch

try {
  return await dgraph.query(query);
} catch (err) {
  if (/Expected \( after math/.test(String(err))) {
    throw new Error('Syntax: wrap math expression in parentheses, e.g. math(a + b)');
  }
  throw err;
}

Prevention

When it happens

Trigger: Writing math without parentheses: `u as math a + b`, a line break/token between math and (, or using math as a value name without invoking it, e.g. `math(a)` misspelled as `math (a)` is fine but `math.a` or `math:` fails.

Common situations: Typos in query blocks; pasting SQL-style expressions into DQL; forgetting the parentheses when converting a plain aggregation to math; editing tools that split tokens.

Related errors


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