Custom field that returns value of a predicate belonging to a specific child?

Assuming the following schema:

type Parent {
  id: ID!
  children: [Child] @hasInverse(field: parent)
}

type Child {
  id: ID!
  parent: Parent!
  createdAt: DateTime
  color: String!
}

With the following data:

{
  "set": [
    {
      "uid": "_:theparent"
    },
    {
      "uid": "_:blue",
      "dgraph.type": "Color",
      "Color.createdAt": "2021-06-21T04:34:19+00:00",
      "Color.color": "blue",
      "Color.parent": { "uid": "_:theparent" }
     },
     {
       "uid": "_:red",
       "dgraph.type": "Child",
       "Child.createdAt": "2021-06-20T04:34:19+00:00",
       "Child.color": "red"
       "Color.parent": { "uid": "_:theparent" }
     },
     {
       "uid": "_:orange",
       "dgraph.type": "Child",
       "Child.createdAt": "2021-06-19T04:34:19+00:00",
       "Child.color": "orange"
       "Color.parent": { "uid": "_:theparent" }
     }
  ]
}     

…Is there any way to create a custom field on the Parent that maps to the value of color on a specific Child node?

What I want to achieve is to run the following query:

fetchParents(func: uid("0x11aa11")) {
  firstColor
}

…and receive a result that supplies a value for Parent.firstColor that corresponds to the value of Child.color of the first child when the child nodes are ordered by Child.createdAt

{
  "data": {
    "fetchParents": [
       {
         "firstColor": "orange"
       }
    ]
  }
}

How I imagine this working:

type Parent {
  id: ID!
  children: [Child] @hasInverse(field: parent)
  firstColor: [Child.color] @computed(func: findFirstChildColor)
}
function findFirstChildColor(uid) {
  // Logic to return correct `Child.color` value
}

Not sure If I got it. But try to add @reverse at Color.parent So you can do:

{
  fetchParents(func: uid("0x11aa11")) {
    firstColor : <~Color.parent> { Child.color }
  }
}

Neat, thanks. What do the angle brackets <> do in that example, I thought they were only used in RDF?

EDIT: oh, it’s due to the Child.parent statement containing a period . …? Which counts as a special character?

Relevant: Querying reverse edges whose names contain colons

If your predicate is a URI or has language-specific characters, then enclose it with angle brackets <> when executing the schema mutation.

https://dgraph.io/docs/query-language/schema/#predicates-i18n

We have some syntaxes from RDF in DQL. Angular brackets is used when we need to use special characters. Especially those where the language is a symbol. Like Chinese or Japanese.

1 Like