SlideShare a Scribd company logo
1 of 78
SPARQL
Departamento de Informática
Universidad de Oviedo
Jose Emilio Labra Gayo
Jose Emilio Labra Gayo – Universidad de Oviedo
SPARQL
SPARQL (April 2006) query language for RDF data
Similar to SQL, but for RDF
Based on graph patterns
It also describes a REST protocol
SPARQL = SPARQL Protocol And RDF Query Language
SPARQL 1.1 (2013, recommendation)
Updates, federated queries, etc.
Jose Emilio Labra Gayo – Universidad de Oviedo
SPARQL Syntax
Similar to Turtle
URIs between <...>
<http://www.example.org/alice>
Namespace prefixes as in Turtle
prefix dc: <http://purl.org/dc/terms/>
dc:creator
Blank nodes
_:node or between square brackets [ ]
Literals between " "
"Alice" "234"^^xsd:integer
Comments start by #
# this is a comment
Variables start by?
?name
Jose Emilio Labra Gayo – Universidad de Oviedo
RDF
RDF = Graph model
Different syntaxes: N-Triples, Turtle, RDF/XML
@prefix dc: <http://purl.org/dc/terms/> .
@prefix uni: <http://uniovi.es/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
uni:biology dc:creator uni:bob .
uni:biology dc:creator uni:alice .
uni:chemistry dc:creator uni:alice .
uni:chemistry dc:creator uni:carol .
uni:law dc:creator uni:carol .
uni:alice rdf:type uni:Lecturer .
uni:bob rdf:type uni:Lecturer .
uni:carol rdf:type uni:Student .
data.ttl
Jose Emilio Labra Gayo – Universidad de Oviedo
@prefix dc: <http://purl.org/dc/terms/> .
@prefix uni: <http://uniovi.es/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
uni:biology dc:creator uni:bob .
uni:biology dc:creator uni:alice .
uni:chemistry dc:creator uni:alice .
uni:chemistry dc:creator uni:carol .
uni:law dc:creator uni:carol .
uni:alice rdf:type uni:Lecturer .
uni:bob rdf:type uni:Lecturer .
uni:carol rdf:type uni:Student .
RDF data
RDF graph
uni:chemistry
uni:alice
dc:creator
uni:carol
dc:creator
uni:Student
rdf:type
uni:biology
uni:bob
dc:creator
dc:creator
uni:Lecturer
rdf:type
rdf:type
uni:law
dc:creator
data.ttl
Jose Emilio Labra Gayo – Universidad de Oviedo
Simple SPARQL query
Search resources created by a Lecturer and order them
by lecturer
prefix dc: <http://purl.org/dc/terms/>
prefix uni: <http://uniovi.es/>
prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?p ?c WHERE {
?p dc:creator ?c .
?c rdf:type uni:Lecturer .
}
ORDER BY ?c
Jose Emilio Labra Gayo – Universidad de Oviedo
SELECT ?p ?c WHERE {
?p dc:creator ?c .
?c rdf:type uni:Lecturer .
}
ORDER BY ?c
uni:chemistry
uni:alicedc:creator
uni:carol
dc:creator
uni:Student
rdf:type
uni:biology
uni:bob
dc:creator
dc:creator
uni:Lecturer
rdf:type
rdf:type
uni:law
dc:creator
Graph patterns
?p
dc:creator ?c
uni:Lecturer
rdf:type
?p
?c
Results
?p ?c
uni:biology uni:bob
uni:chemistry uni:alice
uni:biology uni:alice
?p
?c
?p
?c
uni:biology uni:alice
uni:chemistry uni:alice
uni:biology uni:bob
sorted by ?c
Try it: https://goo.gl/fJuUBn
Jose Emilio Labra Gayo – Universidad de Oviedo
Playing with SPARQL
Command line tools:
Apache Jena. https://jena.apache.org/
Online:
SHACLex: can be used without endpoint
http://shaclex.herokuapp.com/
YASGUI: can be used to query existing SPARQL endpoints
http://yasgui.org/
Creating SPARQL endpoints
Apache Jena Fuseki: https://jena.apache.org/
Blazegraph: https://www.blazegraph.com/
Jose Emilio Labra Gayo – Universidad de Oviedo
Some public SPARQL endpoints
Name URL Description
SPARQLer http://www.sparql.org/sparql.html General purpose query
endpoint
DBpedia http://dbpedia.org/sparql RDF data from wikipedia
Wikidata https://query.wikidata.org/ RDF data from Wikipedia
DBLP http://dblp.rkbexplorer.com/sparql/ Bibliographic data
LinkedMDB http://data.linkedmdb.org/sparql Movie database
bio2rdf http://bio2rdf.org/sparql Linked data for life sciences
List of SPARQL endpoints:
https://www.w3.org/wiki/SparqlEndpoints
Jose Emilio Labra Gayo – Universidad de Oviedo
SPARQL query language
Jose Emilio Labra Gayo – Universidad de Oviedo
Parts of a query
prefix dc: <...>
prefix uni: <...>
SELECT ...
FROM <...>
FROM NAMED <...>
WHERE {
...
}
ORDER BY ...
HAVING ...
GROUP BY ...
LIMIT ...
OFFSET ...
BINDINGS ...
Graph Pattern
Query modifiers
Prefix declarations
Define dataset
Declare type of query
SELECT, ASK, DESCRIBE, CONSTRUCT
Jose Emilio Labra Gayo – Universidad de Oviedo
Prefix declarations
Similar to Turtle
No need to use @prefix, just prefix
No need to end prefix declarations by dot
Common aliases used in these slides:
alias... stands for...
rdf <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
rdfs <http://www.w3.org/2000/01/rdf-schema#>
owl <http://www.w3.org/2002/07/owl#>
xsd <http://www.w3.org/2001/XMLSchema#>
schema <http://schema.org/>
Other common prefixes can be found at: http://prefix.cc
Jose Emilio Labra Gayo – Universidad de Oviedo
Parts of a query
prefix dc: <...>
prefix uni: <...>
SELECT ...
FROM <...>
FROM NAMED <...>
WHERE {
...
}
ORDER BY ...
HAVING ...
GROUP BY ...
LIMIT ...
OFFSET ...
BINDINGS ...
Declare type of query
SELECT, ASK, DESCRIBE, CONSTRUCT
Graph Pattern
Query modifiers
Prefix declarations
Define dataset
Jose Emilio Labra Gayo – Universidad de Oviedo
Types of SPARQL queries
SELECT return values of variables or expressions
Results are a table of values
Can have several serializations: XML, JSON
ASK return true/false
DESCRIBE return a description of a resource
CONSTRUCT queries can build RDF triples/graphs
Jose Emilio Labra Gayo – Universidad de Oviedo
SELECT queries
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 31 .
:bob :name "Robert" ;
:age 31 .
SELECT ?n (?age + 1 as ?newAge) WHERE {
?x :name ?n ; :age ?age
}
Project out specific variables or expressions
---------------------
| n | newAge |
=====================
| "Alice" | 32 |
| "Robert" | 32 |
---------------------
SELECT * WHERE {
?x :name ?n ; :age ?age
}
Project out all variables
---------------------------
| x | n | age |
===========================
| :alice | "Alice" | 31 |
| :bob | "Robert" | 31 |
---------------------------
Project out distinct combinations only
SELECT DISTINCT ?age WHERE {
?x :name ?n ; :age ?age
}
-------
| age |
=======
| 31 |
-------
Jose Emilio Labra Gayo – Universidad de Oviedo
CONSTRUCT queries
Construct an RDF result
Can be used to transform RDF data
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 31 .
:bob :name "Robert" ;
:age 31 .
PREFIX : <http://example.org/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
CONSTRUCT {
?x foaf:name ?name ;
foaf:age ?age
} where {
?x :name ?name ;
:age ?age
}
@prefix : <http://example.org/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
:alice foaf:age 31 ;
foaf:name "Alice" .
:bob foaf:age 31 ;
foaf:name "Robert" .
Result
Jose Emilio Labra Gayo – Universidad de Oviedo
ASK queries
ASK return yes or no
Can be used to check errors
Yes
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 31 .
:bob :name "Robert" ;
:age 31 .
PREFIX : <http://example.org/>
ASK WHERE {
?x :age ?age
FILTER (?age > 18)
}
Result
Jose Emilio Labra Gayo – Universidad de Oviedo
DESCRIBE
Return a description of one or more nodes
@prefix : <http://example.org/>
.
:alice :age 31 ;
:name "Alice" .
PREFIX : <http://example.org/>
DESCRIBE ?x WHERE {
?x :name "Alice" .
}
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 31 .
:bob :name "Robert" ;
:age 31 .
Result
Jose Emilio Labra Gayo – Universidad de Oviedo
Parts of a query
prefix dc: <...>
prefix uni: <...>
SELECT ...
FROM <...>
FROM NAMED <...>
WHERE {
...
}
ORDER BY ...
HAVING ...
GROUP BY ...
LIMIT ...
OFFSET ...
BINDINGS ...
Graph Pattern
Query modifiers
Prefix declarations
Define dataset
Declare type of query
SELECT, ASK, DESCRIBE, CONSTRUCT
Jose Emilio Labra Gayo – Universidad de Oviedo
Define dataset using FROM
FROM declares the URL from which the data is queried
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?n
FROM <http://www.di.uniovi.es/~labra/labraFoaf.rdf>
WHERE { ?x foaf:name ?n }
If several data graphs are declared, they are merged
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?n
FROM <http://www.di.uniovi.es/~labra/labraFoaf.rdf>
FROM <http://www.w3.org/People/Berners-Lee/card>
WHERE {
?x foaf:name ?n
}
-----------------------------------
| n |
===================================
| "Jose Manuel Alonso Cienfuegos" |
| "Timothy Berners-Lee" |
| "Ivan Herman" |
| "Jose Emilio Labra Gayo" |
-----------------------------------
-----------------------------------
| n |
===================================
| "Jose Manuel Alonso Cienfuegos" |
| "Ivan Herman" |
| "Jose Emilio Labra Gayo" |
-----------------------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Named graphs
FROM NAMED asigns a name to the input graph
GRAPH matches with the corresponding graph name
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?n ?g
FROM NAMED <http://www.w3.org/People/Berners-Lee/card>
FROM NAMED <http://www.di.uniovi.es/~labra/labraFoaf.rdf>
WHERE {
GRAPH ?g { ?x foaf:name ?n }
}
------------------------------------------------------------------------------------
| n | g |
====================================================================================
| "Ivan Herman" | <http://www.di.uniovi.es/~labra/labraFoaf.rdf> |
| "Jose Manuel Alonso Cienfuegos" | <http://www.di.uniovi.es/~labra/labraFoaf.rdf> |
| "Jose Emilio Labra Gayo" | <http://www.di.uniovi.es/~labra/labraFoaf.rdf> |
| "Timothy Berners-Lee" | <http://www.w3.org/People/Berners-Lee/card> |
------------------------------------------------------------------------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Parts of a query
prefix dc: <...>
prefix uni: <...>
SELECT ...
FROM <...>
FROM NAMED <...>
WHERE {
...
}
ORDER BY ...
HAVING ...
GROUP BY ...
LIMIT ...
OFFSET ...
BINDINGS ...
Graph Pattern
Query modifiers
Prefix declarations
Define dataset
Declare type of query
SELECT, ASK, DESCRIBE, CONSTRUCT
Jose Emilio Labra Gayo – Universidad de Oviedo
Query patterns
Query patterns are made from triple patterns
Triple pattern = RDF triples which can contain variables
Examples of triple patterns
uni:biology dc:creator ?c resources that are dc:creator's of uni:biology
?r dc:creator :alice resources whose dc:creator is :alice
?r dc:creator ?c all resources related by dc:creator property
uni:biology ?p :alice properties that relate uni:biology with :alice
?x ?p ?y all statements
Jose Emilio Labra Gayo – Universidad de Oviedo
Basic graph patterns
Basic graph pattern = sequence of triple patterns
The matching process combines the values of variables
Example:
The values of variables must be the same in the results
SELECT ?p ?c WHERE {
?p dc:creator ?c .
?c rdf:type uni:Lecturer .
}
ORDER BY ?c
Jose Emilio Labra Gayo – Universidad de Oviedo
Basic graph patterns can have filters
FILTER limits the set of returned values
PREFIX : <http://example.org/>
SELECT ?n ?e WHERE {
?x :name ?n .
?x :age ?e
FILTER (?e > 18)
}
@prefix : <http://example.org/>.
:alice :name "Alice" .
:alice :age 31 .
:bob :name "Robert" .
:bob :age 12 .
:carol :name "Carol" .
:carol :age 25 .
| n | e |
=================
| "Carol" | 25 |
| "Alice" | 31 |
Try it: https://tinyurl.com/y8odenvm
Jose Emilio Labra Gayo – Universidad de Oviedo
Filter operators
FILTER uses XPath 2.0 functions and operators
Datatypes: Boolean, Integer, Float, dataTime, etc.
Typical operators: >, <, >=, <=, =, !=, ||, &&
PREFIX : <http://example.org/>
SELECT ?n ?e WHERE {
?x :name ?n .
?x :age ?e
FILTER (?e > 30 || ?e < 18)
}
Try it: https://tinyurl.com/yavd6bww
Jose Emilio Labra Gayo – Universidad de Oviedo
Convert/create datatypes
str(arg): converts its argument to a string
NOTE: URIs must be converted to strings to treat them as such
datatype(arg): returns datatype of a literal
IF ?x = "123"^^xsd:integer
THEN datatype(?x) = xsd:integer
lang(arg): returns the language of a literal
IF ?x = "University"@en
THEN: lang(?x) = "en"
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?label WHERE {
?x rdfs:label ?label .
FILTER (lang(?label) ="en")
}
Example
Try it: https://tinyurl.com/y8m3xlyg
Jose Emilio Labra Gayo – Universidad de Oviedo
Create datatypes
uri(arg), iri(arg): convert their argument to URI/IRI
bnode(arg): generates a blank node
strdt(literal,datatype): generates a literal with a
datatype
strdt("123","xsd:integer") = "123"^^<xsd:integer>
strlang(literal,lang): generates a literal with some
language
strlang("University","en") = "University"@"en"
Jose Emilio Labra Gayo – Universidad de Oviedo
Check datatypes
isNumeric(arg) = true if the argument is a number
isBlank(arg) = true if the argumento is a blank node
isLiteral(arg) = true if the argument is a literal
isIRI(arg) = true if the argument is an IRI
Jose Emilio Labra Gayo – Universidad de Oviedo
Conditions
bound(arg) = true if the argument has a value
exists(pattern) = true if the pattern is satisfied
not exists(pattern) = true si if the pattern is not satisfied
if(cond,expr1,expr2) = if cond = true, returns expr1,
otherwise, returns expr2
coalesce(e1,e2,...) = returns the first expression that is
evaluated without error
Jose Emilio Labra Gayo – Universidad de Oviedo
Examples
Filter numeric values
PREFIX : <http://example.org/>
SELECT ?age WHERE {
?x :age ?age .
FILTER (isNumeric(?age))
}
@prefix : <http://example.org/> .
:carol :age 34 ;
:name "Carol" .
:alice :age 23 ;
:name "Alice" .
:bob :age "Unknown" ;
:name "Robert" .
-------
| age |
=======
| 34 |
| 23 |
-------
Try it: https://tinyurl.com/yan74uwt
Jose Emilio Labra Gayo – Universidad de Oviedo
Functions with strings
strlen(str) = length of str
ucase(str) converts to uppercase
lcase(str) converts to lowercase
substr(str,start,size?)= substring from start with some size
substr('camino',3,2)='mi'
strstarts(str1,str2) = true if str1 starts with str2
strends(str1,str2) = true if str1 ends with str2
contains(str1,str2) = true if str1 contains str2
encode_for_uri(str) = result of encoding str as a uri
concat(str1,...strN) = concatenates strings
langMatches(str,lang) = true if a string matches some language lang
regex(str,p,flags) = true if string matches regular expression p with flags
Jose Emilio Labra Gayo – Universidad de Oviedo
Examples with strings
@prefix : <http://example.org/> .
:alice :firstName "Alice" ;
:lastName "Cooper" .
:bob :firstName "Robert" ;
:lastName "Smith" .
:carol :firstName "Carol" ;
:lastName "King" .
Try it: https://tinyurl.com/yd3p2l43
PREFIX : <http://example.org/>
SELECT (concat(?firstName,' ',?lastName) AS ?name)
WHERE
{
?x :firstName ?firstName .
?x :lastName ?lastName .
FILTER (contains(ucase(?firstName),'A'))
}
------------------
| name |
==================
| "Alice Cooper" |
| "Carol King" |
------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Regex
REGEX invokes regular expression matching
It is based on XPath 2.0 functions
regex(?Expr, ?Pattern [, ?Flags])
?Expr = expression to match
?Pattern = regular expression pattern
?Flags = matching options
Try it: https://tinyurl.com/yd29xsyz
@prefix : <http://example.org/>.
:alice :firstName "Alice" ;
:lastName "Cooper" .
:bob :firstName "Robert" ;
:lastName "Smith" .
:carol :firstName "Carol" ;
:lastName "King" .
PREFIX : <http://example.org/>
SELECT ?firstName WHERE {
?x :firstName ?firstName .
FILTER (regex(?firstName,"^[ABC](.*)"))
} -------------
| firstName |
=============
| "Alice" |
| "Carol" |
-------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Regex
Regular expressions
^ = start of string
$ = end of string
. = any character
d = dígit
? = optional, * = 0 or more, + = 1 or more
X{n} = matches X n times
X{m,n} = matches X from m to n times
Flags:
i = ignore case
m = multiple lines
s = simple line
x = removes white spaces
Jose Emilio Labra Gayo – Universidad de Oviedo
Numeric functions
abs(n) = absolute value
round(n) = rounds a number n
floor(n) = rounds n down
ceil(n) = rounds n up
rand() = random number between 0 y 1
Jose Emilio Labra Gayo – Universidad de Oviedo
Functions with dates
now() = returns current instant
year(i) = returns the year of some instant i
year("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) = 2011
month(i), day(i), hours(i), minutes(i), seconds(i), timezone(i), tz(i) =
similar but return other components
@prefix : <http://example.org/> .
:alice :age 23 ;
:name "Alice" .
:bob :age 20 ;
:name "Robert" .
PREFIX : <http://example.org/>
SELECT (year(now()) - ?age as ?birthYear) WHERE {
?x :age ?age .
}
-------------
| birthYear |
=============
| 1994 |
| 1997 |
-------------
Jose Emilio Labra Gayo – Universidad de Oviedo
HASH functions
md5(str) = applies MD5 algorithm to a str
sha1(str), sha224(str),sha256(str),sha384(str),
sha512(str) = compute hash of str using the
corresponding variations of SHA algorithm
PREFIX : <http://example.org/>
SELECT ?name
(SHA1(?email) AS ?sha1Email)
WHERE {
?x :name ?name .
?x :email ?email .
}
@prefix : <http://example.org/> .
:alice :name "Alice" ;
:email "alice@email.com" .
:bob :name "Robert" ;
:email "bob@example.com" .
---------------------------------------------------------
| name | sha1Email |
=========================================================
| "Alice" | "14bf670833d4d7daca31afce1011752c80691459" |
| "Robert" | "a460e37bf4d8e893f8fd39536997d5da8d21eebe" |
---------------------------------------------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23 .
:bob :firstName "Robert" ;
:age 20 .
Graph union
UNION combines results from several graphs
PREFIX : <http://example.org/>
SELECT ?n WHERE {
{ ?x :name ?n }
UNION
{ ?y :firstName ?n }
}
------------
| n |
============
| "Alice" |
| "Robert" |
------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Optional
OPTIONAL allows to define triples which match
information if exists, but don't fail if it doesn't exist
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23 .
:bob :name "Robert" .
:carol :name "Carol" ;
:age 33 .
PREFIX : <http://example.org/>
SELECT ?name ?age WHERE {
?x :name ?name .
?x :age ?age
}
PREFIX : <http://example.org/>
SELECT ?name ?age WHERE {
?x :name ?name
OPTIONAL { ?x :age ?age }
}
-----------------
| name | age |
=================
| "Alice" | 23 |
| "Carol" | 33 |
-----------------
------------------
| name | age |
==================
| "Alice" | 23 |
| "Robert" | |
| "Carol" | 33 |
------------------
without optional
with optional
Jose Emilio Labra Gayo – Universidad de Oviedo
Minus
Removes solutions that are compatible with a pattern
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23 .
:bob :name "Robert" .
:carol :name "Carol" ;
:age 33 .
prefix : <http://example.org/>
SELECT ?name WHERE {
?x :name ?name
MINUS {
?x :age 33
}
}
------------
| name |
============
| "Alice" |
| "Robert" |
------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Parts of a query
prefix dc: <...>
prefix uni: <...>
SELECT ...
FROM <...>
FROM NAMED <...>
WHERE {
...
}
ORDER BY ...
HAVING ...
GROUP BY ...
LIMIT ...
OFFSET ...
BINDINGS ...
Graph Pattern
Query modifiers
Prefix declarations
Define dataset
Declare type of query
SELECT, ASK, DESCRIBE, CONSTRUCT
Jose Emilio Labra Gayo – Universidad de Oviedo
Query modifiers
DISTINCT removes duplicate results
ORDER BY specifies the order of results (ASC, DESC…)
LIMIT n limits the number of results
OFFSET m declares from which result to start
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT DISTINCT ?n
WHERE {
?x foaf:knows ?y .
?y foaf:name ?n .
}
ORDER BY ASC(?n)
LIMIT 5
OFFSET 2
Jose Emilio Labra Gayo – Universidad de Oviedo
Bindings
BIND expr AS v = Asigns value of expr to variable v
@prefix : <http://example.org/>.
:apples :name "Apples" ;
:amount 3 ;
:price 3 .
:oranges :name "Oranges" ;
:amount 4 ;
:price 2 .
prefix : <http://example.org/>
SELECT ?name ?totalPrice
WHERE {
?x :name ?name ;
:amount ?amount ;
:price ?price .
BIND ((?amount * ?price) AS ?totalPrice)
}
--------------------------
| name | totalPrice |
==========================
| "Oranges" | 8 |
| "Apples" | 9 |
--------------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Bindings in SELECT clause
It is possible to do the binding directly in the SELECT
@prefix : <http://example.org/>.
:apples :name "Apples" ;
:amount 3 ;
:price 3 .
:oranges :name "Oranges" ;
:amount 4 ;
:price 2 .
prefix : <http://example.org/>
SELECT ?name
((?amount * ?price) AS ?totalPrice)
WHERE {
?x :name ?name ;
:amount ?amount ;
:price ?price .
}
--------------------------
| name | totalPrice |
==========================
| "Oranges" | 8 |
| "Apples" | 9 |
--------------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Aggregation functions:
AVG, SUM, COUNT, SAMPLE
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23 .
:bob :name "Robert" ;
:age 25 .
:carol :name "Carol" ;
:age 33 .
PREFIX : <http://example.org/>
SELECT (AVG(?age) AS ?average)
(SUM(?age) AS ?sum)
(COUNT(?age) AS ?count)
(SAMPLE(?age) AS ?sample)
WHERE {
?x :age ?age .
}
----------------------------------
| average | sum | count | sample |
==================================
| 27.0 | 81 | 3 | 23 |
----------------------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Aggregation functions:
MAX, MIN
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23 .
:bob :name "Robert" ;
:age 25 .
:carol :name "Carol" ;
:age 33 .
PREFIX : <http://example.org/>
SELECT (MAX(?age) AS ?max)
(MIN(?age) AS ?min)
WHERE {
?x :age ?age .
}
-----------------
| max | min |
=================
| 33 | 23 |
-----------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Aggregation functions
GROUP_CONCAT
prefix : <http://example.org/>
SELECT (GROUP_CONCAT(?age;
SEPARATOR=',')
as ?ages) where
{
?x :age ?age .
}
--------------
| ages |
==============
| "23,33,25" |
--------------
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23 .
:bob :name "Robert" ;
:age 25 .
:carol :name "Carol" ;
:age 33 .
Jose Emilio Labra Gayo – Universidad de Oviedo
Groupings: GROUP_BY
GROUP BY groups sets of results
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23;
:salary 1200 .
:bob :name "Robert" ;
:age 25 ;
:salary 1500 .
:carol :name "Carol" ;
:age 23 ;
:salary 2000 .
:dave :name "Dave" ;
:age 25 ;
:salary 2500 .
prefix : <http://example.org/>
SELECT (AVG(?salary) AS ?avgSalary) ?age
WHERE {
?x :age ?age ;
:salary ?salary .
}
GROUP BY ?age
-------------------
| avgSalary | age |
===================
| 1600.0 | 23 |
| 2000.0 | 25 |
-------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Groupings: HAVING
HAVING flters the groups that pass some condition
-------------------
| avgSalary | age |
===================
| 2000.0 | 25 |
-------------------
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23;
:salary 1200 .
:bob :name "Robert" ;
:age 25 ;
:salary 1500 .
:carol :name "Carol" ;
:age 23 ;
:salary 2000 .
:dave :name "Dave" ;
:age 25 ;
:salary 2500 .
prefix : <http://example.org/>
SELECT (AVG(?salary) AS ?avgSalary) ?age
WHERE {
?x :age ?age ;
:salary ?salary .
}
GROUP BY ?age
HAVING (?avgSalary > 1800)
Jose Emilio Labra Gayo – Universidad de Oviedo
Subqueries
It is possible to define queries inside queries
@prefix : <http://example.org/>.
:alice :name "Alice" ;
:age 23;
:salary 1200 .
:bob :name "Robert" ;
:age 25 ;
:salary 1500 .
:carol :name "Carol" ;
:age 23 ;
:salary 2000 .
:dave :name "Dave" ;
:age 25 ;
:salary 2500 .
prefix : <http://example.org/>
SELECT ?name ?salary
(?salary - ?avgSalary AS ?deviation)
WHERE {
?x :name ?name .
?x :salary ?salary .
{
SELECT (AVG(?salary) AS ?avgSalary) WHERE {
?x :salary ?salary .
}
}
}
---------------------------------
| name | salary | deviation |
=================================
| "Carol" | 2000 | 200.0 |
| "Alice" | 1200 | -600.0 |
| "Dave" | 2500 | 700.0 |
| "Robert" | 1500 | -300.0 |
---------------------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Property paths
Properties can use a path (similar to regular expressions)
p Match property p
(e) Path grouped in parenthesis
^e Inverse path e
!p Doesn't match property p
e1 / e2 Path e1 followed by e2
e1 | e2 Path e1 or e2
e* 0 or more e
e+ 1 or more e
e? 0 or 1 e
Jose Emilio Labra Gayo – Universidad de Oviedo
@prefix : <http://example.org/>.
@prefix foaf: <http://xmlns.com/foaf/0.1/>.
:alice :name "Alice" ;
foaf:knows :bob, :carol .
:bob foaf:name "Robert";
foaf:knows :carol .
:carol foaf:name "Carol" ;
foaf:knows :alice .
Property paths
prefix : <http://example.org/>
prefix foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?friend
WHERE {
?x (foaf:name | :name) ?name ;
foaf:knows / (foaf:name | :name) ?friend
} -----------------------
| name | friend |
=======================
| "Alice" | "Carol" |
| "Alice" | "Robert" |
| "Robert" | "Carol" |
| "Carol" | "Alice" |
-----------------------
Jose Emilio Labra Gayo – Universidad de Oviedo
Property paths
@prefix : <http://example.org/>.
@prefix foaf: <http://xmlns.com/foaf/0.1/>.
:isabelle foaf:knows :frank, :grace .
:frank foaf:knows :carol, :emily .
:grace foaf:knows :carol, :emily .
:carol foaf:knows :alice .
:emily foaf:knows :alice .
:heidi foaf:knows :dave .
:dave foaf:knows :bob .
:bob foaf:knows :alice .
prefix : <http://example.org/>
prefix foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?p {
?p foaf:knows+ :alice .
}
-------------
| p |
=============
| :carol |
| :grace |
| :isabelle |
| :frank |
| :emily |
| :bob |
| :dave |
| :heidi |
-------------
Alice
Bob Carol Emily
Dave Frank Grace
Heidi Isabelle
Jose Emilio Labra Gayo – Universidad de Oviedo
Property paths
@prefix : <http://example.org/>.
@prefix foaf: <http://xmlns.com/foaf/0.1/>.
:isabelle foaf:knows :frank, :grace .
:frank foaf:knows :carol, :emily .
:grace foaf:knows :carol, :emily .
:carol foaf:knows :alice .
:emily foaf:knows :alice .
:heidi foaf:knows :dave .
:dave foaf:knows :bob .
:bob foaf:knows :alice .
Alice
Bob Carol Emily
Dave Frank Grace
Heidi Isabelle
prefix : <http://example.org/>
prefix foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?p {
?p foaf:knows/foaf:knows :alice .
}
----------
| p |
==========
| :grace |
| :frank |
| :grace |
| :frank |
| :dave |
----------
Jose Emilio Labra Gayo – Universidad de Oviedo
Property paths
@prefix : <http://example.org/>.
@prefix foaf: <http://xmlns.com/foaf/0.1/>.
:isabelle foaf:knows :frank, :grace .
:frank foaf:knows :carol, :emily .
:grace foaf:knows :carol, :emily .
:carol foaf:knows :alice .
:emily foaf:knows :alice .
:heidi foaf:knows :dave .
:dave foaf:knows :bob .
:bob foaf:knows :alice .
Alice
Bob Carol Emily
Dave Frank Grace
Heidi Isabelle
prefix : <http://example.org/>
prefix foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?p {
?p foaf:knows/^foaf:knows :frank .
}
----------
| p |
==========
| :grace |
| :frank |
| :grace |
| :frank |
----------
Jose Emilio Labra Gayo – Universidad de Oviedo
SPARQL Update
Jose Emilio Labra Gayo – Universidad de Oviedo
Graph operations
Update
INSERT DATA = insert triples
DELETE/INSERT… = delete/insert triples conditionally
DELETE DATA = delete triples
LOAD = load triples from a uri
CLEAR = delete all triples from a graph
Graph management
CREATE = create named graph
DROP = drop graph
COPY…TO… = copy graph
MOVE…TO… = move graph
ADD = insert all elements from a graph in another one
Jose Emilio Labra Gayo – Universidad de Oviedo
Insert
INSERT DATA can be used to insert triples
prefix : <http://example.org/>.
prefix foaf: <http://xmlns.com/foaf/0.1/>.
INSERT DATA {
:ana foaf:name "Ana" ;
foaf:age 18 ;
:salary 1500 .
:bob foaf:name "Robert" ;
foaf:age 20 ;
:salary 2000 .
}
Jose Emilio Labra Gayo – Universidad de Oviedo
Insert in a graph
INSERT DATA into a named graph
prefix : <http://example.org/>
prefix foaf: <http://xmlns.com/foaf/0.1/>
INSERT DATA {
GRAPH <http://example.org/graph1> {
:alice foaf:name "Alice" ;
foaf:age 18 ;
:salary 1500 .
}
}
Jose Emilio Labra Gayo – Universidad de Oviedo
Insert
INSERT can insert triples in a graph
Requires the WHERE clause
PREFIX : <http://example.org/>
INSERT {
?p :value "GoodSalary".
} WHERE {
?p :salary ?salary .
FILTER (?salary >= 4000)
}
Jose Emilio Labra Gayo – Universidad de Oviedo
Graph load
LOAD uri = loads all triples from a graph available at uri
LOAD <http://www.di.uniovi.es/~labra/labraFoaf.rdf>
Jose Emilio Labra Gayo – Universidad de Oviedo
Delete data
DELETE DATA removes all triples in a graph
PREFIX : <http://example/org/>
DELETE DATA {
:alice :age 18 .
}
NOTA: DELETE DATA does not allow variables
Jose Emilio Labra Gayo – Universidad de Oviedo
Delete...where
DELETE WHERE removes triples in a graph specifying a
condition
PREFIX : <http://example.org/>
DELETE {
?x :age ?age .
} WHERE {
?x :age ?age .
FILTER (?age >= 60)
}
Jose Emilio Labra Gayo – Universidad de Oviedo
Updating information
DELETE/INSERT pattern can be used to update triples
in a graph
PREFIX : <http://example.org/>
DELETE { ?x :age ?age }
INSERT { ?x :age ?newAge }
WHERE {
?x :age ?age .
BIND((?age + 1) AS ?newAge)
}
Example: increment age
Jose Emilio Labra Gayo – Universidad de Oviedo
Deleting
CLEAR deletes all triples
It is possible to declare datasets
CLEAR g = Deletes graph g
CLEAR DEFAULT = Deletes default graph
CLEAR ALL = Deletes all graphs
Jose Emilio Labra Gayo – Universidad de Oviedo
Universal query
Obtain all triples in all graphs
PREFIX e: <http://ejemplo.org#>
SELECT * WHERE {
{ ?x ?p ?y . }
UNION
{ GRAPH ?g {
?x ?p ?y .
}
}
}
Jose Emilio Labra Gayo – Universidad de Oviedo
Remote services
SERVICE uri = Runs query from a SPARQL endpoint uri
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?name WHERE {
SERVICE <http://dbpedia.org/sparql> {
SELECT ?name WHERE {
?pais rdf:type dbo:Country .
?pais rdfs:label ?name .
FILTER (lang(?name)='es')
}
}
}
Some SPARQL endpoints:
http://esw.w3.org/topic/SparqlEndpoints
Jose Emilio Labra Gayo – Universidad de Oviedo
Federated queries
Combine results
from several
endpoints
PREFIX imdb: <http://data.linkedmdb.org/resource/movie/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT * {
{ SERVICE <http://dbpedia.org/sparql> {
SELECT ?spouseName WHERE {
?actor rdfs:label "Javier Bardem"@en ;
dbo:spouse ?spouse .
?spouse rdfs:label ?spouseName .
FILTER ( lang(?spouseName) = "en" )
}
}
}
{ SERVICE <http://data.linkedmdb.org/sparql> {
SELECT ?movieName ?movieDate WHERE {
?actor imdb:actor_name "Javier Bardem".
?movie imdb:actor ?actor ;
dcterms:title ?movieName ;
dcterms:date ?movieDate .
}
}
}
}
DBPedia: http://dbpedia.org
IMDB: http://data.linkedmdb.org
Jose Emilio Labra Gayo – Universidad de Oviedo
SPARQL Protocol
Jose Emilio Labra Gayo – Universidad de Oviedo
SPARQL Protocol
Defines the actions: query and update and their
parameters and their formats
query action
2 verbs: GET, POST
Parameters:
query: Encoded query
default-graph-uri: Default graph (optional)
named-graph-uri: Named graph (optional)
update action
Only POST with 3 parameters
update: Update query
using-graph-uri: Default graph (optional)
using-named-graph-uri: Named graph (optional)
Jose Emilio Labra Gayo – Universidad de Oviedo
Validating RDF using SPARQL?
Jose Emilio Labra Gayo – Universidad de Oviedo
Negation by failure pattern in SPARQL
Combining FILTER, OPTIONAL and !BOUND
Example: Search people not married
@prefix : <http://example.org/>.
:alice :isMarriedWith :Bob ;
:name "Alice" .
:bob :isMarriedWith :alice ;
:name "Robert" .
:carol :name "Carol" .
:dave :isMarriedWith :emily ;
:name "Dave" .
PREFIX : <http://example.org/>
SELECT ?n WHERE {
?x :name ?n
OPTIONAL {?x :isMarriedWith ?y }
FILTER ( !BOUND(?y) )
}
Does it really return people not married?
-----------
| n |
===========
| "Carol" |
-----------
Jose Emilio Labra Gayo – Universidad de Oviedo
Validating RDF with SPARQL
Example:
A person has age (integer) and one or more names (string)
Person__
foaf:age xsd:integer
foaf:name xsd:string+
:john foaf:age 23;
foaf:name "John" .
:bob foaf:age 34;
foaf:name "Bob", "Robert" .

