Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

SPARQL Cheat Sheet


Published on

"SPARQL Cheat Sheet" is a short collection of slides intended to act as a guide to SPARQL developers. It includes the syntax and structure of SPARQL queries, common SPARQL prefixes and functions, and help with RDF datasets.

The "SPARQL Cheat Sheet" is intended to accompany the SPARQL By Example slides available at .

Published in: Technology, Education

SPARQL Cheat Sheet

  1. 1. SPARQL By Example:The Cheat SheetAccompanies slides at: & questions to:Lee Feigenbaum <>VP Marketing & Technology, Cambridge SemanticsCo-chair, W3C SPARQL Working Group
  2. 2. ConventionsRed text means:“This is a core part of the SPARQL syntax orlanguage.”Blue text means:“This is an example of query-specific text orvalues that might go into a SPARQL query.”
  3. 3. Nuts & BoltsWrite full URIs:<>Abbreviate URIs with prefixes:PREFIX foo: <>… foo:bar …  rdf:typeURIsPlain literals:“a plain literal”Plain literal with language tag:“bonjour”@frTyped literal:“13”^^xsd:integerShortcuts:true  “true”^^xsd:boolean3  “3”^^xsd:integer4.2  “4.2”^^xsd:decimalLiteralsVariables:?var1, ?anotherVar, ?and_one_moreVariablesComments:# Comments start with a „#‟ and# continue to the end of the lineCommentsMatch 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. 4. Common PrefixesMore common prefixes at http://prefix.ccprefix... …stands forrdf:
  5. 5. Anatomy of a QueryPREFIX foo: <…>PREFIX bar: <…>…SELECT …FROM <…>FROM NAMED <…>WHERE {…}GROUP BY …HAVING …ORDER BY …LIMIT …OFFSET …VALUES …Declare prefixshortcuts(optional)Query resultclauseQuery patternQuery modifiers(optional)Define thedataset (optional)
  6. 6. 4 Types of SPARQL QueriesProject out specific variables and expressions:SELECT ?c ?cap (1000 * ?people AS ?pop)Project out all variables:SELECT *Project out distinct combinations only:SELECT DISTINCT ?countryResults in a table of values (in XML or JSON):SELECT queries?c ?cap ?popex:France ex:Paris 63,500,000ex:Canada ex:Ottawa 32,900,000ex:Italy ex:Rome 58,900,000Construct 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 queriesAsk whether or not there are any matches:ASKResult is either “true” or “false” (in XML or JSON):true, falseASK queriesDescribe the resources matched by the given variables:DESCRIBE ?countryResult 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. 7. Combining SPARQL Graph PatternsConsider A and B as graph patterns.A Basic Graph Pattern – one or more triple patternsA . B Conjunction. Join together the results of solving A and B by matching thevalues of any variables in common.Optional Graph PatternsA OPTIONAL { B } Left join. Join together the results of solving A and B by matching thevalues of any variables in common, if possible. Keep all solutions from A whether ornot there’s a matching solution in B
  8. 8. Combining SPARQL Graph PatternsConsider A and B as graph patterns.Either-or Graph Patterns{ A } UNION { B } Disjunction. Include both the results of solving A and the results ofsolving B.“Subtracted” Graph Patterns (SPARQL 1.1)A MINUS { B } Negation. Solve A. Solve B. Include only those results from solving A thatare not compatible with any of the results from B.
  9. 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. 10. SPARQL Filters• SPARQL FILTERs eliminate solutions that do not cause anexpression to evaluate to true.• Place FILTERs in a query inline within a basic graph patternA . B . FILTER ( …expr… )
  11. 11. Category Functions / Operators ExamplesLogical &Comparisons!, &&, ||, =, !=, <, <=, >,>=, IN, NOT IN?hasPermit || ?age < 25Conditionals(SPARQL 1.1)EXISTS, NOT EXISTS, IF,COALESCENOT EXISTS { ?p foaf:mbox ?email }Math+, -, *, /, abs, round,ceil, floor, RAND?decimal * 10 > ?minPercentStrings(SPARQL 1.1)STRLEN, SUBSTR, UCASE,LCASE, STRSTARTS, CONCAT,STRENDS, CONTAINS,STRBEFORE, STRAFTERSTRLEN(?description) < 255Date/time(SPARQL 1.1)now, year, month, day,hours, minutes, seconds,timezone, tzmonth(now()) < 4SPARQL testsisURI, isBlank,isLiteral, isNumeric,boundisURI(?person) || !bound(?person)Constructors(SPARQL 1.1)URI, BNODE, STRDT,STRLANG, UUID, STRUUIDSTRLANG(?text, “en”) = “hello”@enAccessors str, lang, datatype lang(?title) = “en”Hashing (1.1) MD5, SHA1, SHA256, SHA512 BIND(SHA256(?email) AS ?hash)MiscellaneoussameTerm, langMatches,regex, REPLACEregex(?ssn, “d{3}-d{2}-d{4}”)
  12. 12. Aggregates (SPARQL 1.1)1. Partition results intogroups based on theexpression(s) in theGROUP BY clause2. Evaluate projectionsand aggregate functionsin SELECT clause to getone result per group3. Filter aggregatedresults via the HAVINGclause?key ?val ?other11 4 …1 4 …2 5 …2 4 …2 10 …2 2 …2 1 …3 3 …?key ?sum_of_val1 82 223 3?key ?sum_of_val1 83 3SPARQL 1.1 includes: COUNT, SUM, AVG, MIN, MAX, SAMPLE, GROUP_CONCAT
  13. 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-likeoperators:Construct Meaningpath1/path2 Forwards path (path1 followed by path2)^path1 Backwards path (object to subject)path1|path2 Either path1 or path2path1* path1, repeated zero or more timespath1+ path1, repeated one or more timespath1? path1, optionally!uri Any predicate except uri!^uri Any backwards (object to subject) predicate except uri
  14. 14. RDF DatasetsA SPARQL queries a default graph (normally) and zero ormore named graphs (when inside a GRAPH clause).ex:g1ex:g2ex:g3Default graph(the merge of zero or more graphs)Named graphsex:g1ex:g4PREFIX ex: <…>SELECT …FROM ex:g1FROM ex:g4FROM NAMED ex:g1FROM NAMED ex:g2FROM NAMED ex:g3WHERE {… A …GRAPH ex:g3 {… B …}GRAPH ?graph {… C …}}OROR
  15. 15. SPARQL Over HTTP (the SPARQL Protocol)<parameters>where <parameters> can include:query=<encoded query string>e.g. SELECT+*%0DWHERE+{…default-graph-uri=<encoded graph URI>e.g.…n.b. zero of more occurrences of default-graph-urinamed-graph-uri=<encoded graph URI>e.g.…n.b. zero of more occurrences of named-graph-uriHTTP GET or POST. Graphs given in the protocol override graphs given in thequery.
  16. 16. Federated Query (SPARQL 1.1)PREFIX ex: <…>SELECT …FROM ex:g1WHERE {… A …SERVICE ex:s1 {… B …}SERVICE ex:s2 {… C …}}ex:g1WebSPARQL Endpointex:s2SPARQL Endpointex:s1Local Graph Store
  17. 17. SPARQL 1.1 UpdateSPARQL Update Language StatementsINSERT 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. 18. Some Public SPARQL EndpointsName URL What’s there?SPARQLer queryendpoint for Web-accessibledataDBPedia RDF data fromWikipediaDBLP data fromcomputer science journalsand conferencesLinkedMDB, actors, directors,writers, producers, etc.WorldFactbook statistics from theCIA World Factbookbio2rdf data fromaround 40 public databases
  19. 19. SPARQL Resources• SPARQL Specifications Overview–• SPARQL implementations–• SPARQL endpoints–• SPARQL Frequently Asked Questions–• Common SPARQL extensions–