SlideShare a Scribd company logo
SPARQL
Thomas Francart,
Crédits : This work remixes, translates and complete a presentation from Fabien Gandon, INRIA, under an open licence. Thanks to him.
This work is placed under « Attribution ShareAlike 4.0 International ». You are free to share and adapt this work, even for commercial purposes.
You must give appropriate credit, provide a link to the license, and indicate if changes were made. If you remix, transform, or build upon the
material, you must distribute your contributions under the same license as the original. For more information, see the license.
RDF and its triples
is the first level (after URI)
in the standards of the
semantic web
SPARQL
is on top of RDF . It is a query
language and query protocol.
It is the SQL for RDF data.
SPARQL
• Query data
• Traverse graph from heterogeneous sources
• Consistency checking
• Data analytics
• Data management (copy, move, delete, etc.)
• Convert data from one structure to another
• Make some inferences : find new data/relations from
existing data
• Generate exports (tabular or graph)
• Make federated queries (query multiple databases) …
SPARQL limits
• No full-text search indexes (proprietary extensions)
• No geographical indexes (proprietary extensions)
• No query hints to control exécution plan (proprietary
extensions)
• No stored procedures
• No triggers
SPARQL standard has 3 parts
Part 1: query language syntax
Part 2: result format specification
Part 3: query protocol
6
Your first SPARQL
Basic Graph Patterns
Your first SPARQL
PREFIX ...
SELECT ...
WHERE { ... }
PREFIX clause
Declare “shortcuts” for
URIs used inside the
query
SELECT clause
Indicate which values
you want to return (which
columns)
WHERE Clause
The conditions to search
on the graph/the triples in
the RDF data
Triple patterns :
WHERE Clause
{ ?x rdf:type ex:Person .
?x ex:name ?name . }
Example – persons with their names
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person ?name
WHERE {
?person rdf:type ex:Person .
?person ex:name ?name .
}
Patterns with 1 variable
# ?x that are Persons
?x rdf:type foaf:Person .
# ?x that Tom knows
ex:Tom foaf:knows ?x .
# ?x that link Tom and Oliver
ex:Tom ?x ex:Oliver .
Patterns with 2 variables
# ?x and ?y that know each other
?x foaf:knows ?y .
# All verbs and values about Tom
ex:Tom ?x ?y .
# All subject and verbs that link to Tom
?x ?y ex:Tom .
Patterns with 3 variables
… or no variable at all
# Everyting on everything !
# (returns all database)
?x ?y ?z .
# Tom is a Person
ex:Tom rdf:type foaf:Person .
Exemple – same query as before
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person ?name
WHERE {
?person a ex:Person ;
ex:name ?name .
}
Avoid confusion and always write full « sentences » :
- Subject verb complement dot
- Subject verb complement dot
- Subject verb complement dot
- …
Whitespace between subject / predicate / object
No whitespace in a URI or a variable name
Never put whitespace afer or before the “:” in prefixed URIs.
Never put whitespace after the “?” in variables !
If you want, a whitespace before final “.”
Whitespaces
?aPerson rdf:type foaf:Person .
WHERE {
# Don’t use foaf:Person
?person a ex:Person .
}
Comments
Methodology
Write your queries step by step and test at each
step :
• Add a first criteria
• Use LIMIT keyword to avoid too long result sets
• Test
• Add a criteria
• Test
• Add a criteria
• Etc.
Exercise 1 : a first query with a basic graph
patterns
• Write a query that returns…
• All the companies…
• … with their names
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
…
• Company = dbo:Company
• Name = rdfs:label
http://dbpedia.org/sparql
Exercise 1 : a first query with a basic graph
patterns
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?x ?label
WHERE {
?x a dbo:Company .
?x rdfs:label ?label .
}
Methodology
Understanding and mastering the
structure of the underlying RDF
Knowledge Graph is fundamental
to query it in SPARQL.
Methodology
1. Look at notices of entities to understand their
description
In HTML or in RDF
2. And/or read the model documentation
3. And/or look at sample queries provided
4. And/or do SPARQL exploration queries (see annex)
It is possible to discover the graph data model by issuing specific
SPARQL queries
5. Draw graph sketches
Exercise 2 : A basic graph pattern that
traverses the graph
http://dbpedia.org/sparql
• Write a query that returns…
• All the companies with their names…
• … that have been founded by someone …
• … born in a place …
• … that is in the United States
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbr: <http://dbpedia.org/resource/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
• Company = dbo:Company
• Name = rdfs:label
• founded by = dbo:founder
• Born in = dbo:birthPlace
• In country : dbo:country
• United States : dbr:United_States
Exercise 2 : A basic graph pattern that
traverses the graph
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?x ?label
WHERE {
?x a dbo:Company .
?x rdfs:label ?label .
?x dbo:owner ?owner .
?owner dbo:birthPlace ?somewhere .
?somewhere dbo:country dbr:United_States
}
DISTINCT
SELECT DISTINCT ?x ?y
Deduplicate the result set
Sorting and paging
ORDER BY ?x variable(s) to
order on. Use DESC(?x) to sort from Z-A
LIMIT 100 limit the total size of
result set
OFFSET 10 index of the first result in
total result set
All identical to SQL
Exemple – results 21 to 40 sorted by name
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person ?name
WHERE {
?person rdf:type ex:Person .
?person ex:name ?name .
}
ORDER BY ?name
LIMIT 20
OFFSET 20
Functions and FILTERS
Beyond Basic Graph Patterns
Functions
Functions are applied on variables. They are
used to :
1. FILTER the values of variables we want
FILTER(lang(?x) = "fr")
2. Change the content of a column in the
result set (assignation – see later)
FILTER
Add constraints on the
variables used in the graph
pattern : FILTER(?x > 18)
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person ?name
WHERE {
?person rdf:type ex:Person .
?person ex:name ?name .
?person ex:age ?age .
FILTER (?age > 18)
}
Exemple – person above 18
Mathematical
operators
+, -, *, /, =, !=, >, <, >=, <=
Boolean operators
!, &&, ||
FILTER(
?x = <http://aaa> ||
?x = <http://bbb>
)
Functions on RDF
literals / resources
lang(?x) : language of ?x (« fr »)
str(?x) : string value of ?x (without
language/datatype)
datatype(?x) : datatype of ?x
Exercice 3 : Using FILTER
• Keep only the names of the companies in
English
http://dbpedia.org/sparql
Exercice 3 : Using FILTER
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?x ?label
WHERE {
?x a dbo:Company .
?x rdfs:label ?label .
FILTER(lang(?label) = "en")
}
SELECT (f(?x) AS ?y)
In the SELECT clause, you can
apply a function on a variable
and assign the result to a new
variable with AS.
This is assignation – more on this later
Exercise 4 : Using a function in the SELECT
clause with AS
• We would like to get rid of the « @en » of
the label column in the result set
• Use « str(?label) » in the SELECT clause
to select only the label string without the
language
Exercise 4 : Using a function in the SELECT
clause with AS
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?x (STR(?label) AS ?theLabel)
WHERE {
?x a dbo:Company .
?x rdfs:label ?label .
FILTER(lang(?label) = "en")
}
Functions on RDF
literals / resources
isIRI(?x) : true if ?x is an IRI
isLiteral(?x) : true if ?x is a literal
isBlank(?x) : true if ?x is an
anonymous node
Functions on strings
UCASE(?x) / LCASE(?x) : ?x in upper-case /
lower case
STRLEN(?x) : length of ?x
STRSTARTS(?x, ?y) STRENDS(?x,
?y) CONTAINS(?x, ?y) : test if ?x starts with
/ ends with / contains ?y
STRBEFORE(?x,"foo") /
STRAFTER(?x,"foo") : substring after of
before « foo » in ?x
REPLACE(?x,"http","https") :
replaces « http » with « https » in ?x
Functions on strings
If « test » is true, returns
« then », otherwise returns
« else »
IF(<test>,<then>,<else>)
Combine functions
FILTER(CONTAINS(STR(?x), "foo"))
test if the string value of ?x contains « foo »
Combine functions
FILTER(IF(STRLEN(?name) > 10, BIND(…),
BIND(…)))
FILTER(STRLEN(STRBEFORE(?name, "b")) > 10)
FILTER(
IF(CONTAINS(STRAFTER(LCASE(?name),
"mr."),"tom"),…,…)
)
YEAR(?x) / MONTH(?x) / DAY(?x)
/ HOURS(?x) / MINUTES(?x) /
SECONDS(?x)
Extracts part of a date value
FILTER(YEAR(?x) = 2020)
Functions on dates
IN / NOT IN
IN(…) and NOT IN(…)
FILTER(?x IN (ex:Tom, ex:Oliver,
ex:Franck))
FILTER(?x NOT IN ("a", "b", "c"))
REGEX() function
regex(?x, "^tom", "i")
1. Variable to test
2. Regular expression
3. Options (« i » : case-insensitive)
Starts with « tom » regex(?x, "^tom", "i")
Ends with « tom » regex(?x, "tom$", "i")
Contains a number regex(?x, "[0-9]")
Contains only a number regex(?x, "^[0-9]$")
Contains date in format JJ/MM/AAAA or
JJ-MM-AAAA (with day or month in or or
two caracters)
regex(?x, "[0-9][0-9]?[/-][0-
9][0-9]?[/-][0-9][0-9][0-9][0-
9]")
Starts with http:// or https:// regex(?x, "^https?://[^s]+$")
…
Character Legend Example Sample Match
d
Most engines: one digit
from 0 to 9
file_dd file_25
w
Most engines: "word character": ASCII letter, digit or
underscore
w-www A-b_1
s
Most engines: "whitespace character": space, tab,
newline, carriage return, vertical tab
asbsc
a b
c
D
One character that is not a digit as defined by your
engine's d
DDD ABC
W
One character that is not a word character as defined by
your engine's w
WWWWW *-+=)
S
One character that is not a whitespace character as
defined by your engine's s
SSSS Yoyo
Quantifier Legend Example Sample Match
+ One or more Version w-w+ Version A-b1_1
* Zero or more times A*B*C* AAACC
? Once or none plurals? plural
{3} Exactly three times D{3} ABC
{2,4} Two to four times d{2,4} 156
{3,} Three or more times w{3,} regex_tutorial
Character Legend Example Sample Match
. Any character except line break a.c abc
.
Any character except line break, any number
of times
.* whatever, man.
.
A period (special character: needs to be
escaped by a )
a.c a.c
 Escapes a special character .*+? $^/ .*+? $^/
 Escapes a special character [{()}] [{()}]
