RDF and SPARQL: A Practical Introduction

RDF and SPARQL: A Practical Introduction

RDF is a data model for statements about resources. SPARQL is the query language and protocol for retrieving and constructing RDF. The two are separate specifications, and the separation is useful: a dataset can be published as RDF without exposing a SPARQL endpoint, and an endpoint can serve data that was not published as linked data. For integration work they are usually deployed together. This article introduces the model, the query forms and the practical details that determine whether a query returns in milliseconds or in minutes.

The RDF data model

An RDF statement is a triple of subject, predicate and object. The subject is an IRI or a blank node. The predicate is an IRI. The object is an IRI, a literal or a blank node. An IRI identifies a resource globally; a literal is a value such as a string, number or date, optionally with a language tag or datatype; a blank node is an anonymous resource with only local scope.

Sets of triples form a graph. RDF 1.1 also defines datasets: a default graph plus zero or more named graphs, each identified by an IRI. Named graphs are how provenance, versioning and access control are usually represented. A statement inside a named graph can be attributed to a source without reifying the statement itself.

Serialisations differ in syntax but not in meaning. Turtle is the most readable and is the usual choice for examples and hand-authored data. N-Triples is a line-based subset that is easy to stream and diff. RDF/XML is the original XML syntax. JSON-LD is common in web APIs. A conforming parser produces the same graph from any of them.

@prefix ex: <http://example.org/> .
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

ex:book42
    a ex:Book ;
    dcterms:title "A Practical Guide"@en ;
    dcterms:creator ex:person17 .

ex:person17
    a foaf:Person ;
    foaf:name "Sam Okafor" .

a is shorthand for rdf:type. The semicolon repeats the subject and the full stop ends the statement. The example contains five triples: two type statements, a title, a creator link and a name.

RDF and SPARQL: querying the graph

A SPARQL query is matched against the graph as a set of basic graph patterns. Variables begin with ? or $. A shared variable joins two patterns, because the same variable must bind to the same value in both. The following query lists English titles and author names, ordered by title.

PREFIX ex: <http://example.org/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT ?title ?author
WHERE {
  ?book a ex:Book ;
        dcterms:title ?title ;
        dcterms:creator ?person .
  ?person foaf:name ?author .
  FILTER (lang(?title) = "en")
}
ORDER BY ?title
LIMIT 50

The first pattern binds a book and its title. The second binds the creator, and the third joins that creator to a name. The filter keeps only English titles; the order and limit make the result predictable. SPARQL 1.1 has four query forms. SELECT returns a table of bindings. ASK returns a boolean. CONSTRUCT returns an RDF graph built from a template. DESCRIBE returns an implementation-defined description of a resource, which is useful for interactive clients but unsuitable for reproducible tests because the result is not specified.

Property paths allow transitive traversal, so ex:partOf+ follows one or more part-of links. Aggregates such as COUNT, SUM, GROUP BY and HAVING support summary queries. OPTIONAL implements a left join; MINUS and NOT EXISTS test for the absence of a pattern. Subqueries allow a query to be composed in stages.

The protocol and result formats

SPARQL is also a protocol. A client sends a query to an endpoint by HTTP GET or POST, using the query parameter, and the server returns a result document. SELECT and ASK results use the SPARQL Results XML or JSON format, or CSV and TSV. CONSTRUCT and DESCRIBE return RDF in one of the RDF serialisations, selected by content negotiation. SPARQL 1.1 Update uses a separate update parameter and supports INSERT DATA, DELETE DATA, DELETE/INSERT WHERE, LOAD and CLEAR.

An endpoint may be public, authenticated or restricted by address. Public endpoints usually impose timeouts and result limits, and some disable expensive features such as arbitrary property paths or federated SERVICE calls. A query that performs well against a local store can fail against a public endpoint for reasons that have nothing to do with its logic.

Writing queries that behave

  • Start selective. Put the triple pattern with the fewest matches first and let the engine reorder only if it has statistics. A pattern that begins with a type triple over a large class is usually a mistake.
  • Bind before you filter. A filter that compares an unbound variable removes every row. A filter inside an OPTIONAL is not the same as a filter after it.
  • Limit during exploration. Run the query with LIMIT 20 and no ordering first, inspect the shape of the results, then add the ordering.
  • Count distinct entities. A join across two one-to-many relationships multiplies rows. COUNT(DISTINCT ?entity) is often the number you want.
  • Avoid DESCRIBE in tests. It is useful in a browser, but its output is not defined by the specification.
  • Use named graphs for provenance. If the store supports it, GRAPH ?g { ... } lets a query separate statements by source.
  • Federated queries are not free. SERVICE sends a subquery to another endpoint; latency, availability and result size are outside the local optimiser's control.

A worked query, step by step

A useful query is usually built in stages. Start with the class: SELECT ?book WHERE { ?book a ex:Book }. Add the title pattern, then the creator join. To count books per author, group on the person resource rather than on the name, because two authors can share a name.

PREFIX ex: <http://example.org/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT ?person ?author (COUNT(DISTINCT ?book) AS ?books)
WHERE {
  ?book a ex:Book ;
        dcterms:creator ?person .
  ?person foaf:name ?author .
}
GROUP BY ?person ?author
HAVING (COUNT(DISTINCT ?book) > 2)
ORDER BY DESC(?books)

The join is on ?person. The grouping keeps the person IRI and the displayed name separate, so an accidental name collision does not merge two authors. HAVING filters groups after aggregation, and DESC orders the largest counts first. The result can be joined back to a department or affiliation without changing the aggregation.

When RDF and SPARQL fit

