Support subtypes and subtype polymorphism

Moved from GitHub dgraph/4195

Posted by robsws:

We would like to be able to define a taxonomy in the type system such that one type can be a child type of another. As a result, if you were to filter on the parent type, all nodes of the child type would be matched. For example, the types might look like this, using “inherits” as a placeholder for subtype syntax:

type Vehicle {
  top_speed
  name
  ...
}

type Car inherits Vehicle {
  registration
  ...
}

type Aeroplane inherits Vehicle {
  capacity
}

With the following mutations:

_:car1 <dgraph.type> "Car" .
_:car1 <registration> "AAAA" .
_:car1 <name> "Astra" .
_:car1 <top_speed> 130 .

_:plane1 <dgraph.type> "Aeroplane" .
_:plane1 <capacity> 200 .
_:plane1 <name> "747" .
_:plane1 <top_speed> 360 .

the following query:

{
  all_vehicles(func: type(Vehicle)) {
    dgraph.type
    name
    top_speed
  }
}

should return every node that is a subtype of Vehicle, i.e.:

{
  "all_vehicles": [
    {
      "dgraph.type": "Car"
      "name": "Astra"
      "top_speed": 130
    },
    {
      "dgraph.type": "Aeroplane"
      "name": "747"
      "top_speed": 360
    }
  ]
}

As a workaround, right now we can simply assign all of the parent types of a particular type to an object, since it’s possible to assign multiple types to a node. For example, the following mutation could be made for the car object above:

_:car1 <dgraph.type> "Car" .
_:car1 <dgraph.type> "Vehicle" .

The main issue with this approach is that when returning the type, as I did in the “all_vehicles” query above, it’s not clear which type should be returned as there’s no information about which is the parent and which is the child type. If a node has several types in a taxonomy, we want to return only the leaf node type.

campoy commented :

It’s funny because I just spent one hour proposing a new type system to Manish.
I’ll be writing the specs later on, but it would include inheritance as well as methods and filters.

I’ll keep this issue open for now, and we’ll close it once it’s implemented.

Is this an urgent issue for you or is the current workaround enough for now?

robsws commented :

The workaround serves us fine for now, but it’s good to know that this feature is planned for the future. Thanks @campoy!