Character Legend Example Sample Match
[ … ] One of the characters in the brackets [AEIOU] One uppercase vowel
[ … ] One of the characters in the brackets T[ao]p Tap or Top
- Range indicator [a-z] One lowercase letter
[x-y] One of the characters in the range from x to y [A-Z]+ GREAT
[ … ] One of the characters in the brackets [AB1-5w-z]
One of either:
A,B,1,2,3,4,5,w,x,y,z
[x-y] One of the characters in the range from x to y [ -~]+
Characters in the printable
section of the ASCII table.
[^x] One character that is not x [^a-z]{3} A1!
[^x-y]
One of the characters not in the range from x
to y
[^ -~]+
Characters that are not in the
printable section of the ASCII
table.
Combining Graph
Patterns
Negative patterns / Optional patterns / Union of
patterns
OPTIONAL
Make one or more query
patterns optional
Even if they don’t match, results will still
be returned.
Very useful to build result sets when we
are not 100% all properties exist
Exemple – return age if it is know in the graph
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person ?name ?age
WHERE {
?person rdf:type ex:Person .
?person ex:name ?name .
OPTIONAL { ?person ex:age ?age }
}
Exercise 5 : Making some patterns optional
• Write a query that returns…
• All the companies…
• … with their names
• … and their slogan if they have one !
• Company = dbo:Company
• Name = rdfs:label
• Slogan : dbo:slogan
Exercise 5 : Making some patterns optional
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?x ?label ?slogan
WHERE {
?x a dbo:Company .
?x rdfs:label ?label .
FILTER(lang(?label) = "en")
OPTIONAL { ?x dbo:slogan ?slogan }
}
NOT EXISTS / MINUS
Make some query patterns
negative.
“I am looking for resources that don’t have …”
“I am looking for all resources that have this
minus those that have that”
Exemple – persons who don’t know Tom (FILTER
NOT EXISTS)
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person
WHERE {
?person rdf:type ex:Person .
FILTER NOT EXISTS {
?person ex:knows ex:Tom .
}
}
Exemple – persons except those that know Tom
(MINUS)
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person
WHERE {
?person rdf:type ex:Person .
MINUS {
?person ex:knows ex:Tom .
}
}
NOT EXISTS / MINUS
There are subtle differences
between FILTER NOT EXISTS
and MINUS
SELECT * WHERE {
?s ?p ?o
FILTER NOT EXISTS
{ ?x ?y ?z }
}
0 results
PREFIX ex: <http://ex.fr/>
SELECT * WHERE {
?s ?p ?o
FILTER NOT EXISTS
{ ex:A ex:B ex:C }
}
0 results
SELECT * WHERE {
?s ?p ?o
MINUS
{ ?x ?y ?z }
}
All results
PREFIX ex: <http://ex.fr/>
SELECT * WHERE {
?s ?p ?o
MINUS
{ ex:A ex:B ex:C }
}
All results
Exercise 6 : Making some patterns negative
• Write a query that returns…
• All the companies…
• … with their names
• … for those that do NOT have a slogan
• Company = dbo:Company
• Name = rdfs:label
• Slogan : dbo:slogan
Exercise 6 : Making some patterns negative
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?x ?label
WHERE {
?x a dbo:Company .
?x rdfs:label ?label .
FILTER(lang(?label) = "en")
FILTER NOT EXISTS { ?x dbo:slogan ?slogan }
}
UNION
Give alternatives query
patterns in a query
(a Boolean “OR” between query
patterns).
Rarely used in practice
Exemple – implicit or explicit Adults
PREFIX ex: <http://foo.org/ontology#>
SELECT ?name
WHERE {
?person ex:name ?name .
{
{ ?person rdf:type ex:Adult }
UNION
{ ?person ex:age ?age .
FILTER (?age > 18) }
}
}
Traversing the graph with
property paths
?x foaf:knows/org:membership/org:organization
ex:MinistryOfJustice
Property paths
Easily traverse/navigate
the graph. Similar to Xpath
in XML
Exemple – Persons who are friends of a friends of
Tom
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person
WHERE {
?person rdf:type ex:Person ;
ex:knows/ex:knows ex:Tom .
}
?x Ex:Tom
ex:knows ex:knows
ex:knows/ex:livesIn
ex:knows followed by ex:livesIn
ex:knows|ex:marriedWith
ex:knows or ex:marriedWith
!ex:knows
any property except ex:knows
ex:Tom ^ex:knows ?x :
ex:knows from ?x to ex:Tom
(to be combined with “/” paths)
ex:Tom ex:knows+ ?x
All ?x that Tom knows, and friends of friends of
friends… recursively, including ex:Tom
ex:Tom ex:knows* ?x
All ?x that Tom knows, and friends of friends of
friends… recursively, not including ex:Tom
ex:Tom ex:knows? ?x
Tom and any person he knows
(...)
Combine operators
Exemple Query ancestors of Tom
?ancestor (ex:motherOf|ex:fatherOf)+ ex:Tom
?c1 skos:broader|^skos:narrower ?c2
Exemple Querying inverse links
Exemple Querying RDF lists
?c1 rdf:rest*/rdf:first ?c2
Exercise 7 : Using property paths to traverse /
navigate the graph
http://dbpedia.org/sparql
• Write a query that returns…
• All the companies with their names…
• … that have been founded by someone …
• … born in a place …
• … that is in the United States
• Use a property path
Exercise 7 : Using property paths to traverse /
navigate the graph
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?x ?label
WHERE {
?x a dbo:Company .
?x rdfs:label ?label .
?x dbo:owner/dbo:birthPlace/dbo:country dbr:United_States
}
Assignation
(?x AS ?y) / BIND(?x AS ?y)
Assignation allows to set the
value of a variable with :
• result of a computation
• result of a function
• result of an aggregation function (GROUP BY)
• a (list of) value(s) known in advance
Exemple – Compute “body mass index”
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person ((?w/(?h*?h)) AS ?BMI)
WHERE {
?person a ex:Person ;
ex:height ?h .
ex:weight ?w .
}
Assignation can be done in
SELECT or in WHERE by using
the BIND operator to reuse the
value elsewhere
Exemple – Persons with low BMI
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person ?BMC
WHERE {
?person rdf:type ex:Person .
?person ex:weight ?w .
?person ex:height ?h .
BIND((?w/(?h*?h)) AS ?BMC)
FILTER (?BMC < 25)
}
Aggregation functions
enable to make computations
like COUNT, MAX, MIN, etc. and
can be combined with GROUP
BY.
Exemple – Number of Persons with low BMI
PREFIX ex: <http://foo.org/ontology#>
SELECT (COUNT(?person) as ?count)
WHERE {
?person rdf:type ex:Person ;
ex:weight ?w ;
ex:height ?h .
FILTER ((?w/(?h*?h)) < 25)
}
Exemple – Number of Persons with low BMI per
country
PREFIX ex: <http://foo.org/ontology#>
SELECT ?country (COUNT(?person) as ?count)
WHERE {
?person rdf:type ex:Person ;
ex:weight ?w ;
ex:height ?h .
?person ex:livesIn ?country .
FILTER ((?w/(?h*?h)) > 25)
} GROUP BY ?country
Aggregation functions :
COUNT, SUM, MIN, MAX, AVG,
SAMPLE et GROUP_CONCAT.
Exemple – Concatenate all names of friends of
Tom in a single string
PREFIX ex: <http://foo.org/ontology#>
SELECT (GROUP_CONCAT(?nameOfFriend; separator=“,”) AS
?allNamesOfFriends)
WHERE {
ex:Tom ex:knows/ex:name ?nameOfFriend .
}
HAVING keyword enables to
set a criteria on a group of the
GROUP BY clause, using
aggregates
Rarely used in practice
Exemple – Number of persons with low BMC per
country, for country with average BMC < 20
PREFIX ex: <http://foo.org/ontology#>
SELECT ?country (COUNT(?person) as ?count)
WHERE {
?person a ex:Person ; ex:weight ?w ;
ex:height ?h ; ex:livesIn ?country .
BIND ((?w/(?h*?h)) AS ?IMC)
FILTER(?IMC > 25)
} GROUP BY ?country
HAVING (AVG(?IMC) > 20)
VALUES is a very useful
keyword to directly assign the
values of certain variables. It
enable to pass list of values in
the query
Exemple – Read 3 known person names
PREFIX ex: <http://foo.org/ontology#>
SELECT ?person ?name
WHERE {
?person rdf:type ex:Person .
?person ex:name ?name .
VALUES ?person {
ex:Tom ex:Oliver ex:Mark
}
}
VALUES and FILTER(…
IN(…)) are NOT equivalents
« FILTER IN » is applied after pattern
matching, VALUES is applied during
it.
VALUES is more performant
than « FILTER IN ».
Subqueries & federated
queries
Nested queries are
SELECT subqueries
inside the WHERE
clause.
Use-case 1 : limit / sort / aggregate a subset
Use-case 2 : control the order of exécution of the
query
Exemple – Read top ten most used keywords,
then read their labels
SELECT ?cpt ?label
WHERE {
{
SELECT DISTINCT ?cpt
WHERE {
?doc dcterms:subject ?cpt .
}
ORDER BY DESC(COUNT(?cpt) as ?c)
LIMIT 10
}
?cpt skos:prefLabel ?label
}
Nested queries are
always executed before
the rest of the clauses.
This enables to control the execution
order of the query
It is possible to combine the
results of multiple SPARQL
services with the SERVICE
keyword. This is federated
querying.
Exemple – Read country names from DBPedia, then select
the concepts from a thesaurus having the same label
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX rdfs:<http://www.w3.org/2000/01/rdf-
schema#>
SELECT ?concept
WHERE {
?concept skos:prefLabel ?countryName .
SERVICE <http://dbpedia.org/sparql> {
?country rdfs:label ?countryName .
?country a <http://dbpedia.org/ontology/Country>
}
}
Be careful of the joins when querying an
remote database. Do not write :
SELECT ?person ?countryName
WHERE {
?person rdf:type ex:Person ;
?person ex:livesIn ?country .
SERVICE <http://dbpedia.org/sparql> {
?country rdfs:label ?countryName
}}
Use sub-queries to garantee the order of
exécution of the queries. Write instead :
SELECT ?country ?countryName
WHERE {
{
SELECT DISTINCT ?country WHERE {
?person rdf:type ex:Person ;
?person ex:livesIn ?country .
}
}
SERVICE <http://dbpedia.org/sparql> {
?country rdfs:label ?countryName
}}
Querying Named Graphs
« La quatrième dimension »
GRAPH
Allows patterns to be searched in
a subset of the complete data. A
graph is identified by a URI.
By default, without GRAPH, patterns are
searched in all graphs.
Exemple – keywords used in “production data”
PREFIX …
SELECT ?document ?tag ?label
WHERE {
GRAPH ex:baseProd {
?document dcterms:subject ?tag
}
?tag skos:prefLabel ?label
}
Exemple – return all graphs
PREFIX …
SELECT DISTINCT ?g
WHERE {
GRAPH ?g {
?s ?p ?o
}
}
FROM
Sets the DEFAULT GRAPH in
which patterns without a GRAPH
clause are searched.
SPARQL with FROM
PREFIX ...
SELECT ...
FROM ...
WHERE { ... }
Exemple – keywords from “test data” and
“production data”
PREFIX …
SELECT DISTINCT ?tag
FROM ex:baseProd
FROM ex:baseTest
WHERE {
?document dcterms:subject ?tag
}
FROM NAMED
Restricts the NAMED GRAPHS
available in GRAPH clauses.
Rarely used in practice.
Exemple – keywords from “test data” and
“production data” with their source
PREFIX …
SELECT ?doc ?tag ?g
FROM NAMED ex:baseProd
FROM NAMED ex:baseTest
WHERE
{
GRAPH ?g {
?doc dcterms:subject ?tag
}
}
Other forms of SPARQL
queries
CONSTRUCT / ASK / DESCRIBE
CONSTRUCT
Retourne un graphe RDF
pour chaque résultat
plutôt que des tuples
Exemple – return adults for persons over 18
PREFIX ex: <http://foo.org/ontology#>
CONSTRUCT
{
?person rdf:type ex:Adult
}
WHERE
{
?person ex:age ?age
FILTER (?age > 18)
}
Exemple – extract triples of age of persons
PREFIX ex: <http://foo.org/ontology#>
CONSTRUCT
{
?person ex:age ?age
}
WHERE
{
?person ex:age ?age
}
ASK
Test the existence of a
condition and simply
returns « true » / « false »
For consistency checking – but not much
used in practive. Use a SELECT most of
the time
Exemple – Are there any person over 18 ?
PREFIX ex: <http://foo.org/ontology#>
ASK
{
?person ex:age ?age
FILTER (?age > 18)
}
DESCRIBE
Give the « description »
(set of triples) of a
resource.
Typically, triples that have the URI(s) as
subject, + the labels of the object resources
Exemple – Describe persons over 18
PREFIX ex: <http://foo.org/ontology#>
DESCRIBE ?person
{
?person ex:age ?age
FILTER (?age > 18)
}
Exemple – Describe this known person
DESCRIBE <http://foo.org/~thomas#me>
Annex : queries to discover
the graph structure
1. List all types
SELECT DISTINCT ?type
WHERE {
?x rdf:type ?type .
}
2. List instances
SELECT ?x
WHERE {
?x rdf:type foaf:Person.
}
3. Everything about
SELECT ?p ?o
WHERE {
ex:Tom ?p ?o .
}
DESCRIBE ex:Tom
List all properties
SELECT DISTINCT ?p
WHERE { ?s ?p ?o . }
Be careful about performances
Properties per classes
SELECT DISTINCT ?type ?p
WHERE {
?x a ?type .
?x ?p ?o . FILTER(?p != rdf:type)
}
ORDER BY ?type
Annex : Creating URIs
and literals on-the-fly
One can forge IRIs and literals
and assign them :
IRI(string) : Builds an IRI from a string
ENCODE_FOR_URI(string) : escape a string to put in an
IRI
STR(literal) : string value of a literal or IRI as a
string
STRLANG and STRDT : build literals with value +
language or value + datatype
Exemple – Generate URIs from labels
PREFIX ex: <http://foo.org/ontology#>
SELECT ?newIRI
WHERE {
?person a ex:Person .
?person ex:name ?name .
BIND(
IRI(CONCAT(
“http://sparna.fr/”,
ENCODE_FOR_URI(?name)
))
AS ?newIRI)
}
One can cast values from one
type to another using Xpath
constructors
xsd:boolean(?x), xsd:double(?x),
xsd:float(?x), xsd:decimal(?x),
xsd:integer(?x), xsd:dateTime(?x),
xsd:string(?x)
Exemple – Add one to a literal string value
PREFIX ex: <http://foo.org/ontology#>
SELECT
(
(xsd:integer(?age) + 1) AS
?ageAnneeProchaine
)
WHERE {
?person a ex:Person .
?person ex:age ?age .
}
Annex : SPARQL protocol
and result format
SPARQL Protocol
Standardizes the way to
issue queries to a
triplestore
Unlike SQL. Consequence : you can
switch database implementation
transparently
Exemple – HTTP query following SPARQL
protocol
GET /sparql/?query=<encoded query> HTTP/1.1
Host: dbpedia.org
User-agent: my-sparql-client/0.1
The result format in XML
<?xml version="1.0"?>
<sparql xmlns="http://www.w3.org/2005/sparql-results#" >
<head>
<variable name="person"/>
<variable name="name"/>
</head>
<results ordered="false" distinct="false">
<result>
<binding name="person">
<uri>http://inria.fr/schema#fg</uri>
</binding>
<binding name="name">
<literal>gandon</literal>
</binding>
</result>
<result> ...
The result format in JSON
{
"head": { "vars": [ "book" , "title" ]
} ,
"results": {
"bindings": [
{
"book": { "type": "uri" , "value": "http://example.org/book/book6" } ,
"title": { "type": "literal" , "value": "Harry Potter and the Half-Blood Prince" }
} ,
{
"book": { "type": "uri" , "value": "http://example.org/book/book7" } ,
"title": { "type": "literal" , "value": "Harry Potter and the Deathly Hallows" }
} ,
{
"book": { "type": "uri" , "value": "http://example.org/book/book5" } ,
"title": { "type": "literal" , "value": "Harry Potter and the Order of the Phoenix" }
} ,
{
"book": { "type": "uri" , "value": "http://example.org/book/book4" } ,
"title": { "type": "literal" , "value": "Harry Potter and the Goblet of Fire" }
}
]
}
}
We neverdirectly see this
structure. It is always interpreted for us
by RDF/SPARQL libraries.
thomas.francart@
Web de
Structuration des
Accès aux
sparna.fr
données
informations
connaissances

