Knowledge Graph Navigator

The Knowledge Graph Navigator (which I will often refer to as KGN) is a tool for processing a set of entity names and automatically exploring the public Knowledge Graph DBPedia using SPARQL queries. I started to write KGN for my own use to automate some things I used to do manually when exploring Knowledge Graphs, and later thought that KGN might be also useful for educational purposes. KGN shows the user the auto-generated SPARQL queries so hopefully the user will learn by seeing examples.

I cover SPARQL and linked data/Knowledge Graphs in previous books I have written. The chapter Datastores in this book has a short background section, and for more details please see either of the following:

  • The chapter Knowledge Graph Navigator in my book Loving Common Lisp, or the Savvy Programmer’s Secret Weapon
  • The chapters Background Material for the Semantic Web and Knowledge Graphs, Knowledge Graph Navigator in my book Practical Artificial Intelligence Programming With Clojure

We use the Natural Language Processing (NLP) library from the last chapter to find human and place names in input text and then construct SPARQL queries to access data from DBPedia.

The Racket version of KGN is deliberately small: it answers “who is …” questions about people and “where is …” questions about places. The following screenshots show the application:

KGN finds multiple RDF subjects for “Steve Jobs” so a dialog is presented to choose one

I have implemented parts of KGN in several languages: Common Lisp, Java, Clojure, Racket Scheme, Swift, Python, and Hy. The most full featured version of KGN, including a full user interface, is featured in my book Loving Common Lisp, or the Savvy Programmer’s Secret Weapon that you can read free online. That version performs more speculative SPARQL queries to find information compared to the example here that I designed for ease of understanding, and modification. I am not covering the basics of RDF data and SPARQL queries here. While I provide sufficient background material to understand the code, please read the relevant chapters in my Common Lisp book for more background material.

KGN query results

We will be running an example using data containing three person entities, one company entity, and one place entity. The following figure shows a very small part of the DBPedia Knowledge Graph that is centered around these entities. The data for this figure was collected by an example Knowledge Graph Creator from my Common Lisp book:

File dbpedia_sample.nt loaded into the free version of GraphDB

I chose to use DBPedia instead of WikiData for this example because DBPedia URIs are human readable. The following URIs represent the concept of a person. The semantic meanings of DBPedia and FOAF (friend of a friend) URIs are self-evident to a human reader while the WikiData URI is not:

1 http://www.wikidata.org/entity/Q215627
2 http://dbpedia.org/ontology/Person
3 http://xmlns.com/foaf/0.1/name

I frequently use WikiData in my work and WikiData is one of the most useful public knowledge bases. The SPARQL client that we use has its endpoint in a parameter, so the same code can be pointed at WikiData. You can try manually querying WikiData at the WikiData SPARQL endpoint. For example, you might explore the WikiData URI for the person concept using:

1 select ?p ?o where {
2  <http://www.wikidata.org/entity/Q215627> ?p ?o .
3 } limit 10

For the rest of this chapter we will just use DBPedia or data copied from DBPedia.

After looking at an interactive session using the example program for this chapter we will look at the implementation.

Entity types handled by KGN

To keep this example simple we handle just two entity types:

  • People
  • Places

The Common Lisp version of KGN also searches for relationships between entities. This search process consists of generating a series of SPARQL queries and calling the DBPedia SPARQL endpoint. I may add this feature to the Racket version of KGN in the future.

KGN implementation

The example application takes a question, finds the name of a person or a place in it, and generates a SPARQL query to DBPedia to find information about that entity.

We are using two libraries developed for this book that can be found in the directories Racket-AI-book/source-code/sparql and Racket-AI-book/source-code/nlp to supply support for SPARQL queries and natural language processing.

SPARQL client library

KGN uses the SPARQL client in Racket-AI-book/source-code/sparql/sparql.rkt that we developed in the chapter Datastores. Please see that chapter for the complete listing. KGN loads it with a relative path, (require “../sparql/sparql.rkt”), and uses five of its functions:

  • sparql-dbpedia-person-uri and sparql-dbpedia-place-uri each take a name and return the text of a SPARQL query that finds the URIs and English comments of everything with that name.
  • sparql-query->hash sends a query to DBPedia and returns the JSON reply as a hash table.
  • json->listvals converts that hash table into one list per query variable.
  • extract-name-uri-and-comment pairs up the values of the first two variables, giving a list of (URI comment) pairs.

Part of solving this problem is constructing SPARQL queries as strings, so it is worth looking at how one of the query templates is written:

 1 (define (sparql-dbpedia-person-uri person-name)
 2   (define name (sparql-escape-string person-name))
 3   @string-append{
 4     SELECT DISTINCT ?personuri ?comment {
 5       ?personuri
 6         <http://xmlns.com/foaf/0.1/name>
 7         "@name"@"@"en .
 8       {
 9         ?personuri <http://www.w3.org/2000/01/rdf-schema#comment> ?comment .
10         FILTER (lang(?comment) = 'en')
11       } UNION {
12         ?personuri <http://dbpedia.org/ontology/description> ?comment .
13         FILTER (lang(?comment) = 'en')
14       }
15 }})