The model is strongest where the schema is heterogeneous, incomplete or expected to change, and where data from independent sources must be combined without a central authority. It is weaker for high-volume transactional writes, for queries that scan almost every triple, and for applications that need a fixed relational schema and predictable latency. Modern quad stores narrow the performance gap, but the choice should follow the access pattern rather than the storage technology.

In the LOD2 stack, OpenLink Virtuoso provides the quad store and SPARQL endpoint, and Sparallax provides a faceted browser over the same data. A typical pipeline publishes relational data as RDF, links it to external datasets, loads it into a store, and exposes both an endpoint and dereferenceable URIs. The linked data principles determine what the URIs should mean; ontology design determines which terms the queries use.

The practical test is whether a query can be written from the data's own vocabulary without knowledge of the storage layout. If it can, the model is doing its job.


Testimonials

Dr. Mateja Verlič (Zemanta d.o.o., R&D)

We read a lot about people doing important things, however this time we – LOD2 partners – are the ones changing the history of Web by revolutionizing information use and reuse, contributing to semantic data standards and pushing the limits of almost every WWW-related aspect (sc… read

Dr. Jens Lehmann (Universität Leipzig, Research Group Leader)

The size and number of Semantic Web knowledge bases published as Linked Open Data has been growing tremendously over the past years. The LOD2 project will be a key factor for sustaining this momentum. More importantly, the quality of knowledge bases and the scalability of methods accessing… read

Jindřich Mynarz (University of Economics, Czech Republic)

Apart from being legally open, linked open data is an open technology. Due to its non-exclusive, non-proprietary, well-formalized, and standards-based nature, linked open data supports a wide spectrum of uses. It does not exclude any application from using it and thus it is open to be mixe… read

Dr. Mladen Stanojevic (Institute Mihajlo Pupin, Serbia)

The richness of any semantic model and the usability of represented data is dependent on the links between them. LOD2 is an important step in this direction that will enable an efficient exploration and processing of vast quantity of open data on the Web.

read

Mun Yong Yi (Korea Advanced Institute of Science and Technology (KAIST))

Data becomes more meaningful and powerful as they are linked and integrated. As I learn more about what LOD can do, I am convinced that it will not only change the future of the Internet but also the quality of human life. I am glad that I am participating in this project, which will defin… read

Orri Erling (OpenLink Software, Virtuoso Program Manager)

Value from information increasingly depends on integration. RDF is a great model for this. LOD2 will make RDF a cost competitive alternative in the database space, without compromising ad hoc flexibility and expressive power. read

Vojtech Svatek (University of Economics, Czech Republic)

As researcher in ontological engineering, I am excited to see LOD2 provide tools that make the generation of semantically structured data easy and thus widespread. I believe that ontological research is deemed to build upon the world views already expressed by means of simpl… read

Andreas Blumauer (Semantic Web Company, CEO)

15 years ago we all were excited when we published HTML for the first time and it didn't take a long time until all of us were "on the internet". Now we are starting to publish data on the web. Based on semantic web technologies professional data management will be possible in distributed … read

Kingsley Idehen (OpenLink Software, CEO)

Three years ago, OpenLink Software enthusiastically contributed the prowess of Virtuoso to the grassroots effort that lead to DBpedia and the Linked Open Data cloud that coalesced around it. Today, we are both honored and enthusiastic about Virtuoso's critical infrastructure role in this n… read

Bastiaan Deblieck (TenForce, Partner and Business Development Manager)

An internet of data opens up tremendous opportunities for our corporate and government customers. We intend to be on the forefront of this evolution. read

Christian Dirschl (Wolters Kluwer, Content Architect)

Linked (Open) Data will change the existing publishing paradigms! Creating high quality content for professional usage will remain an important factor in future publishing, but additional access points and new usage environments will equally define its success. read

Dr. Giovanni Tummarello (National University of Ireland, Galway, Research Unit Leader)

Semantic Markups on the Web could drive information reuse to enable scenarios and applications which we can now only dream of. The idea is extraordinarely compelling, but we know now it won't simply realize itself. The LOD2 project is now a great opportunity for inspired and coordinated re… read

Gregory Grefenstette (Exalead, Chief Science Officer)

Enterpise search is all about providing correct, complete, and appropriate information to the employee and decision maker. LOD2 promises to not only allow internal company information to be linked up to the growing amount of Open Data on the web, but to also provide the mechanisms for val… read

Hugh Williams (OpenLink Software)

It is exciting to see the LOD2 project finally kick off in its quest to take the Linked Open Data cloud to the next level of scalability, performance and integration for the exploitation of the Web as a viable platform for enterprise level data and information integration. read

Martin Kaltenböck (Semantic Web Company, CFO)

Linked (Open) Data technologies offer a new way of data integration for the enterprise! Smooth interoperability between internal data sets can reduce costs as well as the enrichment of these data sets by external data can support new market intelligence paradigms for a better decision making. read

Dr. Peter Boncz (Centrum Wiskunde & Informatica)

The publishing of ever more datasets by e.g. governments adds value for many key applications including business intelligence, which will drive the Linked Open Data (LOD) paradigm going forward. In the LOD2 project, CWI is working to increase the scalability and performance of querying int… read

Dr. Sören Auer (Universität Leipzig, LOD2 coordinator)

The Linked Data paradigm is a simple and efficient way for integration of heterogeneous information on the Web. Ultimately, we will, for example, be able to search for a new appartment and a close-by available spot in child care in one go. read

Tassilo Pellegrini (Semantic Web Company, R&D)

Semantic interoperability changes the technological and economic nature of metadata opening up exciting opportunities for value creation in various comercial and non-commercial areas. Linked Data is the blueprint for this new ecosystem and it will change the way we think about and use the web today. read

Wouter Dewanckel (TenForce, WP Project Leader)

It is an honor to take part in this challenging integration project to create solutions that can generate business value out of emerging technologies. read