dgraph-io/dgraph · error

Only uid predicate is allowed in count within groupby

Error message

Only uid predicate is allowed in count within groupby

What it means

In groupby queries, a child SubGraph with DoCount enabled (count(predicate)) must target the special "uid" predicate, because counting within groups is only implemented for uid edges. aggregateChild rejects any other attribute with this error before building the group aggregates.

Source

Thrown at query/groupby.go:35

	"github.com/dgraph-io/dgraph/v25/types"
)

type groupPair struct {
	key  types.Val
	attr string
}

type groupResult struct {
	keys       []groupPair
	aggregates []groupPair
	uids       []uint64
}

func (grp *groupResult) aggregateChild(child *SubGraph) error {
	fieldName := child.Params.Alias
	if child.Params.DoCount {
		if child.Attr != "uid" {
			return errors.Errorf("Only uid predicate is allowed in count within groupby")
		}
		if fieldName == "" {
			fieldName = "count"
		}
		grp.aggregates = append(grp.aggregates, groupPair{
			attr: fieldName,
			key: types.Val{
				Tid:   types.IntID,
				Value: int64(len(grp.uids)),
			},
		})
		return nil
	}
	if child.SrcFunc != nil && isAggregatorFn(child.SrcFunc.Name) {
		if fieldName == "" {
			fieldName = fmt.Sprintf("%s(%s)", child.SrcFunc.Name, child.Attr)
		}
		finalVal, err := aggregateGroup(grp, child)

View on GitHub (pinned to 759e242be6)

Solutions

  1. Use count(uid) inside groupby to count nodes per group
  2. Move the counting of a non-uid predicate outside groupby (e.g. fetch values and count client-side, or run a separate aggregation query)
  3. Restructure the query: groupby on the key and use a nested/second query for per-group counts of the predicate
  4. Check Dgraph docs/version for supported groupby aggregation syntax

Example fix

// before
groupby(q(func: type(Person)) { count(friend) @groupby(city) })
// after
{
  g(func: type(Person)) @groupby(city) { count(uid) }
}
Defensive patterns

Strategy: validation

Validate before calling

function validateGroupbyCount(child) {
  if (child.count && child.predicate !== 'uid') {
    throw new Error('groupby count supports only count(uid), got: ' + child.predicate);
  }
}

Try / catch

try {
  r = await txn.query(q);
} catch (e) {
  if (String(e).includes('Only uid predicate is allowed in count within groupby')) {
    // rewrite query to use count(uid) or aggregate client-side
  }
  throw e;
}

Prevention

When it happens

Trigger: A groupby query containing count(somePredicate) where somePredicate is a regular scalar or index predicate rather than count(uid).

Common situations: Developers try to count values of a normal predicate per group; copying a normal query's count() syntax into groupby where only count(uid) is supported; version-specific groupby limitations.

Related errors


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