Querying Knowledge Graphs with SPARQL

File: Sparql.lean

DBpedia and Wikidata publish facts as triples and answer queries in the SPARQL language over HTTP. This program sends a query to each and returns the rows as lists of variable and value pairs.

The Code

 1 -- lean --run Sparql.lean   (needs curl)
 2 import Lean.Data.Json
 3 open Lean (Json)
 4 
 5 def run (cmd : String) (args : Array String) : IO String := do
 6   let out ← IO.Process.output { cmd, args }
 7   if out.exitCode != 0 then
 8     throw (IO.userError s!"{cmd} failed: {out.stderr}")
 9   return out.stdout
10 
11 -- One result row: (variable, value) pairs
12 abbrev Row := List (String × String)
13 
14 def parseRows (raw : String) : Except String (List Row) := do
15   let json ← Json.parse raw
16   let results ← json.getObjVal? "results"
17   let bindings ← (← results.getObjVal? "bindings").getArr?
18   bindings.toList.mapM fun row => do
19     (← row.getObj?).toList.mapM fun (var, binding) => do
20       return (var, ← (← binding.getObjVal? "value").getStr?)
21 
22 def sparql (endpoint query : String) : IO (List Row) := do
23   let raw ← run "curl" #["-sS", "-G", endpoint,
24     "-H", "Accept: application/sparql-results+json",
25     "-A", "Sparql.lean/1.0 (Lean 4 example)",
26     "--data-urlencode", s!"query={query}"]
27   match parseRows raw with
28   | .ok rows => return rows
29   | .error err => throw (IO.userError s!"{err}\nResponse: {raw}")
30 
31 def dbpedia (query : String) : IO (List Row) :=
32   sparql "https://dbpedia.org/sparql" query
33 
34 def wikidata (query : String) : IO (List Row) :=
35   sparql "https://query.wikidata.org/sparql" query
36 
37 def main : IO Unit := do
38   IO.println (← dbpedia
39     "SELECT ?birth WHERE { dbr:Bill_Gates dbo:birthDate ?birth }")
40   IO.println (← wikidata (
41     "SELECT ?label WHERE { " ++
42     "wd:Q5284 rdfs:label ?label FILTER(LANG(?label) = \"en\") }"))

How It Works

  • A Row is a list of pairs: a variable name and its value.
  • parseRows reads the standard SPARQL JSON result format. The rows are in the bindings array inside results. Each row is an object with one field per variable, and each field holds an object with a value.
  • getObj? returns the fields of an object, and toList turns them into pairs of name and value.
  • mapM is map for a function that can fail. The two nested mapM calls visit every variable of every row. The first failure ends the whole call with its error.
  • curl -G --data-urlencode adds the query to the URL and escapes it.
  • IO.println can print the result with no extra code. Lean has ToString instances for strings, pairs, and lists, and it combines them.

The Result Format

1 {
2   "head": { "vars": ["birth"] },
3   "results": {
4     "bindings": [
5       { "birth": { "type": "literal", "value": "1955-10-28" } }
6     ]
7   }
8 }

parseRows reads results.bindings, then each row object’s fields, then each field’s value. head.vars names the selected variables and is unused here.

Prefix Namespace Source
dbr: http://dbpedia.org/resource/ DBpedia
dbo: http://dbpedia.org/ontology/ DBpedia ontology
wd: http://www.wikidata.org/entity/ Wikidata
rdfs: http://www.w3.org/2000/01/rdf-schema# RDF Schema

SPARQL endpoints define these prefixes themselves, so a query can use dbr:Bill_Gates without a PREFIX line. Another endpoint may use different prefixes; add PREFIX lines when it does.

parseRows keeps only value. A typed literal also has type and datatype, and a label has xml:lang, so dates and language tags become plain strings. Add those fields to Row when the type matters.

Lean 4 Notes

Parameters that share a type. (endpoint query : String) declares two parameters of the same type in one group.

mapM. list.mapM f applies f to each element, where f returns a value in a monad such as Except. The result is one Except that holds the whole list, or the first error. Compare list.map f, which would return a list of separate Except values.

A step inside return. return (var, ← (← binding.getObjVal? "value").getStr?) runs two steps and builds a pair from the result. Read it from the inside: get the value field, read it as a string, pair it with the variable name.

Functions as arguments to mapM. fun row => do ... starts a new do block for each row. The inner fun (var, binding) => do ... takes apart each pair of field name and field value.

Returning an action. dbpedia has no do block. Its body is the action that sparql returns. You need do only when you join several steps.

Parentheses around a long argument. The second query in main is three strings joined with ++. The parentheses make the whole expression one argument to wikidata.

Running It

1 $ lean --run Sparql.lean
2 [[(birth, 1955-10-28)]]
3 [[(label, Bill Gates)]]

Using It

Change the queries in main. The triple store chapter matches patterns against a list in memory. A SPARQL endpoint does the same matching against billions of triples. To use a third endpoint, add a function like dbpedia with its URL.

Public endpoints set timeouts and rate limits. Keep queries small, add LIMIT, and send a User-Agent that names your program, as sparql does. A query that scans millions of triples may time out even when it is correct. Try this: add OPTIONAL, ORDER BY, and LIMIT to a query, then compare the rows with the triple store query.