More Related Content

What's hot

ESWC 2017 Tutorial Knowledge Graphs
ESWC 2017 Tutorial Knowledge GraphsESWC 2017 Tutorial Knowledge Graphs
ESWC 2017 Tutorial Knowledge Graphs
Peter Haase
 
Hadoop vs Apache Spark
Hadoop vs Apache SparkHadoop vs Apache Spark
Hadoop vs Apache Spark
ALTEN Calsoft Labs
 
Introduction to PySpark
Introduction to PySparkIntroduction to PySpark
Introduction to PySpark
Russell Jurney
 
RDF, linked data and semantic web
RDF, linked data and semantic webRDF, linked data and semantic web
RDF, linked data and semantic web
Jose Emilio Labra Gayo
 
Spark Interview Questions and Answers | Apache Spark Interview Questions | Sp...
Spark Interview Questions and Answers | Apache Spark Interview Questions | Sp...Spark Interview Questions and Answers | Apache Spark Interview Questions | Sp...
Spark Interview Questions and Answers | Apache Spark Interview Questions | Sp...
Edureka!
 
Introduction To RDF and RDFS
Introduction To RDF and RDFSIntroduction To RDF and RDFS
Introduction To RDF and RDFS
Nilesh Wagmare
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for Java
Aleksander Pohl
 
