TypeDB tutorial · First presented at ER 2026

Learn TypeDB by modelling a real supply chain

Starting from real data on palm oil trade, from Indonesian districts and mills to EU importers, you'll design a TypeDB schema step by step, load the data and query it. No TypeDB experience needed. If you know entity-relationship modelling, you'll feel at home.

The path: TypeDB basics → the data → setup → build the model → load → query → where next

TypeDB in five minutes

TypeDB is a database whose schema is a conceptual model. You describe your domain with entities, relations and attributes. TypeDB stores data in exactly those terms, checks every query against them, and enforces their constraints.

Three kinds of type

EntitiesThings that exist on their own: a company, a mill, a country.
RelationsConnections between things, where each participant plays a named role. An ownership has an owner and an owned. A relation can have any number of roles and can own attributes itself.
AttributesTyped values, like a name, a volume or a date, owned by entities and relations.

Types can specialise other types (sub), and an @abstract type has no instances of its own. A query for a supertype automatically finds instances of all its subtypes. That's why this model is called PERA: the polymorphic entity-relation-attribute model.

Coming from entity-relationship (ER) modelling? how Chen's concepts map to TypeDB
Chen's ER modelTypeDB
entity setentity type
relationship setrelation type
role (r/e)relates on the relation, plays on the player
value setattribute type with a value type (string, integer, …)
attribute, a function E → Vowns
relationship attributea relation that owns an attribute
subset entity setssub
participation, keys, value constraints@card, @key, @values, @range, @regex

Unlike most ER implementations, nothing is translated away: relations keep their roles and identity, n-ary relations stay n-ary, and subtypes stay subtypes.

Schema, then data

A schema declares the types and how they connect: which attributes a type owns, which roles a relation relates, which roles a type plays. Annotations such as @key and @card add constraints. Here is a tiny schema for companies owning companies:

Data is instances of those types. Each instance is created with isa, given attributes with has, and linked into relations through roles:

A match query describes a pattern, and TypeDB returns every way the data fits it. This one returns one answer, LOUIS DREYFUS owning LDC EAST INDONESIA:

You don't need to run these three. The tutorial below builds a fuller version of the same schema.

The schema is enforced

Queries are pipelines

A TypeQL query is a sequence of clauses, each passing its results to the next: match finds data, then insert, delete, reduce (aggregate), sort or fetch act on it. Schema changes use define and undefine. The syntax guide on this page lists the main keywords.

Learn more: Entities, relations, attributes · Schema & data · Query clauses & pipelines · The PERA model

The data

The data comes from Trase's open supply-chain data: 81 real trade flows of palm oil from East Kalimantan, Indonesia, to EU countries in 2022.

Benedict, J. J., Biddle, H., Gollnow, F., Heilmayr, R., Mueller, C., Ribeiro, V., & Suavet, C. (2024). Indonesia palm oil supply chain (2018–2022) (Version 1.2) [Data set]. Trase. https://doi.org/10.48650/X83N-7M36. Licensed CC BY 4.0.

One row is one trade flow: palm oil grown in a district (kabupaten), processed at a mill, sometimes refined, exported by one company and imported by another into an EU country. The columns fall into three groups:

81trade flows (71 refined, 10 crude)
41mills
6refineries
37companies
6EU destination countries
5,505 ha10-year deforestation exposure
How this excerpt was made simplifications
  • Rows: from the full dataset (~1.7M rows), only 2022 flows from East Kalimantan to the EU with all actors known, then 81 of those, chosen so that every modelling case appears. No values were invented or edited.
  • Columns: 16 of ~35 kept. Dropped: year, Trase IDs and country codes, port of export, economic bloc, sustainability scores and commitments, emissions metrics.
  • Interpretation: NOT REFINED means the flow has no refiner. When importer_group equals importer, no parent is recorded. A refinery that shares its name with an exporter is read as owned by that company.
  • Caveat: Trase flows are modelled from customs, production and facility data, not observed shipments. The insert query below rounds values (volume 3 dp, deforestation 4 dp, USD 2 dp).
Browse the data 81 rows

Setup

