Database Reference
In-Depth Information
SPARQL is based on subgraph matching, where the selection criteria is
expressed as a graph pattern. This pattern is matched against an RDF graph
instantiating the variables in the query.
In what follows, we will work with the Northwind data warehouse
represented as an RDF graph, as studied in Sect. 14.1.3 . Let us analyze the
following SPARQL query, which asks for names and hire date of employees:
PREFIX ex: < http://example.org/NWDW# >
PREFIX rdf: < http://www.w3.org/1999/02/22-rdf-syntax-ns# >
SELECT ?firstName ?lastName ?hireDate
WHERE
{
?emp a ex:Employee .
?emp ex:Employee#FirstName ?firstName .
?emp ex:Employee#LastName ?lastName .
?emp ex:Employee#HireDate ?hireDate .
}
There are three parts in the query. A sequence of PREFIX clauses declare
the namespaces. The SELECT clause indicates the format of the result. The
WHERE clause in this case contains a graph pattern composed of four triples
in Turtle notation. The triples in the query are matched against the triples in
an RDF graph that instantiates the variables in the pattern. In our case, this
is the default RDF graph that represents the Northwind data warehouse. If
we want to include other graphs, a FROM clause must be added, followed by
a list of named graphs. As we have seen, the query above (without the prefix
part) can be more succinctly written as follows:
SELECT ?firstName ?lastName ?hireDate
WHERE
{
?emp a ex:Employee ; ex:Employee#FirstName ?firstName ;
ex:Employee#LastName ?lastName ; ex:Employee#HireDate ?hireDate .
}
To evaluate the above query, we instantiate the variable ?emp with an
IRI whose type is http://example.org/NWDW#Employee . Then, we look if
there is a triple with the same subject and property ex:Employee#FirstName ,
and, if so, we instantiate the variable ?firstName . We proceed similarly to
instantiate the other variables in the query and return the result. Note that
in this case the result of the query is not an RDF graph, but a set of literals.
Alternatively, the CONSTRUCT clause can be used to return an RDF graph
built by substituting variables in a set of triple templates.
From now on, we omit the prefix clauses in queries for brevity. The keyword
DISTINCT must be used to remove duplicates in the result. For example,
the following query returns the cities of the Northwind customers, without
duplicates:
SELECT DISTINCT ?city
WHERE { ?customer a ex:Customer ; ex:Customer#City ?city . }
The FILTER keyword selects patterns that meet a certain condition. For
example, the query “First name and last name of the employees hired between
1992 and 1994” reads in SPARQL as follows:
Search WWH ::




Custom Search