SlideShare a Scribd company logo
1 of 19
SPARQL By Example:
The Cheat Sheet
Accompanies slides at:
http://www.cambridgesemantics.com/semantic-university/sparql-by-example
Comments & questions to:
Lee Feigenbaum <lee@cambridgesemantics.com>
VP Marketing & Technology, Cambridge Semantics
Co-chair, W3C SPARQL Working Group
Conventions
Red text means:
“This is a core part of the SPARQL syntax or
language.”
Blue text means:
“This is an example of query-specific text or
values that might go into a SPARQL query.”
Nuts & Bolts
Write full URIs:
<http://this.is.a/full/URI/written#out>
Abbreviate URIs with prefixes:
PREFIX foo: <http://this.is.a/URI/prefix#>
… foo:bar …
 http://this.is.a/URI/prefix#bar
Shortcuts:
a  rdf:type
URIs
Plain literals:
“a plain literal”
Plain literal with language tag:
“bonjour”@fr
Typed literal:
“13”^^xsd:integer
Shortcuts:
true  “true”^^xsd:boolean
3  “3”^^xsd:integer
4.2  “4.2”^^xsd:decimal
Literals
Variables:
?var1, ?anotherVar, ?and_one_more
Variables
Comments:
# Comments start with a „#‟ and
# continue to the end of the line
Comments
Match an exact RDF triple:
ex:myWidget ex:partNumber “XY24Z1” .
Match one variable:
?person foaf:name “Lee Feigenbaum” .
Match multiple variables:
conf:SemTech2009 ?property ?value .
Triple Patterns
Common Prefixes
More common prefixes at http://prefix.cc
prefix... …stands for
rdf: http://xmlns.com/foaf/0.1/
rdfs: http://www.w3.org/2000/01/rdf-schema#
owl: http://www.w3.org/2002/07/owl#
xsd: http://www.w3.org/2001/XMLSchema#
dc: http://purl.org/dc/elements/1.1/
foaf: http://xmlns.com/foaf/0.1/
Anatomy of a Query
PREFIX foo: <…>
PREFIX bar: <…>
…
SELECT …
FROM <…>
FROM NAMED <…>
WHERE {
…
}
GROUP BY …
HAVING …
ORDER BY …
LIMIT …
OFFSET …
VALUES …
Declare prefix
shortcuts
(optional)
Query result
clause
Query pattern
Query modifiers
(optional)
Define the
dataset (optional)
4 Types of SPARQL Queries
Project out specific variables and expressions:
SELECT ?c ?cap (1000 * ?people AS ?pop)
Project out all variables:
SELECT *
Project out distinct combinations only:
SELECT DISTINCT ?country
Results in a table of values (in XML or JSON):
SELECT queries
?c ?cap ?pop
ex:France ex:Paris 63,500,000
ex:Canada ex:Ottawa 32,900,000
ex:Italy ex:Rome 58,900,000
Construct RDF triples/graphs:
CONSTRUCT {
?country a ex:HolidayDestination ;
ex:arrive_at ?capital ;
ex:population ?population .
}
Results in RDF triples (in any RDF serialization):
ex:France a ex:HolidayDestination ;
ex:arrive_at ex:Paris ;
ex:population 635000000 .
ex:Canada a ex:HolidayDestination ;
ex:arrive_at ex:Ottawa ;
ex:population 329000000 .
CONSTRUCT queries
Ask whether or not there are any matches:
ASK
Result is either “true” or “false” (in XML or JSON):
true, false
ASK queries
Describe the resources matched by the given variables:
DESCRIBE ?country
Result is RDF triples (in any RDF serialization) :
ex:France a geo:Country ;
ex:continent geo:Europe ;
ex:flag <http://…/flag-france.png> ;
…
DESCRIBE queries
Combining SPARQL Graph Patterns
Consider A and B as graph patterns.
A Basic Graph Pattern – one or more triple patterns
A . B
 Conjunction. Join together the results of solving A and B by matching the
values of any variables in common.
Optional Graph Patterns
A OPTIONAL { B }
 Left join. Join together the results of solving A and B by matching the
values of any variables in common, if possible. Keep all solutions from A whether or
not there’s a matching solution in B
Combining SPARQL Graph Patterns
Consider A and B as graph patterns.
Either-or Graph Patterns
{ A } UNION { B }
 Disjunction. Include both the results of solving A and the results of