You need a TypeDB server and a web browser.

  1. Set up a TypeDB server, either:
    • locally, with the installer script or Docker. When the server starts, you should see something like Running TypeDB CE 3.13.6... and then Ready!. Or:
    • as a free cloud instance: go to cloud.typedb.com → sign up for an account → click Deploy → finish the deployment and record your password. Once it's running, you'll see a link to open TypeDB Studio directly.
  2. Note the address, username and password
    • Local: http://localhost:8000, admin, password by default
    • Cloud: copy them from the cloud dashboard
  3. Connect TypeDB Studio
    • Open studio.typedb.com
    • Connect (at the top) with your credentials
    • Create a new, empty database

In Studio, check at the top of the page that you're connected. Then create a new, empty database (next to the connection info).

To write queries, open the Query page. Each query in the tutorial can be pasted into the editor and run with the green Play button in the top right. Queries auto-commit, and schema changes show up in the left sidebar.

Learn more: TypeDB Studio · Installing TypeDB CE

Ready to go!

Part 1 · Build the model

We read the data and model it a few columns at a time. Each step shows an ER diagram first and the TypeQL behind a reveal: try writing it yourself before you look, then run each snippet in order.

1 · Initial definitions: places

Reading the header and a first row, the easiest things to model are the places: the country, the province and the kabupaten (district) the palm oil comes from.

Three kinds of place, each identified by its name (underlined = key), under an abstract place (dashed). Every *_name attribute is a subtype of one name attribute; ER has no notation for that, so it isn't drawn.
Places in TypeQL snippet 1
  • attribute name, value string; declares an attribute type and its value type. country_name and the other names are subtypes of name, so a query for name finds all of them.
  • entity place @abstract; is a supertype with no direct instances. sub place makes country, province and kabupaten kinds of place.
  • owns country_name @key: every country has exactly one name, and no two countries share it.

Learn more: Type hierarchies · @abstract · @key

Places contain places

Presumably the places nest: a kabupaten lies in a province, which lies in a country.

One containment relation type, drawn once for each pair it connects. A province is a child of its country and a parent of its kabupaten.
Places hierarchy in TypeQL snippet 2
  • relation containment, relates parent, relates child declares a relation and its two roles.
  • plays containment:child says which types can fill a role. A province plays both roles.
  • @card sets how many: each containment has exactly one parent and one child (@card(1)), and a place has at most one parent (@card(0..1)).
  • Running define on an existing type, like entity country here, adds to it.

Learn more: Constraining data · @card

Tip: open the Schema page in Studio to see what your schema contains so far, drawn as a graph.

2 · Mills, refineries, exporters

The next columns are harder: the same names turn up as a mill's group, a refinery, an exporter and an importer. Is a refinery_group a different kind of thing from an exporter_group?

A few real rows (scroll sideways for more columns). Coloured: a name that appears more than once in the same row, each name in its own colour. NOT REFINED marks crude palm oil.

Option 1: one entity type per column

Taking the CSV header literally: six entity types, each with its own name.
Option 1 in TypeQL for discussion only, don't run it alongside option 2

Option 2: companies and facilities

The data sheet says each *_group column "groups the [X] column into parent companies where applicable". So there are really only companies and facilities (mills and refineries), linked by ownership, and exporter is a role a company plays, not a kind of company.

Dashed boxes = abstract types: legal_entity generalises companies and facilities. mill_name and refinery_name are both subtypes of facility_name (not drawn). The dashed owned line is added in snippet 4.
Option 2 in TypeQL snippet 3
  • A two-level hierarchy: mill and refinery are kinds of facility, and facilities and companies are kinds of legal_entity.
  • A role a supertype plays is inherited: mills and refineries can both be owned.
  • Companies are identified by their name (@key). Mills and refineries simply own a name.

Learn more: Determining object types · Using type hierarchies

Companies owning companies

In some rows LDC EAST INDONESIA is both the refinery and the exporter, and LOUIS DREYFUS is the refinery's group.

We read this as: the company LDC EAST INDONESIA owns the refinery of the same name and handles exports, and LOUIS DREYFUS is its parent company. So companies need to be ownable by other companies too.

Ownership extension snippet 4

Open the Schema page in Studio again to inspect the current schema: companies, facilities and the ownership relation now sit alongside the places.

3 · Commodities

The data has two commodities, PALM OIL and REFINED PALM OIL. How would you model them?

