Datastores
For my personal research projects the only datastores that I often use are the embedded relational database and Resource Description Framework (RDF) datastores that might be local to my laptop or public Knowledge Graphs like DBpedia and WikiData. The use of RDF data and the SPARQL query language is part of the fields of the semantic web and linked data.
Accessing public RDF Knowledge Graphs - a DBpedia example
I will not cover RDF data and the SPARQL query language in great detail here. For a longer treatment please read the RDF and SPARQL tutorial material in my Common Lisp book: Loving Common Lisp, or the Savvy Programmer’s Secret Weapon. The following short background is enough to follow the code in this chapter and the next one.
Just enough RDF and SPARQL
RDF data is a set of triples. Each triple is a statement with three parts: a subject, a predicate, and an object. Subjects and predicates are URIs, written inside angle brackets. An object is either another URI or a literal value like a string or a number:
1 <http://dbpedia.org/resource/Steve_Jobs>
2 <http://xmlns.com/foaf/0.1/name>
3 "Steve Jobs"@en .
This triple says that the thing identified by the first URI has the name “Steve Jobs”, and the @en tag says that the string is in English. Because the object of one triple can be the subject of another, a collection of triples forms a graph, which is where the term Knowledge Graph comes from.
A SPARQL query is a pattern with variables, which are names that start with a question mark. The query engine finds every way of filling in the variables so that the pattern matches triples in the datastore:
1 SELECT ?person ?comment {
2 ?person <http://xmlns.com/foaf/0.1/name> "Steve Jobs"@en .
3 ?person <http://www.w3.org/2000/01/rdf-schema#comment> ?comment .
4 FILTER (lang(?comment) = 'en')
5 }
The two patterns share the variable ?person, so a result must satisfy both: something named “Steve Jobs” that also has a comment. The FILTER line keeps only English comments. The queries in this chapter also use OPTIONAL (keep the result even if this part does not match) and UNION (match either of two patterns).
A SPARQL client for DBpedia
The following listing shows the file Racket-AI-book/source-code/sparql/sparql.rkt. It queries DBpedia’s public SPARQL endpoint for information about a person or place and converts the reply into Racket lists. Here is what each function does:
- sparql-escape-string prepares a name typed by a user for use inside a quoted SPARQL string. Without it, a name that contains a double quote character would end the string early and break the query.
- sparql-dbpedia-person-uri takes a person’s name and builds a query for the URIs and comments of everything with that name. sparql-dbpedia-place-uri does the same for places.
- sparql-dbpedia-for-person takes a person URI (including the angle brackets) and builds a query for a comment and for web sites associated with that person.
- sparql-query->hash sends a query to the endpoint and converts the JSON reply to a Racket hash table with string->jsexpr. A busy public endpoint sometimes replies with an HTML error page, so this function raises an error that shows the start of the reply when the reply is not JSON.
- json->listvals pulls the variable bindings out of the reply, giving one list per query variable.
- gd turns those per-variable lists into one list per result row.
- sparql-dbpedia is the function you will usually call: it runs a query and returns the rows.
The file starts with #lang at-exp racket. The at-exp reader adds a syntax for text with embedded Racket values, which is convenient for query templates. In the form @string-append{…} everything between the curly braces is literal text, except that @name inserts the value of the variable name. The odd looking @“@” is how you write a literal at sign, which SPARQL needs for the language tag @en.
1 #lang at-exp racket
2
3 ;;; sparql.rkt — A small SPARQL client for the DBpedia public endpoint
4 ;;; Apache 2 License
5
6 (provide sparql-dbpedia-for-person
7 sparql-dbpedia-person-uri
8 sparql-dbpedia-place-uri
9 sparql-escape-string
10 sparql-query->hash
11 json->listvals
12 extract-name-uri-and-comment
13 gd
14 sparql-dbpedia
15 *sparql-endpoint*)
16
17 (require net/url)
18 (require net/uri-codec)
19 (require json)
20 (require racket/pretty)
21
22 ;; The endpoint is a parameter so you can point the same code at another
23 ;; SPARQL service, for example https://query.wikidata.org/sparql
24 (define *sparql-endpoint* (make-parameter "https://dbpedia.org/sparql"))
25
26 ;; Names typed by a user go inside a quoted SPARQL literal. Escape the
27 ;; characters that would end the literal early or break the query.
28 (define (sparql-escape-string s)
29 (let* ([s (string-replace s "\\" "\\\\")]
30 [s (string-replace s "\"" "\\\"")]
31 [s (string-replace s "\n" "\\n")]
32 [s (string-replace s "\r" "\\r")])
33 s))
34
35 (define (sparql-dbpedia-for-person person-uri)
36 @string-append{
37 SELECT
38 (GROUP_CONCAT(DISTINCT ?website; SEPARATOR=" | ")
39 AS ?website) ?comment {
40 OPTIONAL {
41 { @person-uri <http://www.w3.org/2000/01/rdf-schema#comment> ?comment . FILTER (lang(?comment) = 'en') }
42 UNION
43 { @person-uri <http://dbpedia.org/ontology/description> ?comment . FILTER (lang(?comment) = 'en') }
44 } .
45 OPTIONAL {
46 @person-uri
47 <http://dbpedia.org/ontology/wikiPageExternalLink>
48 ?website
49 . FILTER( !regex(str(?website), "dbpedia", "i"))
50 }
51 } LIMIT 4})
52
53 (define (sparql-dbpedia-person-uri person-name)
54 (define name (sparql-escape-string person-name))
55 @string-append{
56 SELECT DISTINCT ?personuri ?comment {
57 ?personuri
58 <http://xmlns.com/foaf/0.1/name>
59 "@name"@"@"en .
60 {
61 ?personuri <http://www.w3.org/2000/01/rdf-schema#comment> ?comment .
62 FILTER (lang(?comment) = 'en')
63 } UNION {
64 ?personuri <http://dbpedia.org/ontology/description> ?comment .
65 FILTER (lang(?comment) = 'en')
66 }
67 }})
68
69 (define (sparql-dbpedia-place-uri place-name)
70 (define name (sparql-escape-string place-name))
71 @string-append{
72 SELECT DISTINCT ?placeuri ?comment {
73 ?placeuri
74 <http://xmlns.com/foaf/0.1/name>
75 "@name"@"@"en .
76 {
77 ?placeuri <http://www.w3.org/2000/01/rdf-schema#comment> ?comment .
78 FILTER (lang(?comment) = 'en')
79 } UNION {
80 ?placeuri <http://dbpedia.org/ontology/description> ?comment .
81 FILTER (lang(?comment) = 'en')
82 }
83 }})
84
85 ;; Send a query and return the JSON reply as a hash table. A busy public
86 ;; endpoint sometimes answers with an HTML error page instead of JSON, so
87 ;; a reply that does not parse raises an error that says what came back.
88 (define (sparql-query->hash query)
89 (define reply
90 (call/input-url
91 (string->url
92 (string-append
93 (*sparql-endpoint*)
94 "?query="
95 (uri-encode query)))
96 get-pure-port
97 port->string
98 '("Accept: application/json")))
99 (with-handlers
100 ([exn:fail:read?
101 (lambda (e)
102 (error 'sparql-query->hash
103 "endpoint did not return JSON; reply starts with: ~a"
104 (substring reply 0 (min 200 (string-length reply)))))])
105 (define result (string->jsexpr reply))
106 (unless (hash? result)
107 (error 'sparql-query->hash "unexpected JSON reply: ~a" result))
108 result))
109
110 ;; One list per query variable; each element is (variable-name value)
111 (define (json->listvals a-hash)
112 (let* ([head (hash-ref a-hash 'head (hash))]
113 [vars (hash-ref head 'vars '())]
114 [results (hash-ref a-hash 'results (hash))]
115 [bindings (hash-ref results 'bindings '())])
116 (for/list ([var vars])
117 (for/list ([bc bindings])
118 (let* ([var-sym (string->symbol var)]
119 [var-info (hash-ref bc var-sym (hash))]
120 [a-value (hash-ref var-info 'value "")])
121 (list var a-value))))))
122
123 ;; Turn the per-variable lists into one list per result row. "Zipping"
124 ;; with (apply map list ...) works for any number of query variables.
125 (define (gd data)
126 (let ([jd (json->listvals data)])
127 (if (null? jd)
128 '()
129 (apply map list jd))))
130
131 ;; Used by the Knowledge Graph Navigator: pair up the values of the
132 ;; first two query variables as (uri comment) lists
133 (define (extract-name-uri-and-comment l1 l2)
134 (map (lambda (a b) (list (second a) (second b)))
135 l1 l2))
136
137 (define (sparql-dbpedia sparql)
138 (gd (sparql-query->hash sparql)))
139
140 (module+ main
141 ;; (pretty-print (sparql-dbpedia (sparql-dbpedia-person-uri "Steve Jobs")))
142 ;; (pretty-print (sparql-dbpedia (sparql-dbpedia-for-person "<http://dbpedia.org/resource/Steve_Jobs>")))
143 (void))
The function gd is short but worth a second look. If json->listvals returns the lists (a1 a2) for the first variable and (b1 b2) for the second, then (apply map list …) pairs them up as ((a1 b1) (a2 b2)), one list per result row. This works for any number of query variables.
Let’s try an example in a Racket REPL:
1 > (require "sparql.rkt")
2 > (sparql-dbpedia (sparql-dbpedia-person-uri "Steve Jobs"))
3 '((("personuri" "http://dbpedia.org/resource/Steve_Jobs_(book)")
4 ("comment" "2011 authorized biography by Walter Isaacson"))
5 (("personuri" "http://dbpedia.org/resource/Steve_Jobs")
6 ("comment"
7 "American entrepreneur; co-founder of Apple Inc. (1955–2011)")))
DBpedia is rebuilt from Wikipedia from time to time, so the results you see will probably differ from mine. Notice that the name “Steve Jobs” matched a book as well as a person. The Knowledge Graph Navigator application in a later chapter shows the user a list to choose from when this happens.
In practice, I start exploring data on DBpedia using the SPARQL query web app https://dbpedia.org/sparql. I experiment with different SPARQL queries for whatever application I am working on and then embed those queries in my Racket, Common Lisp, Clojure (link to read my Clojure AI book free online), and other programming languages I use.
In addition to using DBpedia I often also use the WikiData public Knowledge Graph and local RDF data stores hosted on my laptop with Apache Jena. The endpoint in sparql.rkt is the parameter *sparql-endpoint*, so you can point the same code at another SPARQL service with parameterize. One of the practice problems at the end of this chapter asks you to try this with WikiData.
The directory also contains tests.rkt, which checks the result-processing functions against a saved JSON reply. You can run it without a network connection using raco test tests.rkt.
SQLite
Racket’s standard db library supports SQLite, so there is no package to install. The following listing shows the file sqlite.rkt in the directory Racket-AI-book/source-code/misc_code:
1 #lang racket
2
3 ;;; sqlite.rkt — Using SQLite through Racket's built-in db library
4 ;;; Apache 2 License
5
6 (require db)
7
8 (provide open-person-db add-person! find-person update-person-age!)
9
10 ;; Open (creating if needed) a database and make sure the table exists.
11 ;; Pass 'memory for a throwaway in-memory database.
12 (define (open-person-db [db-file "test.db"])
13 (define conn (sqlite3-connect #:database db-file #:mode 'create))
14 (query-exec conn
15 "create table if not exists person
16 (name varchar(30) primary key, age integer, email varchar(40))")
17 conn)
18
19 ;; Always pass values as query parameters (the ? placeholders) and never
20 ;; build SQL by pasting strings together: parameters are escaped for you.
21 (define (add-person! conn name age email)
22 (query-exec conn
23 "insert or replace into person values (?, ?, ?)"
24 name age email))
25
26 ;; query-maybe-row returns one row as a vector, or #f when nothing matches.
27 (define (find-person conn name)
28 (query-maybe-row conn "select * from person where name = ?" name))
29
30 (define (update-person-age! conn name new-age)
31 (query-exec conn "update person set age = ? where name = ?" new-age name))
32
33 (module+ main
34 (define conn (open-person-db 'memory))
35 (add-person! conn "Mary" 34 "mary@test.com")
36 ;; A transaction: either both inserts happen or neither does.
37 (call-with-transaction
38 conn
39 (lambda ()
40 (add-person! conn "Carlos" 51 "carlos@test.com")
41 (add-person! conn "Ana" 28 "ana@test.com")))
42 (println (query-rows conn "select * from person order by name"))
43 (println (find-person conn "Mary"))
44 (update-person-age! conn "Mary" 35)
45 (println (find-person conn "Mary"))
46 (println (find-person conn "Nobody"))
47 (println (query-value conn "select count(*) from person"))
48 (disconnect conn))
49
50 (module+ test
51 (require rackunit)
52 (define conn (open-person-db 'memory))
53 (add-person! conn "Mary" 34 "mary@test.com")
54 (check-equal? (find-person conn "Mary") (vector "Mary" 34 "mary@test.com"))
55 (update-person-age! conn "Mary" 35)
56 (check-equal? (vector-ref (find-person conn "Mary") 1) 35)
57 (check-false (find-person conn "Nobody"))
58 ;; a name containing a quote is safe because it is a parameter
59 (add-person! conn "O'Brien" 40 "ob@test.com")
60 (check-equal? (query-value conn "select count(*) from person") 2)
61 (disconnect conn))
The function open-person-db uses sqlite3-connect to open a database file. The #:mode ’create keyword argument creates the file if it does not exist, and the create table if not exists statement makes the function safe to call on a database that already has the table. Passing ’memory instead of a file name gives a database that lives only in memory, which is what the example and the tests use.
There are four things to notice in the rest of the code:
- Values are passed as query parameters. Each question mark in the SQL text is replaced by the corresponding extra argument to query-exec. Never build SQL by pasting strings together, because a value containing a quote character, like the name O’Brien in the test, would break the statement or worse.
- query-exec runs a statement that returns no rows, query-rows returns a list of rows with each row a vector, query-maybe-row returns one row or #f, and query-value returns a single value.
- call-with-transaction runs a function inside a transaction. If the function raises an error then none of its changes are kept.
- The test submodule at the end runs with raco test sqlite.rkt.
Running the file prints:
1 $ racket sqlite.rkt
2 '(#("Ana" 28 "ana@test.com")
3 #("Carlos" 51 "carlos@test.com")
4 #("Mary" 34 "mary@test.com"))
5 '#("Mary" 34 "mary@test.com")
6 '#("Mary" 35 "mary@test.com")
7 #f
8 3
The following diagram shows the high-level architecture of the datastore integrations developed in this chapter:
Optional practice problems
- Extend the SQLite example: add a function that deletes a person by name and a function that returns everyone older than a given age, both using query parameters. Add a test for each to the test submodule.
- Query WikiData: use parameterize to bind *sparql-endpoint* to
https://query.wikidata.org/sparqland run a simple query such asSELECT ?s ?p ?o { ?s ?p ?o } LIMIT 3. WikiData asks clients to identify themselves, so you may need to add aUser-Agentheader next to theAcceptheader in sparql-query->hash. - DBpedia location search: write a function
sparql-dbpedia-for-citythat queries DBpedia for a city’s name (e.g., “Paris” or “Tokyo”), returning its URI, country, and population, using SPARQL query templates.