The file sparql.rkt starts with #lang at-exp racket, which turns on Racket’s at-expression reader. This is a standard part of Racket, designed for writing text with a few embedded values. Here is how to read the form @string-append{…}:

  1. Everything between the curly braces is literal text. Line breaks and double quote characters need no escaping, which is why the query looks almost exactly as it would in the DBPedia query web app.
  2. Inside the braces, @name is replaced by the value of the Racket variable name. This is how the person’s name gets into the query.
  3. The pieces of text and the inserted values are passed as arguments to string-append, which joins them into one string.
  4. SPARQL itself uses an at sign for language tags, as in “Steve Jobs”@en. To get a literal at sign we write @“@”, which inserts the one-character string “@”.

So the line “@name”@“@“en produces a double quote, the name, another double quote, an at sign, and the letters en. The name is first passed through sparql-escape-string so that a name containing a double quote cannot end the quoted string early.

The query has two parts joined by UNION because DBPedia stores a short description of a thing under either of two predicates, and we accept whichever one is present. Each part uses FILTER to keep only English text.

NLP library

We implemented a library in the chapter Natural Language Processing that we use here.

Please make sure you have read that chapter before the following sections.

Implementation of KGN application code

The file Racket-AI-book/source-code/kgn/main.rkt contains the query handling code and the file Racket-AI-book/source-code/kgn/kgn.rkt the application code. The provided Racket scheme code is structured for interacting with the DBPedia SPARQL endpoint to retrieve information about persons or places based on a user’s string query. The code is organized into several defined functions aimed at handling different steps of the process:

Query parsing and entity Recognition

The parse-query function takes a string query-str and tokenizes it into a list of words after replacing certain characters (like “.” and “?”). It then checks for keywords like “who” or “where” to infer the type of query - person or place. Using find-human-names and find-place-names from the NLP library in the previous chapter, it extracts the entity names from the tokens. Depending on the type of query and the entities found, it returns a list indicating the type and name of the entity, or a list starting with unknown if no person or place is found.

SPARQL query construction and execution

The functions get-person-results and get-place-results take a name string, construct a SPARQL query to get information about the entity from DBPedia, execute the query, and process the results. They utilize the sparql-dbpedia-person-uri, sparql-query->hash, and json->listvals functions from the SPARQL client to construct the query, execute it, and convert the returned JSON data to a list, respectively.

Query interface

The ui-query-helper function acts as the top-level utility for processing a string query to generate a SPARQL query, execute it, and return the results. It first calls parse-query to understand the type of query and the entity in question. Depending on whether the query is about a person or a place, it invokes get-person-results or get-place-results, respectively, to get the relevant information from DBPedia. It then returns a list containing the SPARQL query and the results, or #f if the query type is unknown.

This code structure facilitates the breakdown of a user’s natural language query into actionable SPARQL queries to retrieve and present information about identified entities from a structured data source like DBPedia.

 1 #lang racket
 2 
 3 (require racket/pretty)
 4 (require "../nlp/main.rkt")          ; find-human-names, find-place-names
 5 (require "../sparql/sparql.rkt")    ; SPARQL query templates and client
 6 
 7 (provide get-person-results)
 8 (provide get-place-results)
 9 (provide parse-query)