solving B.
“Subtracted” Graph Patterns (SPARQL 1.1)
A MINUS { B }
 Negation. Solve A. Solve B. Include only those results from solving A that
are not compatible with any of the results from B.
SPARQL Subqueries (SPARQL 1.1)
Consider A and B as graph patterns.
A .
{
SELECT …
WHERE {
B
}
}
C .
 Join the results of the subquery with the results of solving A and C.
SPARQL Filters
• SPARQL FILTERs eliminate solutions that do not cause an
expression to evaluate to true.
• Place FILTERs in a query inline within a basic graph pattern
A . B . FILTER ( …expr… )
Category Functions / Operators Examples
Logical &
Comparisons
!, &&, ||, =, !=, <, <=, >,
>=, IN, NOT IN
?hasPermit || ?age < 25
Conditionals
(SPARQL 1.1)
EXISTS, NOT EXISTS, IF,
COALESCE
NOT EXISTS { ?p foaf:mbox ?email }
Math
+, -, *, /, abs, round,
ceil, floor, RAND
?decimal * 10 > ?minPercent
Strings
(SPARQL 1.1)
STRLEN, SUBSTR, UCASE,
LCASE, STRSTARTS, CONCAT,
STRENDS, CONTAINS,
STRBEFORE, STRAFTER
STRLEN(?description) < 255
Date/time
(SPARQL 1.1)
now, year, month, day,
hours, minutes, seconds,
timezone, tz
month(now()) < 4
SPARQL tests
isURI, isBlank,
isLiteral, isNumeric,
bound
isURI(?person) || !bound(?person)
Constructors
(SPARQL 1.1)
URI, BNODE, STRDT,
STRLANG, UUID, STRUUID
STRLANG(?text, “en”) = “hello”@en
Accessors str, lang, datatype lang(?title) = “en”
Hashing (1.1) MD5, SHA1, SHA256, SHA512 BIND(SHA256(?email) AS ?hash)
Miscellaneous
sameTerm, langMatches,
regex, REPLACE
regex(?ssn, “d{3}-d{2}-d{4}”)
Aggregates (SPARQL 1.1)
1. Partition results into
groups based on the
expression(s) in the
GROUP BY clause
2. Evaluate projections
and aggregate functions
in SELECT clause to get
one result per group
3. Filter aggregated
results via the HAVING
clause
?key ?val ?other1
1 4 …
1 4 …
2 5 …
2 4 …
2 10 …
2 2 …
2 1 …
3 3 …
?key ?sum_of_val
1 8
2 22
3 3
?key ?sum_of_val
1 8
3 3
SPARQL 1.1 includes: COUNT, SUM, AVG, MIN, MAX, SAMPLE, GROUP_CONCAT
Property Paths (SPARQL 1.1)
• Property paths allow triple patterns to match arbitrary-
length paths through a graph
• Predicates are combined with regular-expression-like
operators:
Construct Meaning
path1/path2 Forwards path (path1 followed by path2)
^path1 Backwards path (object to subject)
path1|path2 Either path1 or path2
path1* path1, repeated zero or more times
path1+ path1, repeated one or more times
path1? path1, optionally
!uri Any predicate except uri
!^uri Any backwards (object to subject) predicate except uri
RDF Datasets
A SPARQL queries a default graph (normally) and zero or
more named graphs (when inside a GRAPH clause).
ex:g1
ex:g2
ex:g3
Default graph
(the merge of zero or more graphs)
Named graphs
ex:g1
ex:g4
PREFIX ex: <…>
SELECT …
FROM ex:g1
FROM ex:g4
FROM NAMED ex:g1
FROM NAMED ex:g2
FROM NAMED ex:g3
WHERE {
… A …
GRAPH ex:g3 {
… B …
}
GRAPH ?graph {
… C …
}
}
OR
OR
SPARQL Over HTTP (the SPARQL Protocol)
http://host.domain.com/sparql/endpoint?<parameters>
where <parameters> can include:
query=<encoded query string>
e.g. SELECT+*%0DWHERE+{…
default-graph-uri=<encoded graph URI>
e.g. http%3A%2F%2Fexmaple.com%2Ffoo…
n.b. zero of more occurrences of default-graph-uri
named-graph-uri=<encoded graph URI>
e.g. http%3A%2F%2Fexmaple.com%2Fbar…
n.b. zero of more occurrences of named-graph-uri
HTTP GET or POST. Graphs given in the protocol override graphs given in the
query.
Federated Query (SPARQL 1.1)
PREFIX ex: <…>
SELECT …
FROM ex:g1
WHERE {
… A …
SERVICE ex:s1 {
… B …
}
SERVICE ex:s2 {
… C …
}
}
ex:g1
Web
SPARQL Endpoint
ex:s2
SPARQL Endpoint
ex:s1
Local Graph Store
SPARQL 1.1 Update
SPARQL Update Language Statements
INSERT DATA { triples }
DELETE DATA {triples}
[ DELETE { template } ] [ INSERT { template } ] WHERE { pattern }
LOAD <uri> [ INTO GRAPH <uri> ]
CLEAR GRAPH <uri>
CREATE GRAPH <uri>
DROP GRAPH <uri>
[ … ] denotes optional parts of SPARQL 1.1 Update syntax
Some Public SPARQL Endpoints
Name URL What’s there?
SPARQLer http://sparql.org/sparql.html
General-purpose query
endpoint for Web-accessible
data
DBPedia http://dbpedia.org/sparql
Extensive RDF data from
Wikipedia
DBLP http://www4.wiwiss.fu-berlin.de/dblp/snorql/
Bibliographic data from
computer science journals
and conferences
LinkedMDB http://data.linkedmdb.org/sparql
Films, actors, directors,
writers, producers, etc.
World
Factbook
http://www4.wiwiss.fu-
berlin.de/factbook/snorql/
Country statistics from the
CIA World Factbook
bio2rdf http://bio2rdf.org/sparql
Bioinformatics data from
around 40 public databases
SPARQL Resources
• SPARQL Specifications Overview
– http://www.w3.org/TR/sparql11-overview/
• SPARQL implementations
– http://esw.w3.org/topic/SparqlImplementations
• SPARQL endpoints
– http://esw.w3.org/topic/SparqlEndpoints
• SPARQL Frequently Asked Questions
– http://www.thefigtrees.net/lee/sw/sparql-faq
• Common SPARQL extensions
– http://esw.w3.org/topic/SPARQL/Extensions

More Related Content

What's hot

Introduction to RDF
Introduction to RDFIntroduction to RDF
Introduction to RDFNarni Rajesh
 
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
 
Introduction to Knowledge Graphs and Semantic AI
Introduction to Knowledge Graphs and Semantic AIIntroduction to Knowledge Graphs and Semantic AI
Introduction to Knowledge Graphs and Semantic AISemantic Web Company
 
Programming in Spark using PySpark
Programming in Spark using PySpark      Programming in Spark using PySpark
Programming in Spark using PySpark Mostafa
 
Introduction of Knowledge Graphs
Introduction of Knowledge GraphsIntroduction of Knowledge Graphs
Introduction of Knowledge GraphsJeff Z. Pan
 
PySpark in practice slides
PySpark in practice slidesPySpark in practice slides
PySpark in practice slidesDat Tran
 
SPARQL in a nutshell
SPARQL in a nutshellSPARQL in a nutshell
SPARQL in a nutshellFabien Gandon
 
Selecting with SPARQL
Selecting with SPARQLSelecting with SPARQL
Selecting with SPARQLostephens
 
Introduction to Graph Databases
Introduction to Graph DatabasesIntroduction to Graph Databases
Introduction to Graph DatabasesMax De Marzi
 
JSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked DataJSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked DataGregg Kellogg
 
MongoDB vs. Postgres Benchmarks
MongoDB vs. Postgres Benchmarks MongoDB vs. Postgres Benchmarks
MongoDB vs. Postgres Benchmarks EDB
 
SPARQL 사용법
SPARQL 사용법SPARQL 사용법
SPARQL 사용법홍수 허
 
Integrating Relational Databases with the Semantic Web: A Reflection
Integrating Relational Databases with the Semantic Web: A ReflectionIntegrating Relational Databases with the Semantic Web: A Reflection
Integrating Relational Databases with the Semantic Web: A ReflectionJuan Sequeda
 
Natural Language Processing with Graph Databases and Neo4j
Natural Language Processing with Graph Databases and Neo4jNatural Language Processing with Graph Databases and Neo4j
Natural Language Processing with Graph Databases and Neo4jWilliam Lyon
 
Data Engineer, Patterns & Architecture The future: Deep-dive into Microservic...
Data Engineer, Patterns & Architecture The future: Deep-dive into Microservic...Data Engineer, Patterns & Architecture The future: Deep-dive into Microservic...
Data Engineer, Patterns & Architecture The future: Deep-dive into Microservic...Igor De Souza
 
Introduction to PySpark
Introduction to PySparkIntroduction to PySpark
Introduction to PySparkRussell Jurney
 
Introduction to Knowledge Graphs: Data Summit 2020
Introduction to Knowledge Graphs: Data Summit 2020Introduction to Knowledge Graphs: Data Summit 2020
Introduction to Knowledge Graphs: Data Summit 2020Enterprise Knowledge
 
Overview of the SPARQL-Generate language and latest developments
Overview of the SPARQL-Generate language and latest developmentsOverview of the SPARQL-Generate language and latest developments
Overview of the SPARQL-Generate language and latest developmentsMaxime Lefrançois
 

What's hot (20)

Introduction to RDF
Introduction to RDFIntroduction to RDF
Introduction to RDF
 
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
 
Introduction to Knowledge Graphs and Semantic AI
Introduction to Knowledge Graphs and Semantic AIIntroduction to Knowledge Graphs and Semantic AI
Introduction to Knowledge Graphs and Semantic AI
 
Programming in Spark using PySpark
Programming in Spark using PySpark      Programming in Spark using PySpark
Programming in Spark using PySpark
 
Introduction of Knowledge Graphs
Introduction of Knowledge GraphsIntroduction of Knowledge Graphs
Introduction of Knowledge Graphs
 
PySpark in practice slides
PySpark in practice slidesPySpark in practice slides
PySpark in practice slides
 
SPARQL in a nutshell
SPARQL in a nutshellSPARQL in a nutshell
SPARQL in a nutshell
 
Selecting with SPARQL
Selecting with SPARQLSelecting with SPARQL
Selecting with SPARQL
 
Introduction to Graph Databases
Introduction to Graph DatabasesIntroduction to Graph Databases
Introduction to Graph Databases
 
Vector database
Vector databaseVector database
Vector database
 
JSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked DataJSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked Data
 
MongoDB vs. Postgres Benchmarks
MongoDB vs. Postgres Benchmarks MongoDB vs. Postgres Benchmarks
MongoDB vs. Postgres Benchmarks
 
SPARQL 사용법
SPARQL 사용법SPARQL 사용법
SPARQL 사용법
 
Integrating Relational Databases with the Semantic Web: A Reflection
Integrating Relational Databases with the Semantic Web: A ReflectionIntegrating Relational Databases with the Semantic Web: A Reflection
Integrating Relational Databases with the Semantic Web: A Reflection
 
Natural Language Processing with Graph Databases and Neo4j
Natural Language Processing with Graph Databases and Neo4jNatural Language Processing with Graph Databases and Neo4j
Natural Language Processing with Graph Databases and Neo4j
 
Data Engineer, Patterns & Architecture The future: Deep-dive into Microservic...
Data Engineer, Patterns & Architecture The future: Deep-dive into Microservic...Data Engineer, Patterns & Architecture The future: Deep-dive into Microservic...
Data Engineer, Patterns & Architecture The future: Deep-dive into Microservic...
 
jQuery
jQueryjQuery
jQuery
 
Introduction to PySpark
Introduction to PySparkIntroduction to PySpark
Introduction to PySpark
 
Introduction to Knowledge Graphs: Data Summit 2020
Introduction to Knowledge Graphs: Data Summit 2020Introduction to Knowledge Graphs: Data Summit 2020
Introduction to Knowledge Graphs: Data Summit 2020
 
Overview of the SPARQL-Generate language and latest developments
Overview of the SPARQL-Generate language and latest developmentsOverview of the SPARQL-Generate language and latest developments
Overview of the SPARQL-Generate language and latest developments
 

Similar to SPARQL Cheat Sheet

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
 
Genomic Analysis in Scala
Genomic Analysis in ScalaGenomic Analysis in Scala
Genomic Analysis in ScalaRyan Williams
 
Semantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorialSemantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorialAdonisDamian
 
SPARQL-DL - Theory & Practice
SPARQL-DL - Theory & PracticeSPARQL-DL - Theory & Practice
SPARQL-DL - Theory & PracticeAdriel Café
 
The Semantics of SPARQL
The Semantics of SPARQLThe Semantics of SPARQL
The Semantics of SPARQLOlaf Hartig
 
The Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLMyungjin Lee
 
Notes from the Library Juice Academy courses on “SPARQL Fundamentals”: Univer...
Notes from the Library Juice Academy courses on “SPARQL Fundamentals”: Univer...Notes from the Library Juice Academy courses on “SPARQL Fundamentals”: Univer...
Notes from the Library Juice Academy courses on “SPARQL Fundamentals”: Univer...Allison Jai O'Dell
 
SPARQL Query Forms
SPARQL Query FormsSPARQL Query Forms
SPARQL Query FormsLeigh Dodds
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQLLino Valdivia
 
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
 
Federation and Navigation in SPARQL 1.1
Federation and Navigation in SPARQL 1.1Federation and Navigation in SPARQL 1.1
Federation and Navigation in SPARQL 1.1net2-project
 
Transformation Processing Smackdown; Spark vs Hive vs Pig
Transformation Processing Smackdown; Spark vs Hive vs PigTransformation Processing Smackdown; Spark vs Hive vs Pig
Transformation Processing Smackdown; Spark vs Hive vs PigLester Martin
 
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
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 

Similar to SPARQL Cheat Sheet (20)

Sparql
SparqlSparql
Sparql
 
Querying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQLQuerying the Semantic Web with SPARQL
Querying the Semantic Web with SPARQL
 
AnzoGraph DB - SPARQL 101
AnzoGraph DB - SPARQL 101AnzoGraph DB - SPARQL 101
AnzoGraph DB - SPARQL 101
 
Genomic Analysis in Scala
Genomic Analysis in ScalaGenomic Analysis in Scala
Genomic Analysis in Scala
 
Semantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorialSemantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorial
 
SPARQL-DL - Theory & Practice
SPARQL-DL - Theory & PracticeSPARQL-DL - Theory & Practice
SPARQL-DL - Theory & Practice
 
The Semantics of SPARQL
The Semantics of SPARQLThe Semantics of SPARQL
The Semantics of SPARQL
 
The Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQL
 
Notes from the Library Juice Academy courses on “SPARQL Fundamentals”: Univer...
Notes from the Library Juice Academy courses on “SPARQL Fundamentals”: Univer...Notes from the Library Juice Academy courses on “SPARQL Fundamentals”: Univer...
Notes from the Library Juice Academy courses on “SPARQL Fundamentals”: Univer...
 
SWT Lecture Session 3 - SPARQL
SWT Lecture Session 3 - SPARQLSWT Lecture Session 3 - SPARQL
SWT Lecture Session 3 - SPARQL
 
SPARQL Query Forms
SPARQL Query FormsSPARQL Query Forms
SPARQL Query Forms
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and 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
 
Java 8
Java 8Java 8
Java 8
 
Federation and Navigation in SPARQL 1.1
Federation and Navigation in SPARQL 1.1Federation and Navigation in SPARQL 1.1
Federation and Navigation in SPARQL 1.1
 
Transformation Processing Smackdown; Spark vs Hive vs Pig
Transformation Processing Smackdown; Spark vs Hive vs PigTransformation Processing Smackdown; Spark vs Hive vs Pig
Transformation Processing Smackdown; Spark vs Hive vs Pig
 
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
 
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQL
 
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQL
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 

More from LeeFeigenbaum

Data Segmenting in Anzo
Data Segmenting in AnzoData Segmenting in Anzo
Data Segmenting in AnzoLeeFeigenbaum
 
Intro to the Semantic Web Landscape - 2011
Intro to the Semantic Web Landscape - 2011Intro to the Semantic Web Landscape - 2011
Intro to the Semantic Web Landscape - 2011LeeFeigenbaum
 
Evolution Towards Web 3.0: The Semantic Web
Evolution Towards Web 3.0: The Semantic WebEvolution Towards Web 3.0: The Semantic Web
Evolution Towards Web 3.0: The Semantic WebLeeFeigenbaum
 
Taking the Tech out of SemTech
Taking the Tech out of SemTechTaking the Tech out of SemTech
Taking the Tech out of SemTechLeeFeigenbaum
 
CSHALS 2010 W3C Semanic Web Tutorial
CSHALS 2010 W3C Semanic Web TutorialCSHALS 2010 W3C Semanic Web Tutorial
CSHALS 2010 W3C Semanic Web TutorialLeeFeigenbaum
 
What;s Coming In SPARQL2?
What;s Coming In SPARQL2?What;s Coming In SPARQL2?
What;s Coming In SPARQL2?LeeFeigenbaum
 
Semantic Web Landscape 2009
Semantic Web Landscape 2009Semantic Web Landscape 2009
Semantic Web Landscape 2009LeeFeigenbaum
 

More from LeeFeigenbaum (8)

Data Segmenting in Anzo
Data Segmenting in AnzoData Segmenting in Anzo
Data Segmenting in Anzo
 
Intro to the Semantic Web Landscape - 2011
Intro to the Semantic Web Landscape - 2011Intro to the Semantic Web Landscape - 2011
Intro to the Semantic Web Landscape - 2011
 
Evolution Towards Web 3.0: The Semantic Web
Evolution Towards Web 3.0: The Semantic WebEvolution Towards Web 3.0: The Semantic Web
Evolution Towards Web 3.0: The Semantic Web
 
Taking the Tech out of SemTech
Taking the Tech out of SemTechTaking the Tech out of SemTech
Taking the Tech out of SemTech
 
CSHALS 2010 W3C Semanic Web Tutorial
CSHALS 2010 W3C Semanic Web TutorialCSHALS 2010 W3C Semanic Web Tutorial
CSHALS 2010 W3C Semanic Web Tutorial
 
What;s Coming In SPARQL2?
What;s Coming In SPARQL2?What;s Coming In SPARQL2?
What;s Coming In SPARQL2?
 
SPARQL 1.1 Status
SPARQL 1.1 StatusSPARQL 1.1 Status
SPARQL 1.1 Status
 
Semantic Web Landscape 2009
Semantic Web Landscape 2009Semantic Web Landscape 2009
Semantic Web Landscape 2009
 

Recently uploaded

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

SPARQL Cheat Sheet

  • 1. SPARQL By Example: The Cheat Sheet Accompanies slides at: http://www.cambridgesemantics.com/semantic-university/sparql-by-example Comments & questions to: Lee Feigenbaum <lee@cambridgesemantics.com> VP Marketing & Technology, Cambridge Semantics Co-chair, W3C SPARQL Working Group
  • 2. Conventions Red text means: “This is a core part of the SPARQL syntax or language.” Blue text means: “This is an example of query-specific text or values that might go into a SPARQL query.”
  • 3. Nuts & Bolts Write full URIs: <http://this.is.a/full/URI/written#out> Abbreviate URIs with prefixes: PREFIX foo: <http://this.is.a/URI/prefix#> … foo:bar …  http://this.is.a/URI/prefix#bar Shortcuts: a  rdf:type URIs Plain literals: “a plain literal” Plain literal with language tag: “bonjour”@fr Typed literal: “13”^^xsd:integer Shortcuts: true  “true”^^xsd:boolean 3  “3”^^xsd:integer 4.2  “4.2”^^xsd:decimal Literals Variables: ?var1, ?anotherVar, ?and_one_more Variables Comments: # Comments start with a „#‟ and # continue to the end of the line Comments Match an exact RDF triple: ex:myWidget ex:partNumber “XY24Z1” . Match one variable: ?person foaf:name “Lee Feigenbaum” . Match multiple variables: conf:SemTech2009 ?property ?value . Triple Patterns
  • 4. Common Prefixes More common prefixes at http://prefix.cc prefix... …stands for rdf: http://xmlns.com/foaf/0.1/ rdfs: http://www.w3.org/2000/01/rdf-schema# owl: http://www.w3.org/2002/07/owl# xsd: http://www.w3.org/2001/XMLSchema# dc: http://purl.org/dc/elements/1.1/ foaf: http://xmlns.com/foaf/0.1/
  • 5. Anatomy of a Query PREFIX foo: <…> PREFIX bar: <…> … SELECT … FROM <…> FROM NAMED <…> WHERE { … } GROUP BY … HAVING … ORDER BY … LIMIT … OFFSET … VALUES … Declare prefix shortcuts (optional) Query result clause Query pattern Query modifiers (optional) Define the dataset (optional)
  • 6. 4 Types of SPARQL Queries Project out specific variables and expressions: SELECT ?c ?cap (1000 * ?people AS ?pop) Project out all variables: SELECT * Project out distinct combinations only: SELECT DISTINCT ?country Results in a table of values (in XML or JSON): SELECT queries ?c ?cap ?pop ex:France ex:Paris 63,500,000 ex:Canada ex:Ottawa 32,900,000 ex:Italy ex:Rome 58,900,000 Construct RDF triples/graphs: CONSTRUCT { ?country a ex:HolidayDestination ; ex:arrive_at ?capital ; ex:population ?population . } Results in RDF triples (in any RDF serialization): ex:France a ex:HolidayDestination ; ex:arrive_at ex:Paris ; ex:population 635000000 . ex:Canada a ex:HolidayDestination ; ex:arrive_at ex:Ottawa ; ex:population 329000000 . CONSTRUCT queries Ask whether or not there are any matches: ASK Result is either “true” or “false” (in XML or JSON): true, false ASK queries Describe the resources matched by the given variables: DESCRIBE ?country Result is RDF triples (in any RDF serialization) : ex:France a geo:Country ; ex:continent geo:Europe ; ex:flag <http://…/flag-france.png> ; … DESCRIBE queries
  • 7. Combining SPARQL Graph Patterns Consider A and B as graph patterns. A Basic Graph Pattern – one or more triple patterns A . B  Conjunction. Join together the results of solving A and B by matching the values of any variables in common. Optional Graph Patterns A OPTIONAL { B }  Left join. Join together the results of solving A and B by matching the values of any variables in common, if possible. Keep all solutions from A whether or not there’s a matching solution in B
  • 8. Combining SPARQL Graph Patterns Consider A and B as graph patterns. Either-or Graph Patterns { A } UNION { B }  Disjunction. Include both the results of solving A and the results of solving B. “Subtracted” Graph Patterns (SPARQL 1.1) A MINUS { B }  Negation. Solve A. Solve B. Include only those results from solving A that are not compatible with any of the results from B.
  • 9. SPARQL Subqueries (SPARQL 1.1) Consider A and B as graph patterns. A . { SELECT … WHERE { B } } C .  Join the results of the subquery with the results of solving A and C.
  • 10. SPARQL Filters • SPARQL FILTERs eliminate solutions that do not cause an expression to evaluate to true. • Place FILTERs in a query inline within a basic graph pattern A . B . FILTER ( …expr… )
  • 11. Category Functions / Operators Examples Logical & Comparisons !, &&, ||, =, !=, <, <=, >, >=, IN, NOT IN ?hasPermit || ?age < 25 Conditionals (SPARQL 1.1) EXISTS, NOT EXISTS, IF, COALESCE NOT EXISTS { ?p foaf:mbox ?email } Math +, -, *, /, abs, round, ceil, floor, RAND ?decimal * 10 > ?minPercent Strings (SPARQL 1.1) STRLEN, SUBSTR, UCASE, LCASE, STRSTARTS, CONCAT, STRENDS, CONTAINS, STRBEFORE, STRAFTER STRLEN(?description) < 255 Date/time (SPARQL 1.1) now, year, month, day, hours, minutes, seconds, timezone, tz month(now()) < 4 SPARQL tests isURI, isBlank, isLiteral, isNumeric, bound isURI(?person) || !bound(?person) Constructors (SPARQL 1.1) URI, BNODE, STRDT, STRLANG, UUID, STRUUID STRLANG(?text, “en”) = “hello”@en Accessors str, lang, datatype lang(?title) = “en” Hashing (1.1) MD5, SHA1, SHA256, SHA512 BIND(SHA256(?email) AS ?hash) Miscellaneous sameTerm, langMatches, regex, REPLACE regex(?ssn, “d{3}-d{2}-d{4}”)
  • 12. Aggregates (SPARQL 1.1) 1. Partition results into groups based on the expression(s) in the GROUP BY clause 2. Evaluate projections and aggregate functions in SELECT clause to get one result per group 3. Filter aggregated results via the HAVING clause ?key ?val ?other1 1 4 … 1 4 … 2 5 … 2 4 … 2 10 … 2 2 … 2 1 … 3 3 … ?key ?sum_of_val 1 8 2 22 3 3 ?key ?sum_of_val 1 8 3 3 SPARQL 1.1 includes: COUNT, SUM, AVG, MIN, MAX, SAMPLE, GROUP_CONCAT
  • 13. Property Paths (SPARQL 1.1) • Property paths allow triple patterns to match arbitrary- length paths through a graph • Predicates are combined with regular-expression-like operators: Construct Meaning path1/path2 Forwards path (path1 followed by path2) ^path1 Backwards path (object to subject) path1|path2 Either path1 or path2 path1* path1, repeated zero or more times path1+ path1, repeated one or more times path1? path1, optionally !uri Any predicate except uri !^uri Any backwards (object to subject) predicate except uri
  • 14. RDF Datasets A SPARQL queries a default graph (normally) and zero or more named graphs (when inside a GRAPH clause). ex:g1 ex:g2 ex:g3 Default graph (the merge of zero or more graphs) Named graphs ex:g1 ex:g4 PREFIX ex: <…> SELECT … FROM ex:g1 FROM ex:g4 FROM NAMED ex:g1 FROM NAMED ex:g2 FROM NAMED ex:g3 WHERE { … A … GRAPH ex:g3 { … B … } GRAPH ?graph { … C … } } OR OR
  • 15. SPARQL Over HTTP (the SPARQL Protocol) http://host.domain.com/sparql/endpoint?<parameters> where <parameters> can include: query=<encoded query string> e.g. SELECT+*%0DWHERE+{… default-graph-uri=<encoded graph URI> e.g. http%3A%2F%2Fexmaple.com%2Ffoo… n.b. zero of more occurrences of default-graph-uri named-graph-uri=<encoded graph URI> e.g. http%3A%2F%2Fexmaple.com%2Fbar… n.b. zero of more occurrences of named-graph-uri HTTP GET or POST. Graphs given in the protocol override graphs given in the query.
  • 16. Federated Query (SPARQL 1.1) PREFIX ex: <…> SELECT … FROM ex:g1 WHERE { … A … SERVICE ex:s1 { … B … } SERVICE ex:s2 { … C … } } ex:g1 Web SPARQL Endpoint ex:s2 SPARQL Endpoint ex:s1 Local Graph Store
  • 17. SPARQL 1.1 Update SPARQL Update Language Statements INSERT DATA { triples } DELETE DATA {triples} [ DELETE { template } ] [ INSERT { template } ] WHERE { pattern } LOAD <uri> [ INTO GRAPH <uri> ] CLEAR GRAPH <uri> CREATE GRAPH <uri> DROP GRAPH <uri> [ … ] denotes optional parts of SPARQL 1.1 Update syntax
  • 18. Some Public SPARQL Endpoints Name URL What’s there? SPARQLer http://sparql.org/sparql.html General-purpose query endpoint for Web-accessible data DBPedia http://dbpedia.org/sparql Extensive RDF data from Wikipedia DBLP http://www4.wiwiss.fu-berlin.de/dblp/snorql/ Bibliographic data from computer science journals and conferences LinkedMDB http://data.linkedmdb.org/sparql Films, actors, directors, writers, producers, etc. World Factbook http://www4.wiwiss.fu- berlin.de/factbook/snorql/ Country statistics from the CIA World Factbook bio2rdf http://bio2rdf.org/sparql Bioinformatics data from around 40 public databases
  • 19. SPARQL Resources • SPARQL Specifications Overview – http://www.w3.org/TR/sparql11-overview/ • SPARQL implementations – http://esw.w3.org/topic/SparqlImplementations • SPARQL endpoints – http://esw.w3.org/topic/SparqlEndpoints • SPARQL Frequently Asked Questions – http://www.thefigtrees.net/lee/sw/sparql-faq • Common SPARQL extensions – http://esw.w3.org/topic/SPARQL/Extensions