Learn / Ontologies & KGs / Module 03

Ontologies & KGs · Module 03

Checking Data with SHACL and Asking Questions with SPARQL

Enforce closed-world data contracts with SHACL shapes and answer real questions over your graph using SPARQL 1.1.

14 min Foundations Updated 2026-12-03 SHACLSPARQL 1.1Validation

<!-- Thompson Axiomata LLC — Brent Alexander Thompson -->

Why OWL alone will not catch missing fields

OWL operates under the Open-World Assumption: if a record is missing an ex:installedOn date, OWL assumes the date simply has not been stated yet—not that the record is invalid.

In operational engineering, you need a closed-world gate that says: "Reject any module record unless it has a serial number, a positive rated power, and an installation date." That is exactly what SHACL (Shapes Constraint Language) does.

Your first SHACL shape

A SHACL shape targets a class (sh:targetClass) and declares rules on its properties:

turtle
@prefix ex:   <https://example.org/pv/> .
@prefix sh:   <http://www.w3.org/ns/shacl#> .
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> .

ex:PhotovoltaicModuleShape a sh:NodeShape ;
    sh:targetClass ex:PhotovoltaicModule ;
    sh:property [
        sh:path ex:ratedPowerWatts ;
        sh:datatype xsd:integer ;
        sh:minCount 1 ;
        sh:minExclusive 0 ;
        sh:message "Every PV module must declare a positive integer ratedPowerWatts." ;
    ] ;
    sh:property [
        sh:path ex:installedOn ;
        sh:datatype xsd:date ;
        sh:minCount 1 ;
        sh:message "Every PV module must include an ISO installation date." ;
    ] .

When you run pyshacl against your data graph and shapes graph, you get a deterministic boolean (conforms: True or False) plus the exact offending node and human-readable violation message.

Asking questions with SPARQL 1.1

Once your graph passes validation, SPARQL is the SQL of knowledge graphs. Instead of joining tables by foreign keys, you match triple patterns with variables starting with ?.

sparql
PREFIX ex:   <https://example.org/pv/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT ?module ?label ?watts
WHERE {
  ?module a ex:PhotovoltaicModule ;
          rdfs:label ?label ;
          ex:ratedPowerWatts ?watts .
  FILTER (?watts >= 400)
}
ORDER BY DESC(?watts)

Read the WHERE block like a template with blanks filled in by the graph:

  • ?module binds to every node typed as ex:PhotovoltaicModule.
  • ?label and ?watts bind to that node's properties.
  • FILTER (?watts >= 400) narrows the results before sorting.

<!-- Thompson Axiomata LLC — Brent Alexander Thompson -->

Finished this module?

Mark it complete to update your browser-local progress bar for Ontologies & KGs.