a) one entity type with an attribute
b) two independent entity types
c) one abstract type with two subtypes

Let's proceed with option a, as it's the simplest one.

Option a) in TypeQL snippet 5
  • @values(...) restricts an attribute to a fixed set of values, like an enum.

Learn more: @values

Challenge: option a) allows at most two commodity instances, because the name is a key restricted to two values. How would you get the same guarantee with option c)?
Challenge: option c) in TypeQL one possible answer

4 · Trade flows

Each row of the data is one trade flow linking a district, a mill, sometimes a refinery (crude palm oil isn't refined), an exporter, an importer, a destination country and a commodity. How would you model the flow itself?

One 6- or 7-way relationship. Dashed line = optional role. company plays two roles: exporter and importer.
Trade flow in TypeQL snippet 6
  • One relation with seven roles. Six are required (@card(1)) and the refiner is optional (@card(0..1)).
  • The relation owns attributes of its own: volume, deforestation exposure and value. double and decimal are numeric value types.
Why not a table or a graph? what other databases do with this
  • In a relational table, the roles survive only as foreign-key column names, the optional refiner becomes a nullable column, and "exactly one mill" has to be enforced in application code or triggers.
  • In a graph database, edges connect only two nodes. Chaining edges (mill → refinery → exporter → importer) invents connections: in this dataset, following hops gives 102 mill–importer pairs, but only 63 appear in a real flow. Making each flow a node of its own keeps the facts, but nothing enforces its roles or their cardinalities, and nothing retains the semantic distinction between what is an entity node versus a relation node.

In TypeDB the seven-way relation is stored, typed and constrained as it is.

Full model

Snippets 1–6 combined into a single define query. Use it if you skipped ahead or want a clean start: run it in a new, empty database.

Part 2 · Load the data

With the full schema in place, one insert query loads all 81 trade flows. It creates the places, companies and facilities first, binding each to a variable such as $co_louis_dreyfus, then uses those variables to create the containment, ownership and trade-flow relations. The whole query commits as one transaction, so if anything breaks the schema, none of it is saved.

Learn more: Inserting data · Transactions

Part 3 · Query

Each question below hides a query. Try writing it first, then open it and run it. The result counts are for this dataset.

Pattern matching and polymorphism

A query lists statements that must all be true. isa facility also matches every subtype of facility. isa! matches only the exact type, so $f isa! $t binds $t to each facility's own type.

Look up all countries and their names 7 results
Get all facilities, polymorphically, with their exact types 47 results
Extension: count facilities by type 41 mills, 6 refineries

Learn more: Variables & patterns · Polymorphic queries · reduce

Trade flows

links (role: $x) matches a relation through one of its roles; you only name the roles you care about. not { … } excludes matches, which suits optional roles like the refiner.

Count trade flows by import country 6 countries
Find the unrefined (crude) trade flows 10 results
Challenge: total deforestation exposure (deforestation_ha) by importer.
Deforestation exposure by importer one possible answer

Learn more: Relation patterns · Negations · Aggregations

Facility ownership

A facility can sit under several layers of companies. Can one query find all of a facility's owners? A disjunction ({ … } or { … }) handles a fixed number of hops. A recursive function handles any number: with fun defines a function for this query only, and let $c in owners($f) calls it.

One or two hops, spelled out LDC EAST INDONESIA and LOUIS DREYFUS
Any number of hops, with a recursive function same answer, any depth

Learn more: Disjunctions · Functions

Hitting the constraints

These are meant to fail. The first two are rejected by the type checker before anything runs; the third breaks a schema constraint when it's committed.

Insert a facility (an abstract type) type error
Find countries playing the mill role in trade flows type error
Insert a country without a country name fails at commit: @key

Learn more: Query validation · Data validation

Querying the model itself

The schema is queryable with the same language. Variables can stand for types as well as data, and statements like relates, plays and sub work in match too.

Which types play which roles in trade_flow? 7 results
Which legal entity types cannot own other legal entities? includes legal_entity itself

Learn more: Querying schema types

Where next

You've built a typed, constrained model of a real supply chain, loaded it and queried it. To keep going:

Or extend this model: add the ports of export or the sustainability commitments from the full Trase dataset, or model ownership shares as an attribute of ownership.