Groupby + Orderasc in Query

What I want to do

Return the most common Field.value

What I did

This returns the fields with a “count” field, but I’m not sure how to then order and limit to 1:

{
  query(func: uid("0xc44c")) {
    Organization.fields @groupby(Field.value) {
    	count(uid)
    }
  }
}

This returns the error: Vars can be assigned only when grouped by UID attribute

{   
  var(func: uid("0xc44c")) {
    Organization.fields @groupby(Field.value) {
    	a as count(uid)
    }
  }
  
  query(func: uid(a)) { uid }
}	

Groupy by works only on edges, not values.

To clarify, Field is a node type with an edge called Field.value :slight_smile:

{   
  query(func: uid("0xc44c")) {
		uid
    Organization.fields @groupby(Field.value) {
    	count(uid)
    }
  }
}	

Returns:

{
  "data": {
    "query": [
      {
        "uid": "0xc44c",
        "Organization.fields": [
          {
            "@groupby": [
              {
                "Field.value": "https://www.google.com/",
                "count": 1
              },
              {
                "Field.value": "https://www.nytco.com/",
                "count": 2
              }
            ]
          }
        ]
      }
    ]
  }

but i’m unsure how to then order by “count”

You can’t, cuz Group By works only on edges. And I know that is possible to run the first step on value edges. But it is not foreseen.

Sorry, I’m not following what you mean.

In my example above I’m grouping by an edge called “Field.value”, and the query returns the strings these edges are pointing to along with a “count” of how common each string is.

Are you saying there’s no way to then sort by this count?

Yes.

Count with Indexing is a post computed feature. So you need an extra block to do so. But you can’t do it with GB cuz it wasn’t made for value edges.

ah, if it’s not too much trouble could you please show me what you mean by this?

when i try to create another block, I get this error: “Vars can be assigned only when grouped by UID attribute”

In fact the phrase would be ‘So would you need an extra block to do so.’

https://dgraph.io/docs/query-language/multiple-query-blocks/#sidebar

That’s what I’m trying to say. The Group By is a multi-block feature. Group By doesn’t work with Value Edges. Only relational edges. That’s why you get this error.

To take a step back and try and understand things a bit better, if my the schema is:

type Form {
    id: ID!
    fields: [uid]
}
type Field {
    id: ID!
    name: string
    value: string
}

How would I query the most common value for each field name? is there an approach other than groupby I could use?