Querying knowledge graphs with SPARQL

File: sparql.lisp

DBpedia and Wikidata are large public knowledge graphs, and both answer SPARQL queries over HTTP. This program turns a query string into a list of Lisp association lists.

The code

 1 ;; sbcl --script sparql.lisp   (needs Quicklisp + curl)
 2 #-quicklisp (load "~/quicklisp/setup.lisp")
 3 (ql:quickload :com.inuoe.jzon :silent t)
 4 
 5 (defun sparql (endpoint query)
 6   "Returns a list of rows, each row an alist of (variable . value),
 7 with variables in SELECT order. Unbound variables are omitted."
 8   (let* ((cmd (list "curl" "-s" "-G" endpoint
 9                     "-H" "Accept: application/sparql-results+json"
10                     "-A" "sparql.lisp/1.0 (Common Lisp example)"
11                     "--data-urlencode"
12                     (concatenate 'string "query=" query)))
13          (raw (uiop:run-program cmd :output :string))
14          (json (com.inuoe.jzon:parse raw))
15          (vars (gethash "vars" (gethash "head" json)))
16          (bindings (gethash "bindings" (gethash "results" json))))
17     (map 'list
18          (lambda (row)
19            (loop for var across vars
20                  for b = (gethash var row)
21                  when b collect (cons var (gethash "value" b))))
22          bindings)))
23 
24 (defun dbpedia (query)
25   (sparql "https://dbpedia.org/sparql" query))
26 
27 (defun wikidata (query)
28   (sparql "https://query.wikidata.org/sparql" query))
29 
30 (print (dbpedia
31         "SELECT ?birth WHERE { dbr:Bill_Gates dbo:birthDate ?birth }"))
32 (print (wikidata
33         (concatenate
34          'string
35          "SELECT ?label WHERE { "
36          "wd:Q5284 rdfs:label ?label FILTER(LANG(?label) = \"en\") }")))

How it works

  • The request is a GET with the query URL-encoded by --data-urlencode, plus an Accept header that asks for the standard JSON results format. Some endpoints, Wikidata in particular, ask clients to send a descriptive User-Agent (-A).
  • In the JSON results format, head.vars lists the query’s variables in SELECT order, and each solution in results.bindings maps variable names to binding objects; a binding’s value key holds the lexical form. The inner loop walks vars (not the hash table, whose key order is unspecified), so each row lists its columns in the order you wrote them. A variable that an OPTIONAL clause leaves unbound has no entry in the solution, and when b drops it from that row.
  • dbpedia and wikidata are one-line wrappers that call sparql with each endpoint.

Running it

1 $ sbcl --script sparql.lisp

The first query asks DBpedia for Bill Gates’s birth date and prints a one-row, one-column result:

1 ((("birth" . "1955-10-28")))

The second asks Wikidata for the English label of the entity wd:Q5284 (Bill Gates). Actual output:

1 ((("label" . "Bill Gates")))

Column order and unbound variables matter once a query has several variables. This query asks DBpedia for two people and an OPTIONAL death date. Actual output in a REPL after loading the file:

1 * (dbpedia "SELECT ?name ?birth ?death WHERE {
2               VALUES ?p { dbr:Alan_Turing dbr:Bill_Gates }
3               ?p foaf:name ?name ; dbo:birthDate ?birth .
4               OPTIONAL { ?p dbo:deathDate ?death } }")
5 ((("name" . "Alan Turing") ("birth" . "1912-06-23") ("death" . "1954-06-07"))
6  (("name" . "Bill Gates") ("birth" . "1955-10-28")))

Each row lists its columns in SELECT order, and Bill Gates’s row has no death entry.

Using it

Knowledge graphs add precise facts to the text sources used elsewhere in this book: SPARQL returns exact, citable values rather than snippets. Try asking DBpedia for a topic’s abstract (dbo:abstract), or use Wikidata’s wdt: properties to follow relationships. The triple-store chapter later in the book builds a small version of the same idea (pattern matching with variables) over in-memory data.