Dgraph returns different data type based on number of elements

Just wanted to discuss about the dgraph response, so the problem is, when I hit the query on dgraph, the response type is not consistent, for e.g if there is only one item then dgraph returns “Object/hash”, and if there are multiple items than it returns “Array of object”.

It will cause problem in frontend/backend, since every time developer will be bound to check the type of data, for each query he is making.
Take the case of Gru’s Question and tag relationship:

This is the dgraph query I used, to get tags associated with questions:

{ 
  root(_xid_: rootQuestion) { 
     question { 
        question.tag { 
            name
            _uid_
         } 
     }  
  }
}

So if If there is only question in db and has only one tag, then the response will be:

{
  root: {
    question : {  //This is an Object here
       question.tag: { //This is also an object
           uid: "0x2382787434"
           name: "Tag 1"
       }
    }
 }
}

Now if I add second question, with 2 tags associated with it, it will return:

{
  root: {
    question : [{  //This has become an Array now
       question.tag: { //This is an "Object" because it has only on tag
           uid: "0x2382787434"
           name: "Tag 1"
       },
       question.tag: [{ //This is an "Array" because of two tags
           uid: "0x2382787434"
           name: "Tag 2"
       }, {
          uid: "0x2382787434"
          name: "Tag 3"
       }],
    }]
 }
}

It would be great for developers to code, if dgraph returns consistent type. Even if there is only one element, it should return array with 1 elements, otherwise they have to introduce if/else condition for each element and nested ones for each query they made to dgraph server.

This is the Screenshot link for the response I recieved

Hmm… interesting point. I wonder if schema can help you there. By setting “question.tag” to a list of objects. @ashwin95r?

1 Like

I feel we could just return an array of objects (As we did previously). So that the client can figure out the number of results using its length.

So, all scalars would be key value pairs and objects would be lists. So the client could loop on the object values without having to do any checks or remembering if they wanted it to be a list or not. Like in go

for _, kv := range mp["Person"].([]interface{}) {
...
}
2 Likes

hmm… I felt the results looked better without the lists, when there was obviously only one result. But, yeah, maybe we should just always return arrays. Feel free to revert my change, and send me a PR, @ashwin95r.

1 Like

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