Aligner vos données avec Wikidata grâce à l'outil Open Refine
Aligner vos données avec Wikidata grâce à l'outil Open RefineAligner vos données avec Wikidata grâce à l'outil Open Refine
Aligner vos données avec Wikidata grâce à l'outil Open Refine
Gautier Poupeau
 
Learning to Rank in Solr: Presented by Michael Nilsson & Diego Ceccarelli, Bl...
Learning to Rank in Solr: Presented by Michael Nilsson & Diego Ceccarelli, Bl...Learning to Rank in Solr: Presented by Michael Nilsson & Diego Ceccarelli, Bl...
Learning to Rank in Solr: Presented by Michael Nilsson & Diego Ceccarelli, Bl...
Lucidworks
 
An Introduction to SPARQL
An Introduction to SPARQLAn Introduction to SPARQL
An Introduction to SPARQL
Olaf Hartig
 
SPARQL in a nutshell
SPARQL in a nutshellSPARQL in a nutshell
SPARQL in a nutshell
Fabien Gandon
 
Apache Spark Introduction
Apache Spark IntroductionApache Spark Introduction
Apache Spark Introduction
sudhakara st
 
Introduction to elasticsearch
Introduction to elasticsearchIntroduction to elasticsearch
Introduction to elasticsearch
pmanvi
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
Myungjin Lee
 
RDFS In A Nutshell V1
RDFS In A Nutshell V1RDFS In A Nutshell V1
RDFS In A Nutshell V1
Fabien Gandon
 
LinkML Intro July 2022.pptx PLEASE VIEW THIS ON ZENODO
LinkML Intro July 2022.pptx PLEASE VIEW THIS ON ZENODOLinkML Intro July 2022.pptx PLEASE VIEW THIS ON ZENODO
LinkML Intro July 2022.pptx PLEASE VIEW THIS ON ZENODO
Chris Mungall
 
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin HuaiA Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
Databricks
 
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQL
Jose Emilio Labra Gayo
 
PostgreSQL
PostgreSQLPostgreSQL
Introduction to Apache Hive
Introduction to Apache HiveIntroduction to Apache Hive
Introduction to Apache Hive
Avkash Chauhan
 

What's hot (20)

ESWC 2017 Tutorial Knowledge Graphs
ESWC 2017 Tutorial Knowledge GraphsESWC 2017 Tutorial Knowledge Graphs
ESWC 2017 Tutorial Knowledge Graphs
 
Hadoop vs Apache Spark
Hadoop vs Apache SparkHadoop vs Apache Spark
Hadoop vs Apache Spark
 
Introduction to PySpark
Introduction to PySparkIntroduction to PySpark
Introduction to PySpark
 
RDF, linked data and semantic web
RDF, linked data and semantic webRDF, linked data and semantic web
RDF, linked data and semantic web
 
Spark Interview Questions and Answers | Apache Spark Interview Questions | Sp...
Spark Interview Questions and Answers | Apache Spark Interview Questions | Sp...Spark Interview Questions and Answers | Apache Spark Interview Questions | Sp...
Spark Interview Questions and Answers | Apache Spark Interview Questions | Sp...
 
Introduction To RDF and RDFS
Introduction To RDF and RDFSIntroduction To RDF and RDFS
Introduction To RDF and RDFS
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for Java
 
Aligner vos données avec Wikidata grâce à l'outil Open Refine
Aligner vos données avec Wikidata grâce à l'outil Open RefineAligner vos données avec Wikidata grâce à l'outil Open Refine
Aligner vos données avec Wikidata grâce à l'outil Open Refine
 
Learning to Rank in Solr: Presented by Michael Nilsson & Diego Ceccarelli, Bl...
Learning to Rank in Solr: Presented by Michael Nilsson & Diego Ceccarelli, Bl...Learning to Rank in Solr: Presented by Michael Nilsson & Diego Ceccarelli, Bl...
Learning to Rank in Solr: Presented by Michael Nilsson & Diego Ceccarelli, Bl...
 
An Introduction to SPARQL
An Introduction to SPARQLAn Introduction to SPARQL
An Introduction to SPARQL
 
SPARQL in a nutshell
SPARQL in a nutshellSPARQL in a nutshell
SPARQL in a nutshell
 
Apache Spark Introduction
Apache Spark IntroductionApache Spark Introduction
Apache Spark Introduction
 
Introduction to elasticsearch
Introduction to elasticsearchIntroduction to elasticsearch
Introduction to elasticsearch
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
 
RDFS In A Nutshell V1
RDFS In A Nutshell V1RDFS In A Nutshell V1
RDFS In A Nutshell V1
 
LinkML Intro July 2022.pptx PLEASE VIEW THIS ON ZENODO
LinkML Intro July 2022.pptx PLEASE VIEW THIS ON ZENODOLinkML Intro July 2022.pptx PLEASE VIEW THIS ON ZENODO
LinkML Intro July 2022.pptx PLEASE VIEW THIS ON ZENODO
 
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin HuaiA Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
 
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQL
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Introduction to Apache Hive
Introduction to Apache HiveIntroduction to Apache Hive
Introduction to Apache Hive
 

Similar to SPARQL introduction and training (130+ slides with exercices)

Aidan's PhD Viva
Aidan's PhD VivaAidan's PhD Viva
Aidan's PhD Viva
Aidan Hogan
 
Sparql
SparqlSparql
Sparql
Tamrat Amare
 
Sparql
SparqlSparql
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQL
Jose Emilio Labra Gayo
 
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
Erik Hatcher
 
The Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQL
Myungjin Lee
 
Querying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQLQuerying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQL
Emanuele Della Valle
 
Making Topicmaps SPARQL
Making Topicmaps SPARQLMaking Topicmaps SPARQL
Making Topicmaps SPARQL
NetworkedPlanet
 
Semantic Web
Semantic WebSemantic Web
Semantic Web
amberkhan59
 
Semantic Web
Semantic WebSemantic Web
Semantic Web
amberkhan59
 
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
andyseaborne
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQL
Lino Valdivia
 
Semantic Web(Web 3.0) SPARQL
Semantic Web(Web 3.0) SPARQLSemantic Web(Web 3.0) SPARQL
Semantic Web(Web 3.0) SPARQL
Daniel D.J. UM
 
A Generic Mapping-based Query Translation from SPARQL to Various Target Datab...
A Generic Mapping-based Query Translation from SPARQL to Various Target Datab...A Generic Mapping-based Query Translation from SPARQL to Various Target Datab...
A Generic Mapping-based Query Translation from SPARQL to Various Target Datab...
Franck Michel
 
Linking the world with Python and Semantics
Linking the world with Python and SemanticsLinking the world with Python and Semantics
Linking the world with Python and Semantics
Tatiana Al-Chueyr
 
