axiothOntology Hub

Learn what an ontology is / Part 2. Representing and connecting data · Lesson 11 of 16

From tables to graphs: R2RML and mappings

Rules that turn relational databases and CSV into triples that fit an ontology.

Most of the world's data sits in tables. Choosing an ontology does not turn it into a graph. You need rules that say "this column of this table is that property of the ontology". Those rules are a mapping.

Select a row to see the triples it becomes

Matching underline colours go together. Each column fills one position of a triple.

Table PET

IDNAMEOWNER_ID
Nabi10
Choco10
Bori11

Mapping rules

  • ID → subject IRI ex:pet/{ID}, class ex:Pet
  • NAME → ex:name
  • OWNER_ID → ex:keptBy ex:person/{OWNER_ID}

Generated triples

  • ex:pet/1 rdf:type ex:Pet .
  • ex:pet/1 ex:name "Nabi" .
  • ex:pet/1 ex:keptBy ex:person/10 .

3 rows × 3 rules = 9 triples. Rows 1 and 2 both point at ex:person/10, so they meet at one node in the graph.

Two W3C standards

StandardHowResult
Direct MappingNo rules to write. Tables become classes, rows subjects, columns propertiesA graph shaped like the database
R2RMLYou write the rules: the shape of IRIs and which ontology terms to useA graph that fits the ontology you chose

How to read R2RML

One mapping (a TriplesMap) has three parts: where to read from (logicalTable), how to build the subject IRI from a row (subjectMap), and which column goes to which property (predicateObjectMap). The mapping is itself written in RDF.

@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix ex: <https://example.org/> .

<#PetMap>
  rr:logicalTable [ rr:tableName "PET" ] ;        # which table
  rr:subjectMap [                                  # one row, one subject
    rr:template "https://example.org/pet/{ID}" ;
    rr:class ex:Pet
  ] ;
  rr:predicateObjectMap [                          # one column, one property
    rr:predicate ex:name ;
    rr:objectMap [ rr:column "NAME" ]
  ] ;
  rr:predicateObjectMap [                          # a foreign key points at another subject
    rr:predicate ex:keptBy ;
    rr:objectMap [ rr:template "https://example.org/person/{OWNER_ID}" ]
  ] .

Copy the data, or translate on demand

Running the mapping to produce a file of triples is called materialisation. The alternative leaves the data in the database and rewrites each incoming SPARQL query to SQL through the mapping. That is a virtual knowledge graph, also called ontology-based data access (OBDA).

When the table is not in a database

R2RML covers relational databases only. RML extends the same approach to CSV, JSON and XML; it is a community specification. For attaching meaning to the columns of a CSV file there is a separate W3C standard, CSVW.

The ontology is the destination and the mapping is the road. When choosing an ontology, ask which of its properties each of your columns could map to; fit shows up quickly.

See it in a real ontology

Read more in the specifications