RDF examples
:mary foaf:age 50, 65 .
Jose Emilio Labra Gayo – Universidad de Oviedo
Example of SPARQL query
ASK {
{ SELECT ?Person {
?Person foaf:age ?o .
} GROUP BY ?Person HAVING (COUNT(*)=1)
}
{ SELECT ?Person {
?Person foaf:age ?o .
FILTER ( isLiteral(?o) &&
datatype(?o) = xsd:integer )
} GROUP BY ?Person HAVING (COUNT(*)=1)
}
{ SELECT ?Person (COUNT(*) AS ?Person_c0) {
?Person foaf:name ?o .
} GROUP BY ?Person HAVING (COUNT(*)>=1)
}
{ SELECT ?Person (COUNT(*) AS ?Person_c1) {
?Person foaf:name ?o .
FILTER (isLiteral(?o) &&
datatype(?o) = xsd:string)
} GROUP BY ?Person HAVING (COUNT(*)>=1)
} FILTER (?Person_c0 = ?Person_c1)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Person__
foaf:age xsd:integer
foaf:name xsd:string+
Jose Emilio Labra Gayo – Universidad de Oviedo
Is it possible to add recursión to the model?
Example:
A person has age (integer), one or more names (string)
and knows 0 or more values which conform to person
Person__
foaf:age xsd:integer
foaf:name xsd:string+
0..*
foaf:knows
Jose Emilio Labra Gayo – Universidad de Oviedo
Validating RDF technologies
ShEx and SHACL can be used to validate RDF
<Person> {
foaf:age xsd:integer ;
foaf:name xsd:string+
foaf:knows @<Person>
}
Example in ShEx (see http://shex.io)
Jose Emilio Labra Gayo – Universidad de Oviedo
References
SPARQL by example
SPARQL by example cheatsheet
Learning SPARQL, book by Bob Ducharme
SPARQL 1.1 spec

More Related Content

What's hot

Two graph data models : RDF and Property Graphs
Two graph data models : RDF and Property GraphsTwo graph data models : RDF and Property Graphs
Two graph data models : RDF and Property Graphsandyseaborne
 
SHACL: Shaping the Big Ball of Data Mud
SHACL: Shaping the Big Ball of Data MudSHACL: Shaping the Big Ball of Data Mud
SHACL: Shaping the Big Ball of Data MudRichard Cyganiak
 
Towards an RDF Validation Language based on Regular Expression Derivatives
Towards an RDF Validation Language based on Regular Expression DerivativesTowards an RDF Validation Language based on Regular Expression Derivatives
Towards an RDF Validation Language based on Regular Expression DerivativesJose Emilio Labra Gayo
 
Graph Data -- RDF and Property Graphs
Graph Data -- RDF and Property GraphsGraph Data -- RDF and Property Graphs
Graph Data -- RDF and Property Graphsandyseaborne
 
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIsJosef Petrák
 
Shape Expressions: An RDF validation and transformation language
Shape Expressions: An RDF validation and transformation languageShape Expressions: An RDF validation and transformation language
Shape Expressions: An RDF validation and transformation languageJose Emilio Labra Gayo
 
SHACL in Apache jena - ApacheCon2020
SHACL in Apache jena - ApacheCon2020SHACL in Apache jena - ApacheCon2020
SHACL in Apache jena - ApacheCon2020andyseaborne
 
Semantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorialSemantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorialAdonisDamian
 
2016-02 Graphs - PG+RDF
2016-02 Graphs - PG+RDF2016-02 Graphs - PG+RDF
2016-02 Graphs - PG+RDFandyseaborne
 
RDF Tutorial - SPARQL 20091031
RDF Tutorial - SPARQL 20091031RDF Tutorial - SPARQL 20091031
RDF Tutorial - SPARQL 20091031kwangsub kim
 

What's hot (20)

Data shapes-test-suite
Data shapes-test-suiteData shapes-test-suite
Data shapes-test-suite
 
RDF, linked data and semantic web
RDF, linked data and semantic webRDF, linked data and semantic web
RDF, linked data and semantic web
 
Two graph data models : RDF and Property Graphs
Two graph data models : RDF and Property GraphsTwo graph data models : RDF and Property Graphs
Two graph data models : RDF and Property Graphs
 
SHACL: Shaping the Big Ball of Data Mud
SHACL: Shaping the Big Ball of Data MudSHACL: Shaping the Big Ball of Data Mud
SHACL: Shaping the Big Ball of Data Mud
 
SHACL by example
SHACL by exampleSHACL by example
SHACL by example
 
Towards an RDF Validation Language based on Regular Expression Derivatives
Towards an RDF Validation Language based on Regular Expression DerivativesTowards an RDF Validation Language based on Regular Expression Derivatives
Towards an RDF Validation Language based on Regular Expression Derivatives
 
SPIN in Five Slides
SPIN in Five SlidesSPIN in Five Slides
SPIN in Five Slides
 
Graph Data -- RDF and Property Graphs
Graph Data -- RDF and Property GraphsGraph Data -- RDF and Property Graphs
Graph Data -- RDF and Property Graphs
 
SHACL Overview
SHACL OverviewSHACL Overview
SHACL Overview
 
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
 
Shape Expressions: An RDF validation and transformation language
Shape Expressions: An RDF validation and transformation languageShape Expressions: An RDF validation and transformation language
Shape Expressions: An RDF validation and transformation language
 
4 sw architectures and sparql
4 sw architectures and sparql4 sw architectures and sparql
4 sw architectures and sparql
 
SHACL in Apache jena - ApacheCon2020
SHACL in Apache jena - ApacheCon2020SHACL in Apache jena - ApacheCon2020
SHACL in Apache jena - ApacheCon2020
 
RDF data validation 2017 SHACL
RDF data validation 2017 SHACLRDF data validation 2017 SHACL
RDF data validation 2017 SHACL
 
Semantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorialSemantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorial
 
2016-02 Graphs - PG+RDF
2016-02 Graphs - PG+RDF2016-02 Graphs - PG+RDF
2016-02 Graphs - PG+RDF
 
What's New in RDF 1.1?
What's New in RDF 1.1?What's New in RDF 1.1?
What's New in RDF 1.1?
 
RDF Tutorial - SPARQL 20091031
RDF Tutorial - SPARQL 20091031RDF Tutorial - SPARQL 20091031
RDF Tutorial - SPARQL 20091031
 
SWT Lecture Session 2 - RDF
SWT Lecture Session 2 - RDFSWT Lecture Session 2 - RDF
SWT Lecture Session 2 - RDF
 
SPARQL Cheat Sheet
SPARQL Cheat SheetSPARQL Cheat Sheet
SPARQL Cheat Sheet
 

Similar to Introduction to SPARQL

SPARQL introduction and training (130+ slides with exercices)
SPARQL introduction and training (130+ slides with exercices)SPARQL introduction and training (130+ slides with exercices)
SPARQL introduction and training (130+ slides with exercices)Thomas Francart
 
The Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLMyungjin Lee
 
SPARQL 1.1 Update (2013-03-05)
SPARQL 1.1 Update (2013-03-05)SPARQL 1.1 Update (2013-03-05)
SPARQL 1.1 Update (2013-03-05)andyseaborne
 
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQLPedro Szekely
 
NoSQL and Triple Stores
NoSQL and Triple StoresNoSQL and Triple Stores
NoSQL and Triple Storesandyseaborne
 
Visualize open data with Plone - eea.daviz PLOG 2013
Visualize open data with Plone - eea.daviz PLOG 2013Visualize open data with Plone - eea.daviz PLOG 2013
Visualize open data with Plone - eea.daviz PLOG 2013Antonio De Marinis
 
Mon norton tut_queryinglinkeddata02
Mon norton tut_queryinglinkeddata02Mon norton tut_queryinglinkeddata02
Mon norton tut_queryinglinkeddata02eswcsummerschool
 
Functional manipulations of large data graphs 20160601
Functional manipulations of large data graphs 20160601Functional manipulations of large data graphs 20160601
Functional manipulations of large data graphs 20160601David Wood
 
SPARQL-DL - Theory & Practice
SPARQL-DL - Theory & PracticeSPARQL-DL - Theory & Practice
SPARQL-DL - Theory & PracticeAdriel Café
 
From SQL to SPARQL
From SQL to SPARQLFrom SQL to SPARQL
From SQL to SPARQLGeorge Roth
 
Querying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQLQuerying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQLEmanuele Della Valle
 
SWT Lecture Session 4 - SW architectures and SPARQL
SWT Lecture Session 4 - SW architectures and SPARQLSWT Lecture Session 4 - SW architectures and SPARQL
SWT Lecture Session 4 - SW architectures and SPARQLMariano Rodriguez-Muro
 
SuRf – Tapping Into The Web Of Data
SuRf – Tapping Into The Web Of DataSuRf – Tapping Into The Web Of Data
SuRf – Tapping Into The Web Of Datacosbas
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQLLino Valdivia
 
2008 11 13 Hcls Call
2008 11 13 Hcls Call2008 11 13 Hcls Call
2008 11 13 Hcls CallJun Zhao
 
Semantic Web(Web 3.0) SPARQL
Semantic Web(Web 3.0) SPARQLSemantic Web(Web 3.0) SPARQL
Semantic Web(Web 3.0) SPARQLDaniel D.J. UM
 

Similar to Introduction to SPARQL (20)

SPARQL introduction and training (130+ slides with exercices)
SPARQL introduction and training (130+ slides with exercices)SPARQL introduction and training (130+ slides with exercices)
SPARQL introduction and training (130+ slides with exercices)
 
The Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQL
 
BioSD Tutorial 2014 Editition
BioSD Tutorial 2014 EdititionBioSD Tutorial 2014 Editition
BioSD Tutorial 2014 Editition
 
Sparql
SparqlSparql
Sparql
 
SPARQL 1.1 Update (2013-03-05)
SPARQL 1.1 Update (2013-03-05)SPARQL 1.1 Update (2013-03-05)
SPARQL 1.1 Update (2013-03-05)
 
Sparql
SparqlSparql
Sparql
 
Querying Linked Data
Querying Linked DataQuerying Linked Data
Querying Linked Data
 
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQL
 
NoSQL and Triple Stores
NoSQL and Triple StoresNoSQL and Triple Stores
NoSQL and Triple Stores
 
Visualize open data with Plone - eea.daviz PLOG 2013
Visualize open data with Plone - eea.daviz PLOG 2013Visualize open data with Plone - eea.daviz PLOG 2013
Visualize open data with Plone - eea.daviz PLOG 2013
 
Mon norton tut_queryinglinkeddata02
Mon norton tut_queryinglinkeddata02Mon norton tut_queryinglinkeddata02
Mon norton tut_queryinglinkeddata02
 
Functional manipulations of large data graphs 20160601
Functional manipulations of large data graphs 20160601Functional manipulations of large data graphs 20160601
Functional manipulations of large data graphs 20160601
 
SPARQL-DL - Theory & Practice
SPARQL-DL - Theory & PracticeSPARQL-DL - Theory & Practice
SPARQL-DL - Theory & Practice
 
From SQL to SPARQL
From SQL to SPARQLFrom SQL to SPARQL
From SQL to SPARQL
 
Querying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQLQuerying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQL
 
SWT Lecture Session 4 - SW architectures and SPARQL
SWT Lecture Session 4 - SW architectures and SPARQLSWT Lecture Session 4 - SW architectures and SPARQL
SWT Lecture Session 4 - SW architectures and SPARQL
 
SuRf – Tapping Into The Web Of Data
SuRf – Tapping Into The Web Of DataSuRf – Tapping Into The Web Of Data
SuRf – Tapping Into The Web Of Data
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQL
 
2008 11 13 Hcls Call
2008 11 13 Hcls Call2008 11 13 Hcls Call
2008 11 13 Hcls Call
 
Semantic Web(Web 3.0) SPARQL
Semantic Web(Web 3.0) SPARQLSemantic Web(Web 3.0) SPARQL
Semantic Web(Web 3.0) SPARQL
 

More from Jose Emilio Labra Gayo

Introducción a la investigación/doctorado
Introducción a la investigación/doctoradoIntroducción a la investigación/doctorado
Introducción a la investigación/doctoradoJose Emilio Labra Gayo
 
Legislative data portals and linked data quality
Legislative data portals and linked data qualityLegislative data portals and linked data quality
Legislative data portals and linked data qualityJose Emilio Labra Gayo
 
Legislative document content extraction based on Semantic Web technologies
Legislative document content extraction based on Semantic Web technologiesLegislative document content extraction based on Semantic Web technologies
Legislative document content extraction based on Semantic Web technologiesJose Emilio Labra Gayo
 
Como publicar datos: hacia los datos abiertos enlazados
Como publicar datos: hacia los datos abiertos enlazadosComo publicar datos: hacia los datos abiertos enlazados
Como publicar datos: hacia los datos abiertos enlazadosJose Emilio Labra Gayo
 
Arquitectura de la Web y Computación en el Servidor
Arquitectura de la Web y Computación en el ServidorArquitectura de la Web y Computación en el Servidor
Arquitectura de la Web y Computación en el ServidorJose Emilio Labra Gayo
 
6 Principios de Programación Orientada a Objetos
6 Principios de Programación Orientada a Objetos6 Principios de Programación Orientada a Objetos
6 Principios de Programación Orientada a ObjetosJose Emilio Labra Gayo
 

More from Jose Emilio Labra Gayo (20)

Publicaciones de investigación
Publicaciones de investigaciónPublicaciones de investigación
Publicaciones de investigación
 
Introducción a la investigación/doctorado
Introducción a la investigación/doctoradoIntroducción a la investigación/doctorado
Introducción a la investigación/doctorado
 
Legislative data portals and linked data quality
Legislative data portals and linked data qualityLegislative data portals and linked data quality
Legislative data portals and linked data quality
 
Wikidata
WikidataWikidata
Wikidata
 
Legislative document content extraction based on Semantic Web technologies
Legislative document content extraction based on Semantic Web technologiesLegislative document content extraction based on Semantic Web technologies
Legislative document content extraction based on Semantic Web technologies
 
Introducción a la Web Semántica
Introducción a la Web SemánticaIntroducción a la Web Semántica
Introducción a la Web Semántica
 
2017 Tendencias en informática
2017 Tendencias en informática2017 Tendencias en informática
2017 Tendencias en informática
 
19 javascript servidor
19 javascript servidor19 javascript servidor
19 javascript servidor
 
Como publicar datos: hacia los datos abiertos enlazados
Como publicar datos: hacia los datos abiertos enlazadosComo publicar datos: hacia los datos abiertos enlazados
Como publicar datos: hacia los datos abiertos enlazados
 
16 Alternativas XML
16 Alternativas XML16 Alternativas XML
16 Alternativas XML
 
XSLT
XSLTXSLT
XSLT
 
XPath
XPathXPath
XPath
 
Arquitectura de la Web y Computación en el Servidor
Arquitectura de la Web y Computación en el ServidorArquitectura de la Web y Computación en el Servidor
Arquitectura de la Web y Computación en el Servidor
 
RDF data model
RDF data modelRDF data model
RDF data model
 
Máster en Ingeniería Web
Máster en Ingeniería WebMáster en Ingeniería Web
Máster en Ingeniería Web
 
2016 temuco tecnologias_websemantica
2016 temuco tecnologias_websemantica2016 temuco tecnologias_websemantica
2016 temuco tecnologias_websemantica
 
2015 bogota datos_enlazados
2015 bogota datos_enlazados2015 bogota datos_enlazados
2015 bogota datos_enlazados
 
17 computacion servidor
17 computacion servidor17 computacion servidor
17 computacion servidor
 
Tecnologias Web Semantica
Tecnologias Web SemanticaTecnologias Web Semantica
Tecnologias Web Semantica
 
6 Principios de Programación Orientada a Objetos
6 Principios de Programación Orientada a Objetos6 Principios de Programación Orientada a Objetos
6 Principios de Programación Orientada a Objetos
 

Recently uploaded

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 

Recently uploaded (20)

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 

Introduction to SPARQL

  • 1. SPARQL Departamento de Informática Universidad de Oviedo Jose Emilio Labra Gayo
  • 2. Jose Emilio Labra Gayo – Universidad de Oviedo SPARQL SPARQL (April 2006) query language for RDF data Similar to SQL, but for RDF Based on graph patterns It also describes a REST protocol SPARQL = SPARQL Protocol And RDF Query Language SPARQL 1.1 (2013, recommendation) Updates, federated queries, etc.
  • 3. Jose Emilio Labra Gayo – Universidad de Oviedo SPARQL Syntax Similar to Turtle URIs between <...> <http://www.example.org/alice> Namespace prefixes as in Turtle prefix dc: <http://purl.org/dc/terms/> dc:creator Blank nodes _:node or between square brackets [ ] Literals between " " "Alice" "234"^^xsd:integer Comments start by # # this is a comment Variables start by? ?name
  • 4. Jose Emilio Labra Gayo – Universidad de Oviedo RDF RDF = Graph model Different syntaxes: N-Triples, Turtle, RDF/XML @prefix dc: <http://purl.org/dc/terms/> . @prefix uni: <http://uniovi.es/> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . uni:biology dc:creator uni:bob . uni:biology dc:creator uni:alice . uni:chemistry dc:creator uni:alice . uni:chemistry dc:creator uni:carol . uni:law dc:creator uni:carol . uni:alice rdf:type uni:Lecturer . uni:bob rdf:type uni:Lecturer . uni:carol rdf:type uni:Student . data.ttl
  • 5. Jose Emilio Labra Gayo – Universidad de Oviedo @prefix dc: <http://purl.org/dc/terms/> . @prefix uni: <http://uniovi.es/> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . uni:biology dc:creator uni:bob . uni:biology dc:creator uni:alice . uni:chemistry dc:creator uni:alice . uni:chemistry dc:creator uni:carol . uni:law dc:creator uni:carol . uni:alice rdf:type uni:Lecturer . uni:bob rdf:type uni:Lecturer . uni:carol rdf:type uni:Student . RDF data RDF graph uni:chemistry uni:alice dc:creator uni:carol dc:creator uni:Student rdf:type uni:biology uni:bob dc:creator dc:creator uni:Lecturer rdf:type rdf:type uni:law dc:creator data.ttl
  • 6. Jose Emilio Labra Gayo – Universidad de Oviedo Simple SPARQL query Search resources created by a Lecturer and order them by lecturer prefix dc: <http://purl.org/dc/terms/> prefix uni: <http://uniovi.es/> prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT ?p ?c WHERE { ?p dc:creator ?c . ?c rdf:type uni:Lecturer . } ORDER BY ?c
  • 7. Jose Emilio Labra Gayo – Universidad de Oviedo SELECT ?p ?c WHERE { ?p dc:creator ?c . ?c rdf:type uni:Lecturer . } ORDER BY ?c uni:chemistry uni:alicedc:creator uni:carol dc:creator uni:Student rdf:type uni:biology uni:bob dc:creator dc:creator uni:Lecturer rdf:type rdf:type uni:law dc:creator Graph patterns ?p dc:creator ?c uni:Lecturer rdf:type ?p ?c Results ?p ?c uni:biology uni:bob uni:chemistry uni:alice uni:biology uni:alice ?p ?c ?p ?c uni:biology uni:alice uni:chemistry uni:alice uni:biology uni:bob sorted by ?c Try it: https://goo.gl/fJuUBn
  • 8. Jose Emilio Labra Gayo – Universidad de Oviedo Playing with SPARQL Command line tools: Apache Jena. https://jena.apache.org/ Online: SHACLex: can be used without endpoint http://shaclex.herokuapp.com/ YASGUI: can be used to query existing SPARQL endpoints http://yasgui.org/ Creating SPARQL endpoints Apache Jena Fuseki: https://jena.apache.org/ Blazegraph: https://www.blazegraph.com/
  • 9. Jose Emilio Labra Gayo – Universidad de Oviedo Some public SPARQL endpoints Name URL Description SPARQLer http://www.sparql.org/sparql.html General purpose query endpoint DBpedia http://dbpedia.org/sparql RDF data from wikipedia Wikidata https://query.wikidata.org/ RDF data from Wikipedia DBLP http://dblp.rkbexplorer.com/sparql/ Bibliographic data LinkedMDB http://data.linkedmdb.org/sparql Movie database bio2rdf http://bio2rdf.org/sparql Linked data for life sciences List of SPARQL endpoints: https://www.w3.org/wiki/SparqlEndpoints
  • 10. Jose Emilio Labra Gayo – Universidad de Oviedo SPARQL query language
  • 11. Jose Emilio Labra Gayo – Universidad de Oviedo Parts of a query prefix dc: <...> prefix uni: <...> SELECT ... FROM <...> FROM NAMED <...> WHERE { ... } ORDER BY ... HAVING ... GROUP BY ... LIMIT ... OFFSET ... BINDINGS ... Graph Pattern Query modifiers Prefix declarations Define dataset Declare type of query SELECT, ASK, DESCRIBE, CONSTRUCT
  • 12. Jose Emilio Labra Gayo – Universidad de Oviedo Prefix declarations Similar to Turtle No need to use @prefix, just prefix No need to end prefix declarations by dot Common aliases used in these slides: alias... stands for... rdf <http://www.w3.org/1999/02/22-rdf-syntax-ns#> rdfs <http://www.w3.org/2000/01/rdf-schema#> owl <http://www.w3.org/2002/07/owl#> xsd <http://www.w3.org/2001/XMLSchema#> schema <http://schema.org/> Other common prefixes can be found at: http://prefix.cc
  • 13. Jose Emilio Labra Gayo – Universidad de Oviedo Parts of a query prefix dc: <...> prefix uni: <...> SELECT ... FROM <...> FROM NAMED <...> WHERE { ... } ORDER BY ... HAVING ... GROUP BY ... LIMIT ... OFFSET ... BINDINGS ... Declare type of query SELECT, ASK, DESCRIBE, CONSTRUCT Graph Pattern Query modifiers Prefix declarations Define dataset
  • 14. Jose Emilio Labra Gayo – Universidad de Oviedo Types of SPARQL queries SELECT return values of variables or expressions Results are a table of values Can have several serializations: XML, JSON ASK return true/false DESCRIBE return a description of a resource CONSTRUCT queries can build RDF triples/graphs
  • 15. Jose Emilio Labra Gayo – Universidad de Oviedo SELECT queries @prefix : <http://example.org/>. :alice :name "Alice" ; :age 31 . :bob :name "Robert" ; :age 31 . SELECT ?n (?age + 1 as ?newAge) WHERE { ?x :name ?n ; :age ?age } Project out specific variables or expressions --------------------- | n | newAge | ===================== | "Alice" | 32 | | "Robert" | 32 | --------------------- SELECT * WHERE { ?x :name ?n ; :age ?age } Project out all variables --------------------------- | x | n | age | =========================== | :alice | "Alice" | 31 | | :bob | "Robert" | 31 | --------------------------- Project out distinct combinations only SELECT DISTINCT ?age WHERE { ?x :name ?n ; :age ?age } ------- | age | ======= | 31 | -------
  • 16. Jose Emilio Labra Gayo – Universidad de Oviedo CONSTRUCT queries Construct an RDF result Can be used to transform RDF data @prefix : <http://example.org/>. :alice :name "Alice" ; :age 31 . :bob :name "Robert" ; :age 31 . PREFIX : <http://example.org/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> CONSTRUCT { ?x foaf:name ?name ; foaf:age ?age } where { ?x :name ?name ; :age ?age } @prefix : <http://example.org/> . @prefix foaf: <http://xmlns.com/foaf/0.1/> . :alice foaf:age 31 ; foaf:name "Alice" . :bob foaf:age 31 ; foaf:name "Robert" . Result
  • 17. Jose Emilio Labra Gayo – Universidad de Oviedo ASK queries ASK return yes or no Can be used to check errors Yes @prefix : <http://example.org/>. :alice :name "Alice" ; :age 31 . :bob :name "Robert" ; :age 31 . PREFIX : <http://example.org/> ASK WHERE { ?x :age ?age FILTER (?age > 18) } Result
  • 18. Jose Emilio Labra Gayo – Universidad de Oviedo DESCRIBE Return a description of one or more nodes @prefix : <http://example.org/> . :alice :age 31 ; :name "Alice" . PREFIX : <http://example.org/> DESCRIBE ?x WHERE { ?x :name "Alice" . } @prefix : <http://example.org/>. :alice :name "Alice" ; :age 31 . :bob :name "Robert" ; :age 31 . Result
  • 19. Jose Emilio Labra Gayo – Universidad de Oviedo Parts of a query prefix dc: <...> prefix uni: <...> SELECT ... FROM <...> FROM NAMED <...> WHERE { ... } ORDER BY ... HAVING ... GROUP BY ... LIMIT ... OFFSET ... BINDINGS ... Graph Pattern Query modifiers Prefix declarations Define dataset Declare type of query SELECT, ASK, DESCRIBE, CONSTRUCT
  • 20. Jose Emilio Labra Gayo – Universidad de Oviedo Define dataset using FROM FROM declares the URL from which the data is queried PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?n FROM <http://www.di.uniovi.es/~labra/labraFoaf.rdf> WHERE { ?x foaf:name ?n } If several data graphs are declared, they are merged PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?n FROM <http://www.di.uniovi.es/~labra/labraFoaf.rdf> FROM <http://www.w3.org/People/Berners-Lee/card> WHERE { ?x foaf:name ?n } ----------------------------------- | n | =================================== | "Jose Manuel Alonso Cienfuegos" | | "Timothy Berners-Lee" | | "Ivan Herman" | | "Jose Emilio Labra Gayo" | ----------------------------------- ----------------------------------- | n | =================================== | "Jose Manuel Alonso Cienfuegos" | | "Ivan Herman" | | "Jose Emilio Labra Gayo" | -----------------------------------
  • 21. Jose Emilio Labra Gayo – Universidad de Oviedo Named graphs FROM NAMED asigns a name to the input graph GRAPH matches with the corresponding graph name PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?n ?g FROM NAMED <http://www.w3.org/People/Berners-Lee/card> FROM NAMED <http://www.di.uniovi.es/~labra/labraFoaf.rdf> WHERE { GRAPH ?g { ?x foaf:name ?n } } ------------------------------------------------------------------------------------ | n | g | ==================================================================================== | "Ivan Herman" | <http://www.di.uniovi.es/~labra/labraFoaf.rdf> | | "Jose Manuel Alonso Cienfuegos" | <http://www.di.uniovi.es/~labra/labraFoaf.rdf> | | "Jose Emilio Labra Gayo" | <http://www.di.uniovi.es/~labra/labraFoaf.rdf> | | "Timothy Berners-Lee" | <http://www.w3.org/People/Berners-Lee/card> | ------------------------------------------------------------------------------------
  • 22. Jose Emilio Labra Gayo – Universidad de Oviedo Parts of a query prefix dc: <...> prefix uni: <...> SELECT ... FROM <...> FROM NAMED <...> WHERE { ... } ORDER BY ... HAVING ... GROUP BY ... LIMIT ... OFFSET ... BINDINGS ... Graph Pattern Query modifiers Prefix declarations Define dataset Declare type of query SELECT, ASK, DESCRIBE, CONSTRUCT
  • 23. Jose Emilio Labra Gayo – Universidad de Oviedo Query patterns Query patterns are made from triple patterns Triple pattern = RDF triples which can contain variables Examples of triple patterns uni:biology dc:creator ?c resources that are dc:creator's of uni:biology ?r dc:creator :alice resources whose dc:creator is :alice ?r dc:creator ?c all resources related by dc:creator property uni:biology ?p :alice properties that relate uni:biology with :alice ?x ?p ?y all statements
  • 24. Jose Emilio Labra Gayo – Universidad de Oviedo Basic graph patterns Basic graph pattern = sequence of triple patterns The matching process combines the values of variables Example: The values of variables must be the same in the results SELECT ?p ?c WHERE { ?p dc:creator ?c . ?c rdf:type uni:Lecturer . } ORDER BY ?c
  • 25. Jose Emilio Labra Gayo – Universidad de Oviedo Basic graph patterns can have filters FILTER limits the set of returned values PREFIX : <http://example.org/> SELECT ?n ?e WHERE { ?x :name ?n . ?x :age ?e FILTER (?e > 18) } @prefix : <http://example.org/>. :alice :name "Alice" . :alice :age 31 . :bob :name "Robert" . :bob :age 12 . :carol :name "Carol" . :carol :age 25 . | n | e | ================= | "Carol" | 25 | | "Alice" | 31 | Try it: https://tinyurl.com/y8odenvm
  • 26. Jose Emilio Labra Gayo – Universidad de Oviedo Filter operators FILTER uses XPath 2.0 functions and operators Datatypes: Boolean, Integer, Float, dataTime, etc. Typical operators: >, <, >=, <=, =, !=, ||, && PREFIX : <http://example.org/> SELECT ?n ?e WHERE { ?x :name ?n . ?x :age ?e FILTER (?e > 30 || ?e < 18) } Try it: https://tinyurl.com/yavd6bww
  • 27. Jose Emilio Labra Gayo – Universidad de Oviedo Convert/create datatypes str(arg): converts its argument to a string NOTE: URIs must be converted to strings to treat them as such datatype(arg): returns datatype of a literal IF ?x = "123"^^xsd:integer THEN datatype(?x) = xsd:integer lang(arg): returns the language of a literal IF ?x = "University"@en THEN: lang(?x) = "en" prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?label WHERE { ?x rdfs:label ?label . FILTER (lang(?label) ="en") } Example Try it: https://tinyurl.com/y8m3xlyg
  • 28. Jose Emilio Labra Gayo – Universidad de Oviedo Create datatypes uri(arg), iri(arg): convert their argument to URI/IRI bnode(arg): generates a blank node strdt(literal,datatype): generates a literal with a datatype strdt("123","xsd:integer") = "123"^^<xsd:integer> strlang(literal,lang): generates a literal with some language strlang("University","en") = "University"@"en"
  • 29. Jose Emilio Labra Gayo – Universidad de Oviedo Check datatypes isNumeric(arg) = true if the argument is a number isBlank(arg) = true if the argumento is a blank node isLiteral(arg) = true if the argument is a literal isIRI(arg) = true if the argument is an IRI
  • 30. Jose Emilio Labra Gayo – Universidad de Oviedo Conditions bound(arg) = true if the argument has a value exists(pattern) = true if the pattern is satisfied not exists(pattern) = true si if the pattern is not satisfied if(cond,expr1,expr2) = if cond = true, returns expr1, otherwise, returns expr2 coalesce(e1,e2,...) = returns the first expression that is evaluated without error
  • 31. Jose Emilio Labra Gayo – Universidad de Oviedo Examples Filter numeric values PREFIX : <http://example.org/> SELECT ?age WHERE { ?x :age ?age . FILTER (isNumeric(?age)) } @prefix : <http://example.org/> . :carol :age 34 ; :name "Carol" . :alice :age 23 ; :name "Alice" . :bob :age "Unknown" ; :name "Robert" . ------- | age | ======= | 34 | | 23 | ------- Try it: https://tinyurl.com/yan74uwt
  • 32. Jose Emilio Labra Gayo – Universidad de Oviedo Functions with strings strlen(str) = length of str ucase(str) converts to uppercase lcase(str) converts to lowercase substr(str,start,size?)= substring from start with some size substr('camino',3,2)='mi' strstarts(str1,str2) = true if str1 starts with str2 strends(str1,str2) = true if str1 ends with str2 contains(str1,str2) = true if str1 contains str2 encode_for_uri(str) = result of encoding str as a uri concat(str1,...strN) = concatenates strings langMatches(str,lang) = true if a string matches some language lang regex(str,p,flags) = true if string matches regular expression p with flags
  • 33. Jose Emilio Labra Gayo – Universidad de Oviedo Examples with strings @prefix : <http://example.org/> . :alice :firstName "Alice" ; :lastName "Cooper" . :bob :firstName "Robert" ; :lastName "Smith" . :carol :firstName "Carol" ; :lastName "King" . Try it: https://tinyurl.com/yd3p2l43 PREFIX : <http://example.org/> SELECT (concat(?firstName,' ',?lastName) AS ?name) WHERE { ?x :firstName ?firstName . ?x :lastName ?lastName . FILTER (contains(ucase(?firstName),'A')) } ------------------ | name | ================== | "Alice Cooper" | | "Carol King" | ------------------
  • 34. Jose Emilio Labra Gayo – Universidad de Oviedo Regex REGEX invokes regular expression matching It is based on XPath 2.0 functions regex(?Expr, ?Pattern [, ?Flags]) ?Expr = expression to match ?Pattern = regular expression pattern ?Flags = matching options Try it: https://tinyurl.com/yd29xsyz @prefix : <http://example.org/>. :alice :firstName "Alice" ; :lastName "Cooper" . :bob :firstName "Robert" ; :lastName "Smith" . :carol :firstName "Carol" ; :lastName "King" . PREFIX : <http://example.org/> SELECT ?firstName WHERE { ?x :firstName ?firstName . FILTER (regex(?firstName,"^[ABC](.*)")) } ------------- | firstName | ============= | "Alice" | | "Carol" | -------------
  • 35. Jose Emilio Labra Gayo – Universidad de Oviedo Regex Regular expressions ^ = start of string $ = end of string . = any character d = dígit ? = optional, * = 0 or more, + = 1 or more X{n} = matches X n times X{m,n} = matches X from m to n times Flags: i = ignore case m = multiple lines s = simple line x = removes white spaces
  • 36. Jose Emilio Labra Gayo – Universidad de Oviedo Numeric functions abs(n) = absolute value round(n) = rounds a number n floor(n) = rounds n down ceil(n) = rounds n up rand() = random number between 0 y 1
  • 37. Jose Emilio Labra Gayo – Universidad de Oviedo Functions with dates now() = returns current instant year(i) = returns the year of some instant i year("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) = 2011 month(i), day(i), hours(i), minutes(i), seconds(i), timezone(i), tz(i) = similar but return other components @prefix : <http://example.org/> . :alice :age 23 ; :name "Alice" . :bob :age 20 ; :name "Robert" . PREFIX : <http://example.org/> SELECT (year(now()) - ?age as ?birthYear) WHERE { ?x :age ?age . } ------------- | birthYear | ============= | 1994 | | 1997 | -------------
  • 38. Jose Emilio Labra Gayo – Universidad de Oviedo HASH functions md5(str) = applies MD5 algorithm to a str sha1(str), sha224(str),sha256(str),sha384(str), sha512(str) = compute hash of str using the corresponding variations of SHA algorithm PREFIX : <http://example.org/> SELECT ?name (SHA1(?email) AS ?sha1Email) WHERE { ?x :name ?name . ?x :email ?email . } @prefix : <http://example.org/> . :alice :name "Alice" ; :email "alice@email.com" . :bob :name "Robert" ; :email "bob@example.com" . --------------------------------------------------------- | name | sha1Email | ========================================================= | "Alice" | "14bf670833d4d7daca31afce1011752c80691459" | | "Robert" | "a460e37bf4d8e893f8fd39536997d5da8d21eebe" | ---------------------------------------------------------
  • 39. Jose Emilio Labra Gayo – Universidad de Oviedo @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23 . :bob :firstName "Robert" ; :age 20 . Graph union UNION combines results from several graphs PREFIX : <http://example.org/> SELECT ?n WHERE { { ?x :name ?n } UNION { ?y :firstName ?n } } ------------ | n | ============ | "Alice" | | "Robert" | ------------
  • 40. Jose Emilio Labra Gayo – Universidad de Oviedo Optional OPTIONAL allows to define triples which match information if exists, but don't fail if it doesn't exist @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23 . :bob :name "Robert" . :carol :name "Carol" ; :age 33 . PREFIX : <http://example.org/> SELECT ?name ?age WHERE { ?x :name ?name . ?x :age ?age } PREFIX : <http://example.org/> SELECT ?name ?age WHERE { ?x :name ?name OPTIONAL { ?x :age ?age } } ----------------- | name | age | ================= | "Alice" | 23 | | "Carol" | 33 | ----------------- ------------------ | name | age | ================== | "Alice" | 23 | | "Robert" | | | "Carol" | 33 | ------------------ without optional with optional
  • 41. Jose Emilio Labra Gayo – Universidad de Oviedo Minus Removes solutions that are compatible with a pattern @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23 . :bob :name "Robert" . :carol :name "Carol" ; :age 33 . prefix : <http://example.org/> SELECT ?name WHERE { ?x :name ?name MINUS { ?x :age 33 } } ------------ | name | ============ | "Alice" | | "Robert" | ------------
  • 42. Jose Emilio Labra Gayo – Universidad de Oviedo Parts of a query prefix dc: <...> prefix uni: <...> SELECT ... FROM <...> FROM NAMED <...> WHERE { ... } ORDER BY ... HAVING ... GROUP BY ... LIMIT ... OFFSET ... BINDINGS ... Graph Pattern Query modifiers Prefix declarations Define dataset Declare type of query SELECT, ASK, DESCRIBE, CONSTRUCT
  • 43. Jose Emilio Labra Gayo – Universidad de Oviedo Query modifiers DISTINCT removes duplicate results ORDER BY specifies the order of results (ASC, DESC…) LIMIT n limits the number of results OFFSET m declares from which result to start PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT DISTINCT ?n WHERE { ?x foaf:knows ?y . ?y foaf:name ?n . } ORDER BY ASC(?n) LIMIT 5 OFFSET 2
  • 44. Jose Emilio Labra Gayo – Universidad de Oviedo Bindings BIND expr AS v = Asigns value of expr to variable v @prefix : <http://example.org/>. :apples :name "Apples" ; :amount 3 ; :price 3 . :oranges :name "Oranges" ; :amount 4 ; :price 2 . prefix : <http://example.org/> SELECT ?name ?totalPrice WHERE { ?x :name ?name ; :amount ?amount ; :price ?price . BIND ((?amount * ?price) AS ?totalPrice) } -------------------------- | name | totalPrice | ========================== | "Oranges" | 8 | | "Apples" | 9 | --------------------------
  • 45. Jose Emilio Labra Gayo – Universidad de Oviedo Bindings in SELECT clause It is possible to do the binding directly in the SELECT @prefix : <http://example.org/>. :apples :name "Apples" ; :amount 3 ; :price 3 . :oranges :name "Oranges" ; :amount 4 ; :price 2 . prefix : <http://example.org/> SELECT ?name ((?amount * ?price) AS ?totalPrice) WHERE { ?x :name ?name ; :amount ?amount ; :price ?price . } -------------------------- | name | totalPrice | ========================== | "Oranges" | 8 | | "Apples" | 9 | --------------------------
  • 46. Jose Emilio Labra Gayo – Universidad de Oviedo Aggregation functions: AVG, SUM, COUNT, SAMPLE @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23 . :bob :name "Robert" ; :age 25 . :carol :name "Carol" ; :age 33 . PREFIX : <http://example.org/> SELECT (AVG(?age) AS ?average) (SUM(?age) AS ?sum) (COUNT(?age) AS ?count) (SAMPLE(?age) AS ?sample) WHERE { ?x :age ?age . } ---------------------------------- | average | sum | count | sample | ================================== | 27.0 | 81 | 3 | 23 | ----------------------------------
  • 47. Jose Emilio Labra Gayo – Universidad de Oviedo Aggregation functions: MAX, MIN @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23 . :bob :name "Robert" ; :age 25 . :carol :name "Carol" ; :age 33 . PREFIX : <http://example.org/> SELECT (MAX(?age) AS ?max) (MIN(?age) AS ?min) WHERE { ?x :age ?age . } ----------------- | max | min | ================= | 33 | 23 | -----------------
  • 48. Jose Emilio Labra Gayo – Universidad de Oviedo Aggregation functions GROUP_CONCAT prefix : <http://example.org/> SELECT (GROUP_CONCAT(?age; SEPARATOR=',') as ?ages) where { ?x :age ?age . } -------------- | ages | ============== | "23,33,25" | -------------- @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23 . :bob :name "Robert" ; :age 25 . :carol :name "Carol" ; :age 33 .
  • 49. Jose Emilio Labra Gayo – Universidad de Oviedo Groupings: GROUP_BY GROUP BY groups sets of results @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23; :salary 1200 . :bob :name "Robert" ; :age 25 ; :salary 1500 . :carol :name "Carol" ; :age 23 ; :salary 2000 . :dave :name "Dave" ; :age 25 ; :salary 2500 . prefix : <http://example.org/> SELECT (AVG(?salary) AS ?avgSalary) ?age WHERE { ?x :age ?age ; :salary ?salary . } GROUP BY ?age ------------------- | avgSalary | age | =================== | 1600.0 | 23 | | 2000.0 | 25 | -------------------
  • 50. Jose Emilio Labra Gayo – Universidad de Oviedo Groupings: HAVING HAVING flters the groups that pass some condition ------------------- | avgSalary | age | =================== | 2000.0 | 25 | ------------------- @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23; :salary 1200 . :bob :name "Robert" ; :age 25 ; :salary 1500 . :carol :name "Carol" ; :age 23 ; :salary 2000 . :dave :name "Dave" ; :age 25 ; :salary 2500 . prefix : <http://example.org/> SELECT (AVG(?salary) AS ?avgSalary) ?age WHERE { ?x :age ?age ; :salary ?salary . } GROUP BY ?age HAVING (?avgSalary > 1800)
  • 51. Jose Emilio Labra Gayo – Universidad de Oviedo Subqueries It is possible to define queries inside queries @prefix : <http://example.org/>. :alice :name "Alice" ; :age 23; :salary 1200 . :bob :name "Robert" ; :age 25 ; :salary 1500 . :carol :name "Carol" ; :age 23 ; :salary 2000 . :dave :name "Dave" ; :age 25 ; :salary 2500 . prefix : <http://example.org/> SELECT ?name ?salary (?salary - ?avgSalary AS ?deviation) WHERE { ?x :name ?name . ?x :salary ?salary . { SELECT (AVG(?salary) AS ?avgSalary) WHERE { ?x :salary ?salary . } } } --------------------------------- | name | salary | deviation | ================================= | "Carol" | 2000 | 200.0 | | "Alice" | 1200 | -600.0 | | "Dave" | 2500 | 700.0 | | "Robert" | 1500 | -300.0 | ---------------------------------
  • 52. Jose Emilio Labra Gayo – Universidad de Oviedo Property paths Properties can use a path (similar to regular expressions) p Match property p (e) Path grouped in parenthesis ^e Inverse path e !p Doesn't match property p e1 / e2 Path e1 followed by e2 e1 | e2 Path e1 or e2 e* 0 or more e e+ 1 or more e e? 0 or 1 e
  • 53. Jose Emilio Labra Gayo – Universidad de Oviedo @prefix : <http://example.org/>. @prefix foaf: <http://xmlns.com/foaf/0.1/>. :alice :name "Alice" ; foaf:knows :bob, :carol . :bob foaf:name "Robert"; foaf:knows :carol . :carol foaf:name "Carol" ; foaf:knows :alice . Property paths prefix : <http://example.org/> prefix foaf: <http://xmlns.com/foaf/0.1/> SELECT ?name ?friend WHERE { ?x (foaf:name | :name) ?name ; foaf:knows / (foaf:name | :name) ?friend } ----------------------- | name | friend | ======================= | "Alice" | "Carol" | | "Alice" | "Robert" | | "Robert" | "Carol" | | "Carol" | "Alice" | -----------------------
  • 54. Jose Emilio Labra Gayo – Universidad de Oviedo Property paths @prefix : <http://example.org/>. @prefix foaf: <http://xmlns.com/foaf/0.1/>. :isabelle foaf:knows :frank, :grace . :frank foaf:knows :carol, :emily . :grace foaf:knows :carol, :emily . :carol foaf:knows :alice . :emily foaf:knows :alice . :heidi foaf:knows :dave . :dave foaf:knows :bob . :bob foaf:knows :alice . prefix : <http://example.org/> prefix foaf: <http://xmlns.com/foaf/0.1/> SELECT ?p { ?p foaf:knows+ :alice . } ------------- | p | ============= | :carol | | :grace | | :isabelle | | :frank | | :emily | | :bob | | :dave | | :heidi | ------------- Alice Bob Carol Emily Dave Frank Grace Heidi Isabelle
  • 55. Jose Emilio Labra Gayo – Universidad de Oviedo Property paths @prefix : <http://example.org/>. @prefix foaf: <http://xmlns.com/foaf/0.1/>. :isabelle foaf:knows :frank, :grace . :frank foaf:knows :carol, :emily . :grace foaf:knows :carol, :emily . :carol foaf:knows :alice . :emily foaf:knows :alice . :heidi foaf:knows :dave . :dave foaf:knows :bob . :bob foaf:knows :alice . Alice Bob Carol Emily Dave Frank Grace Heidi Isabelle prefix : <http://example.org/> prefix foaf: <http://xmlns.com/foaf/0.1/> SELECT ?p { ?p foaf:knows/foaf:knows :alice . } ---------- | p | ========== | :grace | | :frank | | :grace | | :frank | | :dave | ----------
  • 56. Jose Emilio Labra Gayo – Universidad de Oviedo Property paths @prefix : <http://example.org/>. @prefix foaf: <http://xmlns.com/foaf/0.1/>. :isabelle foaf:knows :frank, :grace . :frank foaf:knows :carol, :emily . :grace foaf:knows :carol, :emily . :carol foaf:knows :alice . :emily foaf:knows :alice . :heidi foaf:knows :dave . :dave foaf:knows :bob . :bob foaf:knows :alice . Alice Bob Carol Emily Dave Frank Grace Heidi Isabelle prefix : <http://example.org/> prefix foaf: <http://xmlns.com/foaf/0.1/> SELECT ?p { ?p foaf:knows/^foaf:knows :frank . } ---------- | p | ========== | :grace | | :frank | | :grace | | :frank | ----------
  • 57. Jose Emilio Labra Gayo – Universidad de Oviedo SPARQL Update
  • 58. Jose Emilio Labra Gayo – Universidad de Oviedo Graph operations Update INSERT DATA = insert triples DELETE/INSERT… = delete/insert triples conditionally DELETE DATA = delete triples LOAD = load triples from a uri CLEAR = delete all triples from a graph Graph management CREATE = create named graph DROP = drop graph COPY…TO… = copy graph MOVE…TO… = move graph ADD = insert all elements from a graph in another one
  • 59. Jose Emilio Labra Gayo – Universidad de Oviedo Insert INSERT DATA can be used to insert triples prefix : <http://example.org/>. prefix foaf: <http://xmlns.com/foaf/0.1/>. INSERT DATA { :ana foaf:name "Ana" ; foaf:age 18 ; :salary 1500 . :bob foaf:name "Robert" ; foaf:age 20 ; :salary 2000 . }
  • 60. Jose Emilio Labra Gayo – Universidad de Oviedo Insert in a graph INSERT DATA into a named graph prefix : <http://example.org/> prefix foaf: <http://xmlns.com/foaf/0.1/> INSERT DATA { GRAPH <http://example.org/graph1> { :alice foaf:name "Alice" ; foaf:age 18 ; :salary 1500 . } }
  • 61. Jose Emilio Labra Gayo – Universidad de Oviedo Insert INSERT can insert triples in a graph Requires the WHERE clause PREFIX : <http://example.org/> INSERT { ?p :value "GoodSalary". } WHERE { ?p :salary ?salary . FILTER (?salary >= 4000) }
  • 62. Jose Emilio Labra Gayo – Universidad de Oviedo Graph load LOAD uri = loads all triples from a graph available at uri LOAD <http://www.di.uniovi.es/~labra/labraFoaf.rdf>
  • 63. Jose Emilio Labra Gayo – Universidad de Oviedo Delete data DELETE DATA removes all triples in a graph PREFIX : <http://example/org/> DELETE DATA { :alice :age 18 . } NOTA: DELETE DATA does not allow variables
  • 64. Jose Emilio Labra Gayo – Universidad de Oviedo Delete...where DELETE WHERE removes triples in a graph specifying a condition PREFIX : <http://example.org/> DELETE { ?x :age ?age . } WHERE { ?x :age ?age . FILTER (?age >= 60) }
  • 65. Jose Emilio Labra Gayo – Universidad de Oviedo Updating information DELETE/INSERT pattern can be used to update triples in a graph PREFIX : <http://example.org/> DELETE { ?x :age ?age } INSERT { ?x :age ?newAge } WHERE { ?x :age ?age . BIND((?age + 1) AS ?newAge) } Example: increment age
  • 66. Jose Emilio Labra Gayo – Universidad de Oviedo Deleting CLEAR deletes all triples It is possible to declare datasets CLEAR g = Deletes graph g CLEAR DEFAULT = Deletes default graph CLEAR ALL = Deletes all graphs
  • 67. Jose Emilio Labra Gayo – Universidad de Oviedo Universal query Obtain all triples in all graphs PREFIX e: <http://ejemplo.org#> SELECT * WHERE { { ?x ?p ?y . } UNION { GRAPH ?g { ?x ?p ?y . } } }
  • 68. Jose Emilio Labra Gayo – Universidad de Oviedo Remote services SERVICE uri = Runs query from a SPARQL endpoint uri PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?name WHERE { SERVICE <http://dbpedia.org/sparql> { SELECT ?name WHERE { ?pais rdf:type dbo:Country . ?pais rdfs:label ?name . FILTER (lang(?name)='es') } } } Some SPARQL endpoints: http://esw.w3.org/topic/SparqlEndpoints
  • 69. Jose Emilio Labra Gayo – Universidad de Oviedo Federated queries Combine results from several endpoints PREFIX imdb: <http://data.linkedmdb.org/resource/movie/> PREFIX dcterms: <http://purl.org/dc/terms/> PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT * { { SERVICE <http://dbpedia.org/sparql> { SELECT ?spouseName WHERE { ?actor rdfs:label "Javier Bardem"@en ; dbo:spouse ?spouse . ?spouse rdfs:label ?spouseName . FILTER ( lang(?spouseName) = "en" ) } } } { SERVICE <http://data.linkedmdb.org/sparql> { SELECT ?movieName ?movieDate WHERE { ?actor imdb:actor_name "Javier Bardem". ?movie imdb:actor ?actor ; dcterms:title ?movieName ; dcterms:date ?movieDate . } } } } DBPedia: http://dbpedia.org IMDB: http://data.linkedmdb.org
  • 70. Jose Emilio Labra Gayo – Universidad de Oviedo SPARQL Protocol
  • 71. Jose Emilio Labra Gayo – Universidad de Oviedo SPARQL Protocol Defines the actions: query and update and their parameters and their formats query action 2 verbs: GET, POST Parameters: query: Encoded query default-graph-uri: Default graph (optional) named-graph-uri: Named graph (optional) update action Only POST with 3 parameters update: Update query using-graph-uri: Default graph (optional) using-named-graph-uri: Named graph (optional)
  • 72. Jose Emilio Labra Gayo – Universidad de Oviedo Validating RDF using SPARQL?
  • 73. Jose Emilio Labra Gayo – Universidad de Oviedo Negation by failure pattern in SPARQL Combining FILTER, OPTIONAL and !BOUND Example: Search people not married @prefix : <http://example.org/>. :alice :isMarriedWith :Bob ; :name "Alice" . :bob :isMarriedWith :alice ; :name "Robert" . :carol :name "Carol" . :dave :isMarriedWith :emily ; :name "Dave" . PREFIX : <http://example.org/> SELECT ?n WHERE { ?x :name ?n OPTIONAL {?x :isMarriedWith ?y } FILTER ( !BOUND(?y) ) } Does it really return people not married? ----------- | n | =========== | "Carol" | -----------
  • 74. Jose Emilio Labra Gayo – Universidad de Oviedo Validating RDF with SPARQL Example: A person has age (integer) and one or more names (string) Person__ foaf:age xsd:integer foaf:name xsd:string+ :john foaf:age 23; foaf:name "John" . :bob foaf:age 34; foaf:name "Bob", "Robert" .  RDF examples :mary foaf:age 50, 65 .
  • 75. Jose Emilio Labra Gayo – Universidad de Oviedo Example of SPARQL query ASK { { SELECT ?Person { ?Person foaf:age ?o . } GROUP BY ?Person HAVING (COUNT(*)=1) } { SELECT ?Person { ?Person foaf:age ?o . FILTER ( isLiteral(?o) && datatype(?o) = xsd:integer ) } GROUP BY ?Person HAVING (COUNT(*)=1) } { SELECT ?Person (COUNT(*) AS ?Person_c0) { ?Person foaf:name ?o . } GROUP BY ?Person HAVING (COUNT(*)>=1) } { SELECT ?Person (COUNT(*) AS ?Person_c1) { ?Person foaf:name ?o . FILTER (isLiteral(?o) && datatype(?o) = xsd:string) } GROUP BY ?Person HAVING (COUNT(*)>=1) } FILTER (?Person_c0 = ?Person_c1) } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Person__ foaf:age xsd:integer foaf:name xsd:string+
  • 76. Jose Emilio Labra Gayo – Universidad de Oviedo Is it possible to add recursión to the model? Example: A person has age (integer), one or more names (string) and knows 0 or more values which conform to person Person__ foaf:age xsd:integer foaf:name xsd:string+ 0..* foaf:knows
  • 77. Jose Emilio Labra Gayo – Universidad de Oviedo Validating RDF technologies ShEx and SHACL can be used to validate RDF <Person> { foaf:age xsd:integer ; foaf:name xsd:string+ foaf:knows @<Person> } Example in ShEx (see http://shex.io)
  • 78. Jose Emilio Labra Gayo – Universidad de Oviedo References SPARQL by example SPARQL by example cheatsheet Learning SPARQL, book by Bob Ducharme SPARQL 1.1 spec