SWT Lecture Session 2 - RDF
SWT Lecture Session 2 - RDFSWT Lecture Session 2 - RDF
SWT Lecture Session 2 - RDF
Mariano Rodriguez-Muro
 
BioSD Tutorial 2014 Editition
BioSD Tutorial 2014 EdititionBioSD Tutorial 2014 Editition
BioSD Tutorial 2014 Editition
Rothamsted Research, UK
 
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
Antonio De Marinis
 
XSPARQL CrEDIBLE workshop
XSPARQL CrEDIBLE workshopXSPARQL CrEDIBLE workshop
XSPARQL CrEDIBLE workshop
nunoalexandrelopes
 
ParlBench: a SPARQL-benchmark for electronic publishing applications.
ParlBench: a SPARQL-benchmark for electronic publishing applications.ParlBench: a SPARQL-benchmark for electronic publishing applications.
ParlBench: a SPARQL-benchmark for electronic publishing applications.
Tatiana Tarasova
 

Similar to SPARQL introduction and training (130+ slides with exercices) (20)

Aidan's PhD Viva
Aidan's PhD VivaAidan's PhD Viva
Aidan's PhD Viva
 
Sparql
SparqlSparql
Sparql
 
Sparql
SparqlSparql
Sparql
 
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQL
 
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
 
The Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQL
 
Querying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQLQuerying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQL
 
Making Topicmaps SPARQL
Making Topicmaps SPARQLMaking Topicmaps SPARQL
Making Topicmaps SPARQL
 
Semantic Web
Semantic WebSemantic Web
Semantic Web
 
Semantic Web
Semantic WebSemantic Web
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
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQL
 
Semantic Web(Web 3.0) SPARQL
Semantic Web(Web 3.0) SPARQLSemantic Web(Web 3.0) SPARQL
Semantic Web(Web 3.0) SPARQL
 
A Generic Mapping-based Query Translation from SPARQL to Various Target Datab...
A Generic Mapping-based Query Translation from SPARQL to Various Target Datab...A Generic Mapping-based Query Translation from SPARQL to Various Target Datab...
A Generic Mapping-based Query Translation from SPARQL to Various Target Datab...
 
Linking the world with Python and Semantics
Linking the world with Python and SemanticsLinking the world with Python and Semantics
Linking the world with Python and Semantics
 
SWT Lecture Session 2 - RDF
SWT Lecture Session 2 - RDFSWT Lecture Session 2 - RDF
SWT Lecture Session 2 - RDF
 
BioSD Tutorial 2014 Editition
BioSD Tutorial 2014 EdititionBioSD Tutorial 2014 Editition
BioSD Tutorial 2014 Editition
 
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
 
XSPARQL CrEDIBLE workshop
XSPARQL CrEDIBLE workshopXSPARQL CrEDIBLE workshop
XSPARQL CrEDIBLE workshop
 
ParlBench: a SPARQL-benchmark for electronic publishing applications.
ParlBench: a SPARQL-benchmark for electronic publishing applications.ParlBench: a SPARQL-benchmark for electronic publishing applications.
ParlBench: a SPARQL-benchmark for electronic publishing applications.
 

More from Thomas Francart

SPARQL queries on CIDOC-CRM data of BritishMuseum
SPARQL queries on CIDOC-CRM data of BritishMuseumSPARQL queries on CIDOC-CRM data of BritishMuseum
SPARQL queries on CIDOC-CRM data of BritishMuseum
Thomas Francart
 
SPARQL sur les données CIDOC-CRM du British Museum
SPARQL sur les données CIDOC-CRM du British MuseumSPARQL sur les données CIDOC-CRM du British Museum
SPARQL sur les données CIDOC-CRM du British Museum
Thomas Francart
 
CIDOC-CRM + SPARQL Tutorial sur les données Doremus
CIDOC-CRM + SPARQL Tutorial sur les données DoremusCIDOC-CRM + SPARQL Tutorial sur les données Doremus
CIDOC-CRM + SPARQL Tutorial sur les données Doremus
Thomas Francart
 
Découvrir les données de data.bnf.fr en utilisant SPARQL
Découvrir les données de data.bnf.fr en utilisant SPARQLDécouvrir les données de data.bnf.fr en utilisant SPARQL
Découvrir les données de data.bnf.fr en utilisant SPARQL
Thomas Francart
 
JSON-LD
JSON-LDJSON-LD
Solr formation Sparna
Solr formation SparnaSolr formation Sparna
Solr formation Sparna
Thomas Francart
 
SKOS Play @ semweb.pro 2014
SKOS Play @ semweb.pro 2014SKOS Play @ semweb.pro 2014
SKOS Play @ semweb.pro 2014
Thomas Francart
 
Web of Data - Introduction (english)
Web of Data - Introduction (english)Web of Data - Introduction (english)
Web of Data - Introduction (english)
Thomas Francart
 
Partager et réutiliser des données sur le web
Partager et réutiliser des données sur le webPartager et réutiliser des données sur le web
Partager et réutiliser des données sur le web
Thomas Francart
 
RDFS : une introduction
RDFS : une introductionRDFS : une introduction
RDFS : une introduction
Thomas Francart
 
Skos play
Skos playSkos play
Skos play
Thomas Francart
 
Web de données - une introduction
Web de données - une introductionWeb de données - une introduction
Web de données - une introduction
Thomas Francart
 
RDF : une introduction
RDF : une introductionRDF : une introduction
RDF : une introduction
Thomas Francart
 

More from Thomas Francart (13)

SPARQL queries on CIDOC-CRM data of BritishMuseum
SPARQL queries on CIDOC-CRM data of BritishMuseumSPARQL queries on CIDOC-CRM data of BritishMuseum
SPARQL queries on CIDOC-CRM data of BritishMuseum
 
SPARQL sur les données CIDOC-CRM du British Museum
SPARQL sur les données CIDOC-CRM du British MuseumSPARQL sur les données CIDOC-CRM du British Museum
SPARQL sur les données CIDOC-CRM du British Museum
 
CIDOC-CRM + SPARQL Tutorial sur les données Doremus
CIDOC-CRM + SPARQL Tutorial sur les données DoremusCIDOC-CRM + SPARQL Tutorial sur les données Doremus
CIDOC-CRM + SPARQL Tutorial sur les données Doremus
 
Découvrir les données de data.bnf.fr en utilisant SPARQL
Découvrir les données de data.bnf.fr en utilisant SPARQLDécouvrir les données de data.bnf.fr en utilisant SPARQL
Découvrir les données de data.bnf.fr en utilisant SPARQL
 
JSON-LD
JSON-LDJSON-LD
JSON-LD
 
Solr formation Sparna
Solr formation SparnaSolr formation Sparna
Solr formation Sparna
 
SKOS Play @ semweb.pro 2014
SKOS Play @ semweb.pro 2014SKOS Play @ semweb.pro 2014
SKOS Play @ semweb.pro 2014
 
Web of Data - Introduction (english)
Web of Data - Introduction (english)Web of Data - Introduction (english)
Web of Data - Introduction (english)
 
Partager et réutiliser des données sur le web
Partager et réutiliser des données sur le webPartager et réutiliser des données sur le web
Partager et réutiliser des données sur le web
 
RDFS : une introduction
RDFS : une introductionRDFS : une introduction
RDFS : une introduction
 
Skos play
Skos playSkos play
Skos play
 
Web de données - une introduction
Web de données - une introductionWeb de données - une introduction
Web de données - une introduction
 
RDF : une introduction
RDF : une introductionRDF : une introduction
RDF : une introduction
 

Recently uploaded

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 

Recently uploaded (20)

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 