10 (provide ui-query-helper)
11 
12 (define (get-person-results person-name-string)
13   (let ((person-uri (sparql-dbpedia-person-uri person-name-string)))
14     (let* ((hash-data (sparql-query->hash person-uri)))
15       (list
16        person-uri
17        (extract-name-uri-and-comment
18         (first (json->listvals hash-data)) (second (json->listvals hash-data)))))))
19 
20 
21 (define (get-place-results place-name-string)
22   (let ((place-uri (sparql-dbpedia-place-uri place-name-string)))
23     (let* ((hash-data (sparql-query->hash place-uri)))
24       (list
25        place-uri
26        (extract-name-uri-and-comment
27         (first (json->listvals hash-data)) (second (json->listvals hash-data)))))))
28 
29 
30 (define (parse-query query-str)
31   (let ((cleaned-query-tokens
32          (string-split (string-replace  (string-replace query-str "." " ") "?" " "))))
33     (printf "\n+ + + cleaned-query-tokens:~a\n" cleaned-query-tokens)
34     (if (member "who" cleaned-query-tokens)
35         (let ((person-names (find-human-names (list->vector cleaned-query-tokens) '())))
36           (printf "\n+ + person-names= ~a\n" person-names)
37           (if (> (length person-names) 0)
38               (list 'person (first person-names))   ;; for now, return the first name found
39               (list 'unknown query-str)))
40         (if (member "where" cleaned-query-tokens)
41             (let ((place-names (find-place-names (list->vector cleaned-query-tokens) '())))
42               (printf "\n+ + place-names= ~a\n" place-names)
43               (if (> (length place-names) 0)
44                   (list 'place (first place-names))   ;; for now, return the first place name found
45                   (list 'unknown query-str)))
46             (list 'unknown query-str))))) ;; no person or place name match so just return original query
47 
48 (define (ui-query-helper query-str)  ;; top level utility function for string query -> 1) generated sparql 2) query function
49   (display "in ui-query-helper: query-str=") (display query-str)
50   (let* ((parse-results (parse-query query-str))
51          (question-type (first parse-results))
52          (entity-name (second parse-results)))
53     (display (list parse-results question-type entity-name))
54     (if (equal? question-type 'person)
55         (let* ((results2 (get-person-results entity-name))
56                (sparql (car results2))
57                (results (second results2)))
58           (printf "\n++  results: ~a\n" results)
59           (list sparql results))
60         (if (equal? question-type 'place)
61             (let* ((results2 (get-place-results entity-name))
62                    (sparql (car results2))
63                    (results (second results2)))
64               (list sparql results))
65             #f))))

The file Racket-AI-book/source-code/kgn/dialog-utils.rkt contains the user interface code for a dialog box that lets the user choose between several matching entities. The function make-selection-functions builds the dialog once, with a list box and a button, and returns two functions. The first takes a list of strings, puts them in the list box, and shows the dialog. Because this is a modal dialog% object, that call does not return until the user closes the dialog by double-clicking an item or clicking the button. The second function returns the index of the item that was selected. Returning a pair of functions that share the dialog is a simple way to hide the GUI objects from the rest of the program.

 1 #lang racket/gui
 2 
 3 (require racket/gui/base)
 4 (require racket/pretty)
 5 (provide make-selection-functions)
 6 
 7 (define (make-selection-functions parent-frame title)
 8   (let* ((dialog
 9           (new dialog%   
10                [label title]     
11                [parent parent-frame]     
12                [width 440]   
13                [height 480]))
14          (close-callback
15           (lambda (button event)
16             (send dialog show #f)))
17          (entity-chooser-dialog-list-box
18           (new list-box%     
19                [label ""]    
20                [choices (list "aaaa" "bbbb")]    
21                [parent dialog]   
22                [callback (lambda (click event)
23                            (if (equal? (send event get-event-type) 'list-box-dclick)
24                                (close-callback click event)
25                                #f))]))
26          (quit-button
27           (new button% [parent dialog]
28              [label "Select an entity"]
29              [callback  close-callback]))
30          (set-new-items-and-show-dialog
31           (lambda (a-list)
32             (send entity-chooser-dialog-list-box set-selection 0)
33             (send entity-chooser-dialog-list-box set a-list)
34             (send dialog show #t)))
35          (get-selection-index (lambda () (first (send entity-chooser-dialog-list-box get-selections)))))
36     (list set-new-items-and-show-dialog get-selection-index)))

The local file kgn.rkt is the main program for this application. It builds the window: a text field for the question, a button, a read-only area that shows the generated SPARQL, and a read-only area for the results. Most of the file is the callback that runs when the user presses Enter or clicks the button. The callback calls ui-query-helper and then handles three cases. If there is exactly one result it is shown directly. If there are several, as with “Steve Jobs” in the first screenshot, the selection dialog is shown and the chosen result is displayed. If there are none, a message says so.

One detail is a little unusual. The widgets are created inside a single match-let* form, and the query callback needs to refer to widgets that are created after the text field that uses the callback. The code solves this by first installing a placeholder function named dummy and then replacing it with the real callback, using set!, once all of the widgets exist.

 1 #lang racket/gui
 2 
 3 ;; note: when building executable, choose GRacket, not Racket to get *.app bundle
 4 (require racket/gui/base)
 5 (require racket/match)
 6 (require racket/pretty)
 7 (require scribble/text/wrap)
 8 
 9 
10 ;; Sample queries:
11 ;;   who is Bill Gates
12 ;;   where is San Francisco?
13 ;; (only who/where queries are currently handled)
14 
15 (require "main.rkt")
16 (require "dialog-utils.rkt")
17 
18 (define count-substring 
19   (compose length regexp-match*))
20 
21 (define (short-string s)
22   (if (< (string-length s) 75)
23       s
24       (substring s 0 73)))
25 
26 (define dummy (lambda (button event) (display "\ndummy\n"))) ;; this will be redefined after UI objects are created
27 
28 (let ((query-callback (lambda (button event) (dummy button event))))
29   (match-let* ([frame (new frame% [label "Knowledge Graph Navigator"]
30                            [height 400] [width 608] [alignment '(left top)])]
31                [(list set-new-items-and-show-dialog get-selection-index) ; returns list of 2 callback functions
32                 (make-selection-functions frame "Test selection list")]
33                [query-field (new text-field%
34                                  [label "  Query:"] [parent frame]
35                                  [callback
36                                   (lambda( k e)
37                                     (if (equal? (send e get-event-type) 'text-field-enter) (query-callback k e) #f))])]
38                [a-container (new pane%
39                                  [parent frame] [alignment '(left top)])]
40                [a-message (new message%
41                                [parent frame] [label "  Generated SPARQL:"])]
42                [sparql-canvas (new text-field%
43                                    (parent frame) (label "")
44                                    [min-width 380] [min-height 200]
45                                    [enabled #f])]
46                [a-message-2 (new message% [parent frame] [label "  Results:"])]
47                [results-canvas (new text-field%
48                                     (parent frame) (label "")
49                                     [min-height 200] [enabled #f])]
50                [a-button (new button% [parent a-container]
51                               [label "Process: query -> generated SPARQL -> results from DBPedia"]
52                               [callback query-callback])])
53     (display "\nbefore setting new query-callback\n")
54     (set!
55      dummy ;; override dummy labmda defined earlier
56      (lambda (button event)
57        (display "\n+ in query-callback\n")
58        (let ((query-helper-results-all (ui-query-helper (send query-field get-value))))
59          (if (equal? query-helper-results-all #f)
60              (let ()
61                (send  sparql-canvas set-value "no generated SPARQL")
62                (send  results-canvas set-value "no results"))
63              (let* ((sparql-results (first query-helper-results-all))
64                     (query-helper-results-uri-and-description (cadr query-helper-results-all))
65                     (uris (map first query-helper-results-uri-and-description))
66                     (query-helper-results (map second query-helper-results-uri-and-description)))
67                (display "\n++ query-helper-results:\n") (display query-helper-results) (display "\n")
68                (if (= (length query-helper-results) 1)
69                    (let ()
70                      (send  sparql-canvas set-value sparql-results)
71                      (send  results-canvas set-value
72                             (string-append (string-join  (wrap-line (first query-helper-results) 95) "\n") "\n\n" (first uris))))
73                     (if (> (length query-helper-results) 1)
74                         (begin
75                           (set-new-items-and-show-dialog (map short-string query-helper-results))
76                           (let ([sel-index (get-selection-index)])
77                             (if (and (>= sel-index 0) (< sel-index (length query-helper-results)))
78                                 (let ([selected-result (list-ref query-helper-results sel-index)]
79                                       [selected-uri (list-ref uris sel-index)])
80                                   (display selected-result)
81                                   (send sparql-canvas set-value sparql-results)
82                                   (send results-canvas set-value
83                                         (string-append (string-join (wrap-line selected-result 95) "\n") "\n\n" selected-uri)))
84                                 (send results-canvas set-value "Selection cancelled"))))
85                         (send  results-canvas set-value (string-append "No results for: " (send query-field get-value))))))))))
86      (send frame show #t)))

The parsing step can be tested without the GUI or a network connection. The file tests.rkt checks that “who is Bill Gates?” is recognized as a question about a person, that “where is San Francisco?” is recognized as a question about a place, and that a question with no known name is reported as unknown. Run it with raco test tests.rkt.

The two screen shot figures seen earlier show the GUI application running.

The following diagram shows the high-level architecture of the Knowledge Graph Navigator application developed in this chapter:

Architecture diagram

Knowledge Graph Navigator wrap up

This KGN example was hopefully both interesting to you and simple enough in its implementation to use as a jumping off point for your own projects.

I had the idea for the KGN application because I was spending quite a bit of time manually setting up SPARQL queries for DBPedia (and other public sources like WikiData) and I wanted to experiment with partially automating this process. I have experimented with versions of KGN written in Java, Hy language (Lisp running on Python that I wrote a short book on), Swift, and Common Lisp and all four implementations take different approaches as I experimented with different ideas.

Optional practice problems

  1. Extend templates for Historical Events: the current KGN implementation only recognizes persons and places. Add support for querying historical events (e.g., battles, treaty signings) by crafting a new SPARQL template and corresponding parsing logic.
  2. Add Wikidata Backend: currently, KGN only queries DBpedia. Implement alternative query templates targeting Wikidata’s SPARQL endpoint (bind the *sparql-endpoint* parameter from the SPARQL client), mapping the resulting entities back to the GUI.
  3. Query History in the GUI: modify the GUI code in kgn.rkt to include a historical list of past queries in the user interface. Clicking on an item in the history list should automatically reload and execute that query.