SPARQL introduction and training (130+ slides with exercices)

  • 1. SPARQL Thomas Francart, Crédits : This work remixes, translates and complete a presentation from Fabien Gandon, INRIA, under an open licence. Thanks to him. This work is placed under « Attribution ShareAlike 4.0 International ». You are free to share and adapt this work, even for commercial purposes. You must give appropriate credit, provide a link to the license, and indicate if changes were made. If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. For more information, see the license.
  • 2. RDF and its triples is the first level (after URI) in the standards of the semantic web
  • 3. SPARQL is on top of RDF . It is a query language and query protocol. It is the SQL for RDF data.
  • 4. SPARQL • Query data • Traverse graph from heterogeneous sources • Consistency checking • Data analytics • Data management (copy, move, delete, etc.) • Convert data from one structure to another • Make some inferences : find new data/relations from existing data • Generate exports (tabular or graph) • Make federated queries (query multiple databases) …
  • 5. SPARQL limits • No full-text search indexes (proprietary extensions) • No geographical indexes (proprietary extensions) • No query hints to control exécution plan (proprietary extensions) • No stored procedures • No triggers
  • 6. SPARQL standard has 3 parts Part 1: query language syntax Part 2: result format specification Part 3: query protocol 6
  • 7. Your first SPARQL Basic Graph Patterns
  • 8. Your first SPARQL PREFIX ... SELECT ... WHERE { ... }
  • 9. PREFIX clause Declare “shortcuts” for URIs used inside the query
  • 10. SELECT clause Indicate which values you want to return (which columns)
  • 11. WHERE Clause The conditions to search on the graph/the triples in the RDF data
  • 12. Triple patterns : WHERE Clause { ?x rdf:type ex:Person . ?x ex:name ?name . }
  • 13. Example – persons with their names PREFIX ex: <http://foo.org/ontology#> SELECT ?person ?name WHERE { ?person rdf:type ex:Person . ?person ex:name ?name . }
  • 14. Patterns with 1 variable # ?x that are Persons ?x rdf:type foaf:Person . # ?x that Tom knows ex:Tom foaf:knows ?x . # ?x that link Tom and Oliver ex:Tom ?x ex:Oliver .
  • 15. Patterns with 2 variables # ?x and ?y that know each other ?x foaf:knows ?y . # All verbs and values about Tom ex:Tom ?x ?y . # All subject and verbs that link to Tom ?x ?y ex:Tom .
  • 16. Patterns with 3 variables … or no variable at all # Everyting on everything ! # (returns all database) ?x ?y ?z . # Tom is a Person ex:Tom rdf:type foaf:Person .
  • 17. Exemple – same query as before PREFIX ex: <http://foo.org/ontology#> SELECT ?person ?name WHERE { ?person a ex:Person ; ex:name ?name . } Avoid confusion and always write full « sentences » : - Subject verb complement dot - Subject verb complement dot - Subject verb complement dot - …
  • 18. Whitespace between subject / predicate / object No whitespace in a URI or a variable name Never put whitespace afer or before the “:” in prefixed URIs. Never put whitespace after the “?” in variables ! If you want, a whitespace before final “.” Whitespaces ?aPerson rdf:type foaf:Person .
  • 19. WHERE { # Don’t use foaf:Person ?person a ex:Person . } Comments
  • 20. Methodology Write your queries step by step and test at each step : • Add a first criteria • Use LIMIT keyword to avoid too long result sets • Test • Add a criteria • Test • Add a criteria • Etc.
  • 21. Exercise 1 : a first query with a basic graph patterns • Write a query that returns… • All the companies… • … with their names PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> … • Company = dbo:Company • Name = rdfs:label http://dbpedia.org/sparql
  • 22. Exercise 1 : a first query with a basic graph patterns PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x ?label WHERE { ?x a dbo:Company . ?x rdfs:label ?label . }
  • 23. Methodology Understanding and mastering the structure of the underlying RDF Knowledge Graph is fundamental to query it in SPARQL.
  • 24. Methodology 1. Look at notices of entities to understand their description In HTML or in RDF 2. And/or read the model documentation 3. And/or look at sample queries provided 4. And/or do SPARQL exploration queries (see annex) It is possible to discover the graph data model by issuing specific SPARQL queries 5. Draw graph sketches
  • 25. Exercise 2 : A basic graph pattern that traverses the graph http://dbpedia.org/sparql • Write a query that returns… • All the companies with their names… • … that have been founded by someone … • … born in a place … • … that is in the United States PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX dbr: <http://dbpedia.org/resource/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> • Company = dbo:Company • Name = rdfs:label • founded by = dbo:founder • Born in = dbo:birthPlace • In country : dbo:country • United States : dbr:United_States
  • 26. Exercise 2 : A basic graph pattern that traverses the graph PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x ?label WHERE { ?x a dbo:Company . ?x rdfs:label ?label . ?x dbo:owner ?owner . ?owner dbo:birthPlace ?somewhere . ?somewhere dbo:country dbr:United_States }
  • 27. DISTINCT SELECT DISTINCT ?x ?y Deduplicate the result set
  • 28. Sorting and paging ORDER BY ?x variable(s) to order on. Use DESC(?x) to sort from Z-A LIMIT 100 limit the total size of result set OFFSET 10 index of the first result in total result set All identical to SQL
  • 29. Exemple – results 21 to 40 sorted by name PREFIX ex: <http://foo.org/ontology#> SELECT ?person ?name WHERE { ?person rdf:type ex:Person . ?person ex:name ?name . } ORDER BY ?name LIMIT 20 OFFSET 20
  • 30. Functions and FILTERS Beyond Basic Graph Patterns
  • 31. Functions Functions are applied on variables. They are used to : 1. FILTER the values of variables we want FILTER(lang(?x) = "fr") 2. Change the content of a column in the result set (assignation – see later)
  • 32. FILTER Add constraints on the variables used in the graph pattern : FILTER(?x > 18)
  • 33. PREFIX ex: <http://foo.org/ontology#> SELECT ?person ?name WHERE { ?person rdf:type ex:Person . ?person ex:name ?name . ?person ex:age ?age . FILTER (?age > 18) } Exemple – person above 18
  • 34. Mathematical operators +, -, *, /, =, !=, >, <, >=, <=
  • 35. Boolean operators !, &&, || FILTER( ?x = <http://aaa> || ?x = <http://bbb> )
  • 36. Functions on RDF literals / resources lang(?x) : language of ?x (« fr ») str(?x) : string value of ?x (without language/datatype) datatype(?x) : datatype of ?x
  • 37. Exercice 3 : Using FILTER • Keep only the names of the companies in English http://dbpedia.org/sparql
  • 38. Exercice 3 : Using FILTER PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x ?label WHERE { ?x a dbo:Company . ?x rdfs:label ?label . FILTER(lang(?label) = "en") }
  • 39. SELECT (f(?x) AS ?y) In the SELECT clause, you can apply a function on a variable and assign the result to a new variable with AS. This is assignation – more on this later
  • 40. Exercise 4 : Using a function in the SELECT clause with AS • We would like to get rid of the « @en » of the label column in the result set • Use « str(?label) » in the SELECT clause to select only the label string without the language
  • 41. Exercise 4 : Using a function in the SELECT clause with AS PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x (STR(?label) AS ?theLabel) WHERE { ?x a dbo:Company . ?x rdfs:label ?label . FILTER(lang(?label) = "en") }
  • 42. Functions on RDF literals / resources isIRI(?x) : true if ?x is an IRI isLiteral(?x) : true if ?x is a literal isBlank(?x) : true if ?x is an anonymous node
  • 43. Functions on strings UCASE(?x) / LCASE(?x) : ?x in upper-case / lower case STRLEN(?x) : length of ?x STRSTARTS(?x, ?y) STRENDS(?x, ?y) CONTAINS(?x, ?y) : test if ?x starts with / ends with / contains ?y
  • 44. STRBEFORE(?x,"foo") / STRAFTER(?x,"foo") : substring after of before « foo » in ?x REPLACE(?x,"http","https") : replaces « http » with « https » in ?x Functions on strings
  • 45. If « test » is true, returns « then », otherwise returns « else » IF(<test>,<then>,<else>)
  • 46. Combine functions FILTER(CONTAINS(STR(?x), "foo")) test if the string value of ?x contains « foo »
  • 47. Combine functions FILTER(IF(STRLEN(?name) > 10, BIND(…), BIND(…))) FILTER(STRLEN(STRBEFORE(?name, "b")) > 10) FILTER( IF(CONTAINS(STRAFTER(LCASE(?name), "mr."),"tom"),…,…) )
  • 48. YEAR(?x) / MONTH(?x) / DAY(?x) / HOURS(?x) / MINUTES(?x) / SECONDS(?x) Extracts part of a date value FILTER(YEAR(?x) = 2020) Functions on dates
  • 49. IN / NOT IN IN(…) and NOT IN(…) FILTER(?x IN (ex:Tom, ex:Oliver, ex:Franck)) FILTER(?x NOT IN ("a", "b", "c"))
  • 50. REGEX() function regex(?x, "^tom", "i") 1. Variable to test 2. Regular expression 3. Options (« i » : case-insensitive)
  • 51. Starts with « tom » regex(?x, "^tom", "i") Ends with « tom » regex(?x, "tom$", "i") Contains a number regex(?x, "[0-9]") Contains only a number regex(?x, "^[0-9]$") Contains date in format JJ/MM/AAAA or JJ-MM-AAAA (with day or month in or or two caracters) regex(?x, "[0-9][0-9]?[/-][0- 9][0-9]?[/-][0-9][0-9][0-9][0- 9]") Starts with http:// or https:// regex(?x, "^https?://[^s]+$") …
  • 52. Character Legend Example Sample Match d Most engines: one digit from 0 to 9 file_dd file_25 w Most engines: "word character": ASCII letter, digit or underscore w-www A-b_1 s Most engines: "whitespace character": space, tab, newline, carriage return, vertical tab asbsc a b c D One character that is not a digit as defined by your engine's d DDD ABC W One character that is not a word character as defined by your engine's w WWWWW *-+=) S One character that is not a whitespace character as defined by your engine's s SSSS Yoyo Quantifier Legend Example Sample Match + One or more Version w-w+ Version A-b1_1 * Zero or more times A*B*C* AAACC ? Once or none plurals? plural {3} Exactly three times D{3} ABC {2,4} Two to four times d{2,4} 156 {3,} Three or more times w{3,} regex_tutorial
  • 53. Character Legend Example Sample Match . Any character except line break a.c abc . Any character except line break, any number of times .* whatever, man. . A period (special character: needs to be escaped by a ) a.c a.c Escapes a special character .*+? $^/ .*+? $^/ Escapes a special character [{()}] [{()}] Character Legend Example Sample Match [ … ] One of the characters in the brackets [AEIOU] One uppercase vowel [ … ] One of the characters in the brackets T[ao]p Tap or Top - Range indicator [a-z] One lowercase letter [x-y] One of the characters in the range from x to y [A-Z]+ GREAT [ … ] One of the characters in the brackets [AB1-5w-z] One of either: A,B,1,2,3,4,5,w,x,y,z [x-y] One of the characters in the range from x to y [ -~]+ Characters in the printable section of the ASCII table. [^x] One character that is not x [^a-z]{3} A1! [^x-y] One of the characters not in the range from x to y [^ -~]+ Characters that are not in the printable section of the ASCII table.
  • 54. Combining Graph Patterns Negative patterns / Optional patterns / Union of patterns
  • 55. OPTIONAL Make one or more query patterns optional Even if they don’t match, results will still be returned. Very useful to build result sets when we are not 100% all properties exist
  • 56. Exemple – return age if it is know in the graph PREFIX ex: <http://foo.org/ontology#> SELECT ?person ?name ?age WHERE { ?person rdf:type ex:Person . ?person ex:name ?name . OPTIONAL { ?person ex:age ?age } }
  • 57. Exercise 5 : Making some patterns optional • Write a query that returns… • All the companies… • … with their names • … and their slogan if they have one ! • Company = dbo:Company • Name = rdfs:label • Slogan : dbo:slogan
  • 58. Exercise 5 : Making some patterns optional PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x ?label ?slogan WHERE { ?x a dbo:Company . ?x rdfs:label ?label . FILTER(lang(?label) = "en") OPTIONAL { ?x dbo:slogan ?slogan } }
  • 59. NOT EXISTS / MINUS Make some query patterns negative. “I am looking for resources that don’t have …” “I am looking for all resources that have this minus those that have that”
  • 60. Exemple – persons who don’t know Tom (FILTER NOT EXISTS) PREFIX ex: <http://foo.org/ontology#> SELECT ?person WHERE { ?person rdf:type ex:Person . FILTER NOT EXISTS { ?person ex:knows ex:Tom . } }
  • 61. Exemple – persons except those that know Tom (MINUS) PREFIX ex: <http://foo.org/ontology#> SELECT ?person WHERE { ?person rdf:type ex:Person . MINUS { ?person ex:knows ex:Tom . } }
  • 62. NOT EXISTS / MINUS There are subtle differences between FILTER NOT EXISTS and MINUS
  • 63. SELECT * WHERE { ?s ?p ?o FILTER NOT EXISTS { ?x ?y ?z } } 0 results PREFIX ex: <http://ex.fr/> SELECT * WHERE { ?s ?p ?o FILTER NOT EXISTS { ex:A ex:B ex:C } } 0 results SELECT * WHERE { ?s ?p ?o MINUS { ?x ?y ?z } } All results PREFIX ex: <http://ex.fr/> SELECT * WHERE { ?s ?p ?o MINUS { ex:A ex:B ex:C } } All results
  • 64. Exercise 6 : Making some patterns negative • Write a query that returns… • All the companies… • … with their names • … for those that do NOT have a slogan • Company = dbo:Company • Name = rdfs:label • Slogan : dbo:slogan
  • 65. Exercise 6 : Making some patterns negative PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x ?label WHERE { ?x a dbo:Company . ?x rdfs:label ?label . FILTER(lang(?label) = "en") FILTER NOT EXISTS { ?x dbo:slogan ?slogan } }
  • 66. UNION Give alternatives query patterns in a query (a Boolean “OR” between query patterns). Rarely used in practice
  • 67. Exemple – implicit or explicit Adults PREFIX ex: <http://foo.org/ontology#> SELECT ?name WHERE { ?person ex:name ?name . { { ?person rdf:type ex:Adult } UNION { ?person ex:age ?age . FILTER (?age > 18) } } }
  • 68. Traversing the graph with property paths ?x foaf:knows/org:membership/org:organization ex:MinistryOfJustice
  • 69. Property paths Easily traverse/navigate the graph. Similar to Xpath in XML
  • 70. Exemple – Persons who are friends of a friends of Tom PREFIX ex: <http://foo.org/ontology#> SELECT ?person WHERE { ?person rdf:type ex:Person ; ex:knows/ex:knows ex:Tom . } ?x Ex:Tom ex:knows ex:knows
  • 71. ex:knows/ex:livesIn ex:knows followed by ex:livesIn ex:knows|ex:marriedWith ex:knows or ex:marriedWith !ex:knows any property except ex:knows ex:Tom ^ex:knows ?x : ex:knows from ?x to ex:Tom (to be combined with “/” paths)
  • 72. ex:Tom ex:knows+ ?x All ?x that Tom knows, and friends of friends of friends… recursively, including ex:Tom ex:Tom ex:knows* ?x All ?x that Tom knows, and friends of friends of friends… recursively, not including ex:Tom ex:Tom ex:knows? ?x Tom and any person he knows (...) Combine operators
  • 73. Exemple Query ancestors of Tom ?ancestor (ex:motherOf|ex:fatherOf)+ ex:Tom ?c1 skos:broader|^skos:narrower ?c2 Exemple Querying inverse links Exemple Querying RDF lists ?c1 rdf:rest*/rdf:first ?c2
  • 74. Exercise 7 : Using property paths to traverse / navigate the graph http://dbpedia.org/sparql • Write a query that returns… • All the companies with their names… • … that have been founded by someone … • … born in a place … • … that is in the United States • Use a property path
  • 75. Exercise 7 : Using property paths to traverse / navigate the graph PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x ?label WHERE { ?x a dbo:Company . ?x rdfs:label ?label . ?x dbo:owner/dbo:birthPlace/dbo:country dbr:United_States }
  • 76. Assignation (?x AS ?y) / BIND(?x AS ?y)
  • 77. Assignation allows to set the value of a variable with : • result of a computation • result of a function • result of an aggregation function (GROUP BY) • a (list of) value(s) known in advance
  • 78. Exemple – Compute “body mass index” PREFIX ex: <http://foo.org/ontology#> SELECT ?person ((?w/(?h*?h)) AS ?BMI) WHERE { ?person a ex:Person ; ex:height ?h . ex:weight ?w . }
  • 79. Assignation can be done in SELECT or in WHERE by using the BIND operator to reuse the value elsewhere
  • 80. Exemple – Persons with low BMI PREFIX ex: <http://foo.org/ontology#> SELECT ?person ?BMC WHERE { ?person rdf:type ex:Person . ?person ex:weight ?w . ?person ex:height ?h . BIND((?w/(?h*?h)) AS ?BMC) FILTER (?BMC < 25) }
  • 81. Aggregation functions enable to make computations like COUNT, MAX, MIN, etc. and can be combined with GROUP BY.
  • 82. Exemple – Number of Persons with low BMI PREFIX ex: <http://foo.org/ontology#> SELECT (COUNT(?person) as ?count) WHERE { ?person rdf:type ex:Person ; ex:weight ?w ; ex:height ?h . FILTER ((?w/(?h*?h)) < 25) }
  • 83. Exemple – Number of Persons with low BMI per country PREFIX ex: <http://foo.org/ontology#> SELECT ?country (COUNT(?person) as ?count) WHERE { ?person rdf:type ex:Person ; ex:weight ?w ; ex:height ?h . ?person ex:livesIn ?country . FILTER ((?w/(?h*?h)) > 25) } GROUP BY ?country
  • 84. Aggregation functions : COUNT, SUM, MIN, MAX, AVG, SAMPLE et GROUP_CONCAT.
  • 85. Exemple – Concatenate all names of friends of Tom in a single string PREFIX ex: <http://foo.org/ontology#> SELECT (GROUP_CONCAT(?nameOfFriend; separator=“,”) AS ?allNamesOfFriends) WHERE { ex:Tom ex:knows/ex:name ?nameOfFriend . }
  • 86. HAVING keyword enables to set a criteria on a group of the GROUP BY clause, using aggregates Rarely used in practice
  • 87. Exemple – Number of persons with low BMC per country, for country with average BMC < 20 PREFIX ex: <http://foo.org/ontology#> SELECT ?country (COUNT(?person) as ?count) WHERE { ?person a ex:Person ; ex:weight ?w ; ex:height ?h ; ex:livesIn ?country . BIND ((?w/(?h*?h)) AS ?IMC) FILTER(?IMC > 25) } GROUP BY ?country HAVING (AVG(?IMC) > 20)
  • 88. VALUES is a very useful keyword to directly assign the values of certain variables. It enable to pass list of values in the query
  • 89. Exemple – Read 3 known person names PREFIX ex: <http://foo.org/ontology#> SELECT ?person ?name WHERE { ?person rdf:type ex:Person . ?person ex:name ?name . VALUES ?person { ex:Tom ex:Oliver ex:Mark } }
  • 90. VALUES and FILTER(… IN(…)) are NOT equivalents « FILTER IN » is applied after pattern matching, VALUES is applied during it. VALUES is more performant than « FILTER IN ».
  • 92. Nested queries are SELECT subqueries inside the WHERE clause. Use-case 1 : limit / sort / aggregate a subset Use-case 2 : control the order of exécution of the query
  • 93. Exemple – Read top ten most used keywords, then read their labels SELECT ?cpt ?label WHERE { { SELECT DISTINCT ?cpt WHERE { ?doc dcterms:subject ?cpt . } ORDER BY DESC(COUNT(?cpt) as ?c) LIMIT 10 } ?cpt skos:prefLabel ?label }
  • 94. Nested queries are always executed before the rest of the clauses. This enables to control the execution order of the query
  • 95. It is possible to combine the results of multiple SPARQL services with the SERVICE keyword. This is federated querying.
  • 96. Exemple – Read country names from DBPedia, then select the concepts from a thesaurus having the same label PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX rdfs:<http://www.w3.org/2000/01/rdf- schema#> SELECT ?concept WHERE { ?concept skos:prefLabel ?countryName . SERVICE <http://dbpedia.org/sparql> { ?country rdfs:label ?countryName . ?country a <http://dbpedia.org/ontology/Country> } }
  • 97. Be careful of the joins when querying an remote database. Do not write : SELECT ?person ?countryName WHERE { ?person rdf:type ex:Person ; ?person ex:livesIn ?country . SERVICE <http://dbpedia.org/sparql> { ?country rdfs:label ?countryName }}
  • 98. Use sub-queries to garantee the order of exécution of the queries. Write instead : SELECT ?country ?countryName WHERE { { SELECT DISTINCT ?country WHERE { ?person rdf:type ex:Person ; ?person ex:livesIn ?country . } } SERVICE <http://dbpedia.org/sparql> { ?country rdfs:label ?countryName }}
  • 99. Querying Named Graphs « La quatrième dimension »
  • 100. GRAPH Allows patterns to be searched in a subset of the complete data. A graph is identified by a URI. By default, without GRAPH, patterns are searched in all graphs.
  • 101. Exemple – keywords used in “production data” PREFIX … SELECT ?document ?tag ?label WHERE { GRAPH ex:baseProd { ?document dcterms:subject ?tag } ?tag skos:prefLabel ?label }
  • 102. Exemple – return all graphs PREFIX … SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }
  • 103. FROM Sets the DEFAULT GRAPH in which patterns without a GRAPH clause are searched.
  • 104. SPARQL with FROM PREFIX ... SELECT ... FROM ... WHERE { ... }
  • 105. Exemple – keywords from “test data” and “production data” PREFIX … SELECT DISTINCT ?tag FROM ex:baseProd FROM ex:baseTest WHERE { ?document dcterms:subject ?tag }
  • 106. FROM NAMED Restricts the NAMED GRAPHS available in GRAPH clauses. Rarely used in practice.
  • 107. Exemple – keywords from “test data” and “production data” with their source PREFIX … SELECT ?doc ?tag ?g FROM NAMED ex:baseProd FROM NAMED ex:baseTest WHERE { GRAPH ?g { ?doc dcterms:subject ?tag } }
  • 108. Other forms of SPARQL queries CONSTRUCT / ASK / DESCRIBE
  • 109. CONSTRUCT Retourne un graphe RDF pour chaque résultat plutôt que des tuples
  • 110. Exemple – return adults for persons over 18 PREFIX ex: <http://foo.org/ontology#> CONSTRUCT { ?person rdf:type ex:Adult } WHERE { ?person ex:age ?age FILTER (?age > 18) }
  • 111. Exemple – extract triples of age of persons PREFIX ex: <http://foo.org/ontology#> CONSTRUCT { ?person ex:age ?age } WHERE { ?person ex:age ?age }
  • 112. ASK Test the existence of a condition and simply returns « true » / « false » For consistency checking – but not much used in practive. Use a SELECT most of the time
  • 113. Exemple – Are there any person over 18 ? PREFIX ex: <http://foo.org/ontology#> ASK { ?person ex:age ?age FILTER (?age > 18) }
  • 114. DESCRIBE Give the « description » (set of triples) of a resource. Typically, triples that have the URI(s) as subject, + the labels of the object resources
  • 115. Exemple – Describe persons over 18 PREFIX ex: <http://foo.org/ontology#> DESCRIBE ?person { ?person ex:age ?age FILTER (?age > 18) }
  • 116. Exemple – Describe this known person DESCRIBE <http://foo.org/~thomas#me>
  • 117. Annex : queries to discover the graph structure
  • 118. 1. List all types SELECT DISTINCT ?type WHERE { ?x rdf:type ?type . }
  • 119. 2. List instances SELECT ?x WHERE { ?x rdf:type foaf:Person. }
  • 120. 3. Everything about SELECT ?p ?o WHERE { ex:Tom ?p ?o . } DESCRIBE ex:Tom
  • 121. List all properties SELECT DISTINCT ?p WHERE { ?s ?p ?o . } Be careful about performances
  • 122. Properties per classes SELECT DISTINCT ?type ?p WHERE { ?x a ?type . ?x ?p ?o . FILTER(?p != rdf:type) } ORDER BY ?type
  • 123. Annex : Creating URIs and literals on-the-fly
  • 124. One can forge IRIs and literals and assign them : IRI(string) : Builds an IRI from a string ENCODE_FOR_URI(string) : escape a string to put in an IRI STR(literal) : string value of a literal or IRI as a string STRLANG and STRDT : build literals with value + language or value + datatype
  • 125. Exemple – Generate URIs from labels PREFIX ex: <http://foo.org/ontology#> SELECT ?newIRI WHERE { ?person a ex:Person . ?person ex:name ?name . BIND( IRI(CONCAT( “http://sparna.fr/”, ENCODE_FOR_URI(?name) )) AS ?newIRI) }
  • 126. One can cast values from one type to another using Xpath constructors xsd:boolean(?x), xsd:double(?x), xsd:float(?x), xsd:decimal(?x), xsd:integer(?x), xsd:dateTime(?x), xsd:string(?x)
  • 127. Exemple – Add one to a literal string value PREFIX ex: <http://foo.org/ontology#> SELECT ( (xsd:integer(?age) + 1) AS ?ageAnneeProchaine ) WHERE { ?person a ex:Person . ?person ex:age ?age . }
  • 128. Annex : SPARQL protocol and result format
  • 129. SPARQL Protocol Standardizes the way to issue queries to a triplestore Unlike SQL. Consequence : you can switch database implementation transparently
  • 130. Exemple – HTTP query following SPARQL protocol GET /sparql/?query=<encoded query> HTTP/1.1 Host: dbpedia.org User-agent: my-sparql-client/0.1
  • 131. The result format in XML <?xml version="1.0"?> <sparql xmlns="http://www.w3.org/2005/sparql-results#" > <head> <variable name="person"/> <variable name="name"/> </head> <results ordered="false" distinct="false"> <result> <binding name="person"> <uri>http://inria.fr/schema#fg</uri> </binding> <binding name="name"> <literal>gandon</literal> </binding> </result> <result> ...
  • 132. The result format in JSON { "head": { "vars": [ "book" , "title" ] } , "results": { "bindings": [ { "book": { "type": "uri" , "value": "http://example.org/book/book6" } , "title": { "type": "literal" , "value": "Harry Potter and the Half-Blood Prince" } } , { "book": { "type": "uri" , "value": "http://example.org/book/book7" } , "title": { "type": "literal" , "value": "Harry Potter and the Deathly Hallows" } } , { "book": { "type": "uri" , "value": "http://example.org/book/book5" } , "title": { "type": "literal" , "value": "Harry Potter and the Order of the Phoenix" } } , { "book": { "type": "uri" , "value": "http://example.org/book/book4" } , "title": { "type": "literal" , "value": "Harry Potter and the Goblet of Fire" } } ] } }
  • 133. We neverdirectly see this structure. It is always interpreted for us by RDF/SPARQL libraries.
  • 134. thomas.francart@ Web de Structuration des Accès aux sparna.fr données informations connaissances