Tutorial V:
Covers SPARQL Extensions for:
Aggregates, Date Arithmetic, Updates, Deletes,
Sub-queries, Path Expressions and Inference Rules

OpenLink Software

Live Instances

All the queries in this tutorial can be verified against the following live instances:

For each of these instances you have /sparql (basic SPARQL Endpoint) and /isparql (SPARQL Query By Example UI and Endpoint).

Sub-Queries



Sub-queries

Scalar Subquery and Existence

## Find a Person Entities named "Stefan Jenkner"
## that knows at least on person named "Christin":

SELECT ?x
WHERE
  {
    ?x  foaf:name  "Stefan Jenkner"  .
    FILTER
      (
        bif:exists
          ( (
             SELECT *
             WHERE
               {
                 ?x  foaf:knows  ?y      .
                 ?y  foaf:name   "Christin"
               }
          ) )
      )
  }

## See LOD live results.

Nested DISTINCT subquery with Scalars and Order By

## "Nested DISTINCT subquery
## with Scalars and Order By":

SELECT DISTINCT ?n
  ((
     SELECT COUNT (*)
     WHERE
       {
         ?p   foaf:interest  ?i  .
         ?ps  foaf:interest  ?i
       }
  ))
  ((
     SELECT COUNT (*)
     WHERE
       {
         ?p  foaf:interest  ?i
       }
  ))
WHERE
  {
    ?ps  foaf:nick  "brisch"@en  .
    {
      SELECT DISTINCT ?p ?psi
      WHERE
        {
          ?p    foaf:interest  ?i .
          ?psi  foaf:interest  ?i
        }
     } .
     FILTER
       (
         ?ps  =  ?psi
       )
       ?p  foaf:nick  ?n
  }
ORDER BY DESC 2
LIMIT 50

## See LOD live results.

Distinctive Shared Interests

## "Find pairs of people interested
## in the same specialty where the two people
## do not know each other":

SELECT ?i
       ?cnt
       ?n1
       ?n2
       ?p1
       ?p2
WHERE
  {
    {
      SELECT ?i
             COUNT (*) AS ?cnt
      WHERE
        {
          ?p  foaf:interest  ?i
        }
      GROUP BY ?i
    }
    FILTER
      (
        ?cnt  >  1
        &&
        ?cnt  <  10
      ) .
    ?p1  foaf:interest  ?i  .
    ?p2  foaf:interest  ?i  .
    FILTER
      (
        ?p1  !=  ?p2
        &&
        !bif:exists
          ((
             SELECT (1)
             WHERE
               {
                 ?p1  foaf:knows  ?p2
               }
          )) &&
        !bif:exists
          ((
             SELECT (1)
             WHERE
               {
                 ?p2  foaf:knows  ?p1
               }
          ))
      ) .
    ?p1  foaf:nick  ?n1  .
    ?p2  foaf:nick  ?n2
  }
ORDER BY ?cnt
LIMIT 10

## See LOD live results.

SPARQL Subquery for enabling literal values based joins: Variant I

## "Use subqueries to enable literal values based joins:"

PREFIX nie: <http://www.semanticdesktop.org/ontologies/nie#>
PREFIX nao: <http://www.semanticdesktop.org/ontologies/nao#>

SELECT DISTINCT ?r
WHERE
  {
    graph ?g
      {
        ?r nie:url ?url .
      } .
    ?g nao:maintainedBy ?app .
    FILTER (?app = (SELECT ?a WHERE { ?a nao:identifier "nepomukindexer" }))
  }

SPARQL Subquery for enabling literal values based joins: Variant II

## "Use subqueries to enable literal values based joins:"

PREFIX nie: <http://www.semanticdesktop.org/ontologies/nie#>
PREFIX nao: <http://www.semanticdesktop.org/ontologies/nao#>

SELECT DISTINCT ?r
WHERE
  {
    graph ?g
      {
        ?r nie:url ?url .
      } .
    ?g nao:maintainedBy
     `(
        SELECT ?a
        WHERE
          {
            ?a nao:identifier "nepomukindexer"
          }
     )` .
  }

Path Expressions



Path Expressions

Find all names and optionally mailboxes of friends

## "Find all names and optionally mailboxes
## of friends of all Melvin Carvalho who know a Michael Hausenblas":

SELECT ?f+>foaf:name
       ?f*>foaf:mbox
WHERE
  {
    ?x  foaf:name   "Melvin Carvalho"  .
    ?x  foaf:knows  ?f       .
    FILTER
      (
        ?f+>foaf:name  =  "Michael Hausenblas"
      )
  }

The same query could be written:

SELECT ?fname
       ?mbox
WHERE
  {
     ?x   foaf:knows  ?f       .
     OPTIONAL
       {
         ?f  foaf:mbox   ?mbox
       }  .
     ?f   foaf:name   ?fname   .
     ?x   foaf:name   "Melvin Carvalho"  .
     ?x   foaf:knows  ?f2      .
     ?f2  foaf:name   "Michael Hausenblas"
  }

## See LOD live results.

Full Text Queries & Text Scores Filtering



Full Text Queries & Text Scores Filtering

Text Scores

## "Text Scores
## incorporated into SPARQL":

SELECT *
WHERE
  {
    ?s ?p ?o .
    ?o bif:contains 'NEW AND YORK'
    OPTION (score ?sc) .
  }
ORDER BY DESC (?sc)
LIMIT 10

## See dbpedia live results.

## See LOD live results.

Entity Ranking & Score



Entity Ranking & Score

Entity Ranking

## "Entity Ranking":

PREFIX yago: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>

SELECT DISTINCT ?s2 AS ?c1
       ( <LONG::IRI_RANK> (?s2) ) AS ?Rank
WHERE
  {
    ?s1 ?s1textp ?o1 .
    ?o1 bif:contains 'Shakespeare' .
    ?s1 a yago:Writer110794014 .
    ?s2 prop:writer ?s1
  }
ORDER BY DESC ( <LONG::IRI_RANK> (?s2) )

## See dbpedia live results.

## See LOD live results.

Entity Ranking and Score

## Searching over labels, with text match
## scores and additional ranks for each
## iri / resource:

SELECT ?s ?page ?label
      ?textScore AS ?Text_Score_Rank
      ( <LONG::IRI_RANK> (?s) ) AS ?Entity_Rank
WHERE
  {
    ?s foaf:page ?page .
    ?s rdfs:label ?label .
    FILTER( lang( ?label ) = "en" ) .
    ?label bif:contains 'adobe and flash'
    OPTION (score ?textScore ) .
   }

## See LOD live results.

XCONTAINS & IN Operator



XCONTAINS & IN Operator

XCONTAINS

## "xcontains usage":

SELECT *
FROM <http://mygraph.com>
WHERE
  {
    ?s ?p ?o .
    ?o bif:xcontains "//Hello[text-contains (., 'world')]"
  }

Operator IN

## "Operatior IN usage":

SELECT ?s1 ?s2 COUNT (1)
WHERE
  {
    ?s1 ?p ?o .
    FILTER (
             ?s1 IN
              (
                <http://dbpedia.org/resource/Climate_change>,
                <http://dbpedia.org/resource/Disaster_risk_reduction>,
                <http://dbpedia.org/resource/Tanzania>,
                <http://dbpedia.org/resource/Capacity_building>,
                <http://dbpedia.org/resource/Poverty>,
                <http://dbpedia.org/resource/Construction>,
                <http://dbpedia.org/resource/Vulnerability>,
                <http://dbpedia.org/resource/Mount_Kilimanjaro>,
                <http://dbpedia.org/resource/Social_vulnerability>
              )
            )
    ?s2 ?p ?o .
    FILTER (
             ?s2 IN
             (
               <http://dbpedia.org/resource/Climate_change>,
               <http://dbpedia.org/resource/Disaster_risk_reduction>,
               <http://dbpedia.org/resource/Tanzania>,
               <http://dbpedia.org/resource/Capacity_building>,
               <http://dbpedia.org/resource/Poverty>,
               <http://dbpedia.org/resource/Construction>,
               <http://dbpedia.org/resource/Vulnerability>,
               <http://dbpedia.org/resource/Mount_Kilimanjaro>,
               <http://dbpedia.org/resource/Social_vulnerability>
             )
           )
    FILTER ( ?s1 != ?s2 )
    FILTER ( str( ?s1 ) < str ( ?s2 ) )
  }
LIMIT 20

## See dbpedia live results.

## See LOD live results.

Negation



Negation

Negation: DISTINCT

SELECT DISTINCT ?x ?o
WHERE
  {
    ?x a foaf:Agent .
    ?x ?p ?o .
    FILTER (
            !bif:exists
              (
                (
                  SELECT (1)
                  WHERE
                    {
                      ?x a foaf:Person
                    }
                )
              )
           )
  }
LIMIT 10

## See LOD live results.

Negation: DESCRIBE

DESCRIBE ?x
WHERE
  {
    ?x a foaf:Agent .
    FILTER (
            !bif:exists
              (
                (
                  SELECT (1)
                  WHERE
                    {
                      ?x a foaf:Person
                    }
                )
              )
           )
  }
LIMIT 200

## See LOD live results.

Aggregates



Aggregates

MAX

## "Find which town or city in
## the UK has the largest proportion of students":

PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
PREFIX dbpedia-owl-uni: <http://dbpedia.org/ontology/University/>
PREFIX dbpedia-owl-inst: <http://dbpedia.org/ontology/EducationalInstitution/>

SELECT ?town COUNT(?uni)
       ?pgrad ?ugrad
       MAX(?population)
       ( ((?pgrad+?ugrad)/ MAX(?population))*100 ) AS ?percentage
WHERE
  {
    ?uni dbpedia-owl-inst:country dbpedia:United_Kingdom ;
                         dbpedia-owl-uni:postgrad ?pgrad ;
                        dbpedia-owl-uni:undergrad ?ugrad ;
                             dbpedia-owl-inst:city ?town .
    OPTIONAL
        {
          ?town dbpedia-owl:populationTotal ?population .
          FILTER (?population > 0 )
        }
  }
GROUP BY ?town ?pgrad ?ugrad
HAVING ( ( ( (?pgrad+?ugrad)/ MAX(?population) )*100 ) > 0 )
ORDER BY DESC 6

SUM

## "Aggregate Distance Values Over Years":

PREFIX dst: <http://linkedgeodata.org/vocabulary#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT (bif:year( bif:stringdate(?sdate)) AS ?syear)
       (bif:sum( bif:number(?dist)) AS ?distance)
FROM <urn:dates:distances>
WHERE
  {
    ?row dc:date ?sdate .
    ?row dst:distance ?dist
  }
GROUP BY (bif:year(bif:stringdate(?sdate)))
ORDER BY ASC(bif:year(bif:stringdate(?sdate)))

Date Arithmetic



Date Arithmetic

Calculate Age based on Birth and Death Dates

## "Sample listing of musicians that includes age at time of death":

SELECT ?s ?genre ?died ?born
   (bif:datediff('year', xsd:dateTime(str(?born)), xsd:dateTime(str(?died)))) AS ?age
WHERE
  {
    {
      SELECT DISTINCT ?s ?genre ?died ?born
      FROM <http://dbpedia.org>
      WHERE
        {
          ?s a <http://dbpedia.org/ontology/MusicalArtist> ;
                <http://dbpedia.org/ontology/genre> ?genre ;
             <http://dbpedia.org/ontology/deathDate> ?died ;
             <http://dbpedia.org/ontology/birthDate> ?born .
        }
      LIMIT 20
    }
  }

## See dbpedia live results.

## See LOD live results.

Calculated Death Age using Data Cleansed Dates

## "Sample listing of musicians (includes use of
## IF for data cleansing) that includes age at time of death ":

SELECT ?person ?genre ?died ?born
       (
         IF
           (
             ( datatype (?born) in (xsd:dateTime, xsd:date) )
             and
             ( datatype (?died) in (xsd:dateTime, xsd:date) ),
             bif:datediff
               (
                 'year',
                 xsd:dateTime( str(?born) ),
                 xsd:dateTime( str(?died) )
               ),
             "error"
           )
       ) AS ?age
WHERE
  {
    {
      SELECT DISTINCT ?person ?genre ?died ?born
      FROM <http://dbpedia.org>
      WHERE
        {
          ?person a <http://dbpedia.org/ontology/MusicalArtist> ;
          <http://dbpedia.org/ontology/genre> ?genre ;
          <http://dbpedia.org/ontology/deathDate> ?died ;
          <http://dbpedia.org/ontology/birthDate> ?born .
        }
      ORDER BY DESC ( <LONG::IRI_RANK> (?person) )
      LIMIT 100
    }
  }

## See dbpedia live results.

## See LOD live results.

Calculate Age and Order by Entity Rank

## "Sample listing of musicians that includes birth date, death date,
## and age ordered by musicians entity rank ":

SELECT DISTINCT ?person ?plabel ?genre ?glabel ?died
    ?born ( <LONG::IRI_RANK> (?person) ) as ?rank
    (
      IF
        (
          ( datatype (?born) in (xsd:dateTime, xsd:date) )
          and
          ( datatype (?died) in (xsd:dateTime, xsd:date) ),
          bif:datediff
            (
              'year',
              xsd:dateTime( str(?born) ),
              xsd:dateTime( str(?died) )
            ),
          "error"
        )
    ) AS ?age
WHERE
  {
    {
      SELECT DISTINCT ?person ?plabel ?genre ?glabel ?died ?born
      FROM <http://dbpedia.org>
      WHERE
        {
          ?person a <http://dbpedia.org/ontology/MusicalArtist> ;
                     <http://dbpedia.org/ontology/genre> ?genre ;
                  <http://dbpedia.org/ontology/deathDate> ?died ;
                                             rdfs:label ?plabel ;
                  <http://dbpedia.org/ontology/birthDate> ?born .
          ?genre rdfs:label ?glabel .
          FILTER (lang(?plabel) = "en")
          FILTER (lang(?glabel) = "en")
        }
      ORDER BY DESC ( <LONG::IRI_RANK> (?person) )
      LIMIT 100
    }
  }

## See dbpedia live results.

## See LOD live results.

Calculate Average Death Age

## "Sample listing of musicians that includes
## average age at time of death, by genre":

SELECT ?genre, (avg(?age)) AS ?avg
WHERE
  {
    {
      SELECT DISTINCT ?genre ?person
        (
          bif:datediff
            (
              'year',
              xsd:dateTime( str(?born) ),
              xsd:dateTime( str(?died) )
            )
        ) as ?age
      WHERE
        {
          {
            SELECT DISTINCT ?person ?genre ?died ?born
            FROM <http://dbpedia.org>
            WHERE
              {
                ?person a <http://dbpedia.org/ontology/MusicalArtist> ;
                           <http://dbpedia.org/ontology/genre> ?genre ;
                        <http://dbpedia.org/ontology/deathDate> ?died ;
                        <http://dbpedia.org/ontology/birthDate> ?born .
                FILTER ( datatype (?born) IN (xsd:dateTime, xsd:date) )
                FILTER ( datatype (?died) IN (xsd:dateTime, xsd:date) )
              }
          }
        }
    }
  }
GROUP BY (?genre)
ORDER BY DESC (?avg)
LIMIT 100

Calculate Average Death Age with Entity Rank

## "Sample listing of musicians that includes
## average age at time of death with entity rank, by genre":

SELECT ?genre, (avg(?age)) AS ?avg,
    ( <LONG::IRI_RANK> (?person) ) as ?rank
WHERE
  {
    {
      SELECT DISTINCT ?genre ?person
        (
          bif:datediff
            (
              'year',
              xsd:dateTime( str(?born) ),
              xsd:dateTime( str(?died) )
            )
        ) as ?age
      WHERE
        {
          {
            SELECT DISTINCT ?person ?genre ?died ?born
            FROM <http://dbpedia.org>
            WHERE
              {
                ?person a <http://dbpedia.org/ontology/MusicalArtist> ;
                           <http://dbpedia.org/ontology/genre> ?genre ;
                        <http://dbpedia.org/ontology/deathDate> ?died ;
                        <http://dbpedia.org/ontology/birthDate> ?born .
                FILTER ( datatype (?born) IN (xsd:dateTime, xsd:date) )
                FILTER ( datatype (?died) IN (xsd:dateTime, xsd:date) )
              }
          }
        }
      ORDER BY DESC ( <LONG::IRI_RANK> (?person) )
    }
  }
ORDER BY DESC (?avg)
LIMIT 100

Calculate Average Death Age with Entity Rank and Pretty Labels

## "Sample listing of musicians that includes
## average age at time of death with entity rank,
## by genre and pretty labels":

SELECT ?genre, str(?glabel) as ?genre_names, (avg(?age)) AS ?avg,
    ( <LONG::IRI_RANK> (?person) ) as ?rank
WHERE
  {
    {
      SELECT DISTINCT ?genre ?person ?glabel
        (
          IF
            (
              ( datatype (?born) in (xsd:dateTime, xsd:date) )
              and
              ( datatype (?died) in (xsd:dateTime, xsd:date) ),
              bif:datediff
                (
                  'year',
                  xsd:dateTime(str(?born)),
                  xsd:dateTime(str(?died))
                ),
                "error"
        ) as ?age
      WHERE
        {
          {
            SELECT DISTINCT ?person ?genre ?glabel ?died ?born
            FROM <http://dbpedia.org>
            WHERE
              {
                ?person a <http://dbpedia.org/ontology/MusicalArtist> ;
                           <http://dbpedia.org/ontology/genre> ?genre ;
                        <http://dbpedia.org/ontology/deathDate> ?died ;
                        <http://dbpedia.org/ontology/birthDate> ?born .
                FILTER ( datatype (?born) IN (xsd:dateTime, xsd:date) )
                FILTER ( datatype (?died) IN (xsd:dateTime, xsd:date) )
                ?genre rdfs:label ?glabel .
                FILTER ( lang(?glabel) = "en" ) .
                FILTER (?born < ?died) .
              }
          }
        }
      ORDER BY DESC ( <LONG::IRI_RANK> (?person) )
    }
  }
ORDER BY DESC (?avg)
LIMIT 100

Average Age, Entity Rank, Grouping and Pretty Labels

## "Sample listing of musicians that includes
## Entity Rank, Grouping and Pretty Labels":

SELECT DISTINCT ?person str(?plabel) ?genre str(?glabel)
    ?died ?born ( <LONG::IRI_RANK> (?person) ) as ?rank
    (
      IF
        (
          ( datatype (?born) in (xsd:dateTime, xsd:date) )
          and
          ( datatype (?died) in (xsd:dateTime, xsd:date) ),
          bif:datediff
            (
              'year',
              xsd:dateTime(str(?born)),
              xsd:dateTime(str(?died))
            ),
            "error"
        )
    ) AS ?age
WHERE
  {
    {
      SELECT DISTINCT ?person ?plabel ?genre ?glabel ?died ?born
      FROM <http://dbpedia.org>
      WHERE
        {
          ?person a <http://dbpedia.org/ontology/MusicalArtist> ;
                     <http://dbpedia.org/ontology/genre> ?genre ;
                  <http://dbpedia.org/ontology/deathDate> ?died ;
                                             rdfs:label ?plabel ;
          <http://dbpedia.org/ontology/birthDate> ?born .
          ?genre rdfs:label ?glabel .
          FILTER ( lang(?plabel) = "en" )
          FILTER ( lang(?glabel) = "en" )
        }
      ORDER BY DESC ( <LONG::IRI_RANK> (?person) )
      LIMIT 100
    }
  }

## See dbpedia live results.

## See LOD live results.

Using bif:dateadd in selective Index-Friendly Filter

## "Index-friendly filter for Date range ( bif:dateadd ) within SPARQL query":

SELECT ?wiki,
    ?dbp,
    bif:datediff('second', xsd:DateTime(str(?extracted)) , now()) AS ?secondsAgo
WHERE
  {
    ?wiki foaf:primaryTopic ?dbp .
    ?dbp <http://dbpedia.org/ontology/activeYearsEndDate> ?extracted .
    FILTER ( xsd:DateTime(str(?extracted)) > bif:dateadd('minute', -10, now()))
  }
ORDER BY DESC (xsd:DateTime(str(?extracted)))
LIMIT 30

## See dbpedia live results.

## See LOD live results.

Text Search



Text Search

SQL and TEXT Search

## "Find best lang matching City,
## containing "London" in its name":

SELECT DISTINCT ?cityUri ?cityName
  (
    sql:BEST_LANGMATCH ( ?cityName,
                         'en, en-gb;q=0.8, fr;q=0.7, *;q=0.1',
                         ''
                       )
  ) as ?bestCityName
WHERE
 {
  ?cityUri ?predicate ?value.
  ?cityUri a <http://dbpedia.org/ontology/City>.
  ?value bif:contains "London".
  OPTIONAL
   {
    ?cityUri rdfs:label ?cityName
   }
 }

## See dbpedia live results.

## See LOD live results.

Extending SPARQL via SQL for Full Text search: Variant I

##"Find all albums using parts of the Album Name":

SELECT ?s ?o ?an ( bif:search_excerpt ( bif:vector ( 'In', 'Your' ) , ?o ) )
WHERE
 {
  ?s rdf:type mo:Record .
  ?s foaf:maker ?a .
  ?a foaf:name ?an .
  ?s dc:title ?o .
  FILTER ( bif:contains ( ?o, '"in your"' ) )
 }
LIMIT 10

## See LOD live results.

Extending SPARQL via SQL for Full Text search: Variant II

## "Find all movies from DBpedia
## where Title contains the words:
## 'Broken' and 'Flowers'":

SELECT ?s ?an ?dn ?o( bif:search_excerpt ( bif:vector ( 'Broken', 'Flowers' ) , ?o ) )
WHERE
 {
  ?s rdf:type dbpedia-owl:Film .
  ?s dbpprop:name ?o .
  FILTER ( bif:contains ( ?o, '"broken flowers"' ) )
  OPTIONAL { ?s dbpprop:starring ?starring . }
  OPTIONAL { ?s dbpprop:director ?director . }
  OPTIONAL { ?starring dbpprop:name ?an . }
  OPTIONAL { ?director dbpprop:name ?dn . }
 }
LIMIT 100

## See dbpedia live results.

## See LOD live results.

Dates Manipulation



Dates Manipulation

Date manipulation for xsd types within SPARQL

## This example shows usage of dateTime column
truncation to date only and performs a group by
on this column

## Insert some triples in a graph:
INSERT INTO GRAPH <http://BookStore.com>
 {
  <http://www.dajobe.org/foaf.rdf#i> <http://purl.org/dc/elements/1.1/title> "SPARQL and RDF" .
  <http://www.dajobe.org/foaf.rdf#i> <http://purl.org/dc/elements/1.1/date> <1999-01-01T00:00:00>.
  <http://www.w3.org/People/Berners-Lee/card#i> <http://purl.org/dc/elements/1.1/title> "Design notes" .
  <http://www.w3.org/People/Berners-Lee/card#i> <http://purl.org/dc/elements/1.1/date> <2001-01-01T00:00:00>.
  <http://www.w3.org/People/Connolly/#me> <http://purl.org/dc/elements/1.1/title> "Fundamentals of Compiler Design" .
  <http://www.w3.org/People/Connolly/#me> <http://purl.org/dc/elements/1.1/date> <2002-01-01T00:00:00>.
  <http://www.ivan-herman.net/foaf.rdf#me> <http://purl.org/dc/elements/1.1/title> "RDF Store" .
  <http://www.ivan-herman.net/foaf.rdf#me> <http://purl.org/dc/elements/1.1/date> <2001-03-05T00:00:00>.
  <http://bblfish.net/people/henry/card#me> <http://purl.org/dc/elements/1.1/title> "Design RDF notes" .
  <http://bblfish.net/people/henry/card#me> <http://purl.org/dc/elements/1.1/date> <2001-01-01T00:00:00>.
  <http://hometown.aol.com/chbussler/foaf/chbussler.foaf#me> <http://purl.org/dc/elements/1.1/title> "RDF Fundamentals" .
  <http://hometown.aol.com/chbussler/foaf/chbussler.foaf#me> <http://purl.org/dc/elements/1.1/date> <2002-01-01T00:00:00>.
 };

## Find Count of Group by Dates
SELECT (xsd:date(bif:subseq(str(?a_dt), 0, 10))), count(*)
FROM <http://BookStore.com>
WHERE
 {
  ?s <http://purl.org/dc/elements/1.1/date> ?a_dt
 }
GROUP BY ( xsd:date( bif:subseq( str( ?a_dt ), 0, 10 ) ) )

## See LOD live results.

Date Range within SPARQL

## This example shows usage of date range

SELECT ?s ?date
WHERE
 {
  ?s ?p ?date .
  FILTER ( ?date >= "19450101"^^xsd:date && ?date <= "19451231"^^xsd:date )
 }
LIMIT 100

## See dbpedia live results.

## See LOD live results.

Date with range Example II

## This example shows usage of date with bif:contains

SELECT DISTINCT ?s ?date
WHERE
 {
  ?s ?p ?date .
  FILTER( ?date >= xsd:date("1945-01-01")
       && ?date < xsd:date("1946-01-01")
       && (str(?p) != str(rdfs:label)) )
 }
LIMIT 30

## See dbpedia live results.

## See LOD live results.

Calling SQL from SPARQL



Calling SQL from SPARQL

Calling SQL from SPARQL via "sql" namespace prefix

## "Calling SQL from SPARQL via use of sql: namespace prefix":

create procedure DB.DBA.ComposeInfo (
  in pname varchar,
  in pnick varchar := '',
  in pbox varchar := '' )
  {
    declare ss varchar;
    ss := concat(pname, ' ', pnick, ' ', pbox);
    ss := rtrim (ss, ' ');
    return ss;
  };

GRANT EXECUTE ON DB.DBA.ComposeInfo to SPARQL_SELECT;

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

SELECT ( sql:ComposeInfo ( ?name, ?nick, ?box ) )
FROM <http://www.w3.org/People/Berners-Lee/card>
WHERE
  {
    ?s rdf:type foaf:Person .
    OPTIONAL { ?s foaf:name ?name } .
    OPTIONAL { ?s foaf:nick ?nick } .
    OPTIONAL { ?s foaf:box ?box } .
    FILTER ( ?nick like '%TimBL%' ) .
  }

## See LOD live results.

Calling SQL from SPARQL via "bif" namespace prefix

## "bif: namespace prefix":

SELECT *
WHERE
  {
    ?s ?p ?o .
    ?o bif:contains '"Timo*"'
  }
LIMIT 100

## See dbpedia live results.

## See LOD live results.

SPARUL Features



SPARUL Features

DESCRIBE

## "Pragma for Controlling SPARUL DESCRIBE behaviour
## e.g. Concise Bound Graphs":

DEFINE sql:describe-mode "CBD"
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

DESCRIBE ?friend
WHERE
  {
    ?s foaf:knows ?friend .
    ?friend foaf:nick ?nick .
    FILTER ( ?s =
        <http://melvincarvalho.com/#me> )
  }
LIMIT 100

## See LOD live results.

INSERT

## "Pragma for Controlling SPARQL INSERT behaviour":

DEFINE input:default-graph-uri <http://mygraph.com>

INSERT INTO <http://mygraph.com>
  {
    <http://myopenlink.net/dataspace/Kingsley#this>
    <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
    <http://rdfs.org/sioc/ns#User>
  }

INSERT via CONSTRUCT

## "Use of SPARUL CONSTRUCT to add triples to a Named Graph:
## 1) Execute a CONSTRUCT query.
## 2) View the generated triples to ensure they are correct.
## 3) Replace CONSTRUCT with INSERT INTO."

-- The CONSTRUCT query:
CONSTRUCT
  {
    ?s <http://www.w3.org/2002/07/owl#equivalentClass>
      `iri (bif:replace(?o,'http://schema.rdfs.org/', 'http://schema.org/'))`
  }
FROM <http://www.openlinksw.com/schemas/rdfs>
WHERE
  {
    ?s <http://www.w3.org/2002/07/owl#equivalentClass> ?o
  }

-- Replaced CONSTRUCT with INSERT INTO:
SPARQL INSERT INTO <http://www.openlinksw.com/schemas/rdfs>
  {
    ?s <http://www.w3.org/2002/07/owl#equivalentClass>
      `iri (bif:replace(?o,'http://schema.rdfs.org/', 'http://schema.org/'))`
  }
FROM <http://www.openlinksw.com/schemas/rdfs>
WHERE
  {
    ?s <http://www.w3.org/2002/07/owl#equivalentClass> ?o
  }

LOAD

## "Pragma for Controlling SPARQL LOAD behaviour":

SPARQL
load bif:concat (
                  "http://", bif:registry_get("URIQADefaultHost"),
                  "/DAV/n3_collection/kidehen.n3"
                )
INTO GRAPH <http://mygraph.com>

DELETE

## "Pragma for Controlling SPARQL DELETE behaviour":

PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

DELETE FROM GRAPH <http://BookStore.com> { ?book ?p ?v }
WHERE
  {
    GRAPH <http://BookStore.com>
      {
        ?book dc:date ?date
        FILTER (
                 xsd:dateTime( ?date ) <
                 xsd:dateTime( "2000-01-01T00:00:00" )
               ).
        ?book ?p ?v.
      }
  }

UPDATE

## "Pragma for Controlling SPARQL UPDATE behaviour"
## convert all properties to string:

INSERT INTO GRAPH <http://ucb.com/nbeabase>
  {
    ?sa <http://ucb.com/nbeabase/resource/sampleId> `str (?oa)`
  }
WHERE
  {
    ?sa <http://ucb.com/nbeabase/resource/chemAbsNo> ?oa . FILTER REGEX (?oa, '-','i')
  }

MODIFY

## "MODIFY GRAPH usage as form of UPDATE operation:"

MODIFY GRAPH <http://schema.org/docs/schemaorg>
DELETE { ?s ?p ?o}
INSERT
  {
    `iri (bif:concat (str (?s), "#this"))` ?p ?o
  }
FROM <http://schema.org/docs/schemaorg>
WHERE
  {
    ?s ?p ?o .
    ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .
    FILTER ( !isblank (?s) )
  }

SPARQL 1.1 Features



SPARQL 1.1 Features

NOT EXISTS

## "NOT EXISTS usage:"

SELECT COUNT(*)
WHERE
 {
  ?s ?p "Novosibirsk" .
  FILTER NOT EXISTS { ?s ?p "Новосибирск" }
 }

## See LOD live results.

MINUS

## "MINUS usage:"

SELECT COUNT(*)
WHERE
 {
  ?s ?p "Novosibirsk" .
  FILTER MINUS { ?s ?p "Новосибирск" }
 }

## See LOD live results.

DELETE Triple Patterns that are Not Scoped to a Named Graph

## "DELETE Triple Patterns that are Not Scoped to a Named Graph:"

## "Presuming this triple exists in one or more graphs in the store:"

  {
    <http://kingsley.idehen.net/dataspace/person/kidehen#this>
      <http://xmlns.com/foaf/0.1/knows>
        <http://id.myopenlink.net/dataspace/person/KingsleyUyiIdehen#this>
  }

## The SQL query below will delete that triple
## from all graphs in the store:

DELETE
  FROM DB.DBA.RDF_QUAD
 WHERE p = iri_to_id
            ('http://xmlns.com/foaf/0.1/knows')
   AND s = iri_to_id
            ('http://kingsley.idehen.net/dataspace/person/kidehen#this')
   AND o = iri_to_id
            ('http://id.myopenlink.net/dataspace/person/KingsleyUyiIdehen#this')
;

## According to SPARQL 1.1 Update, the FROM clause which scopes the
## query to a single graph is optional. Thus, the SQL query above can
## be rewritten to the SPARQL query below, again deleting the matching
## triple from all graphs in the store:

DELETE
  {
    GRAPH ?g
     {
       <http://kingsley.idehen.net/dataspace/person/kidehen#this>
         <http://xmlns.com/foaf/0.1/knows>
           <http://id.myopenlink.net/dataspace/person/KingsleyUyiIdehen#this>
     }
  }
WHERE
  {
    GRAPH ?g
      {
        <http://kingsley.idehen.net/dataspace/person/kidehen#this>
          <http://xmlns.com/foaf/0.1/knows>
           <http://id.myopenlink.net/dataspace/person/KingsleyUyiIdehen#this>
      }
  }

Transitivity



Transitivity

Transitivity: Variant I

## "Find all the people known by Kingsley Idehen
## to a depth between 1 and 4 applications of
## the subquery":

SELECT ?o ?dist
       (
         (
           SELECT COUNT (*)
           WHERE
             {
               ?o foaf:knows ?xx
             }
         )
       )
WHERE
  {
    {
      SELECT ?s ?o
      WHERE
        {
          ?s foaf:knows ?o
        }
    }
    OPTION ( TRANSITIVE,
             t_distinct,
             t_in(?s),
             t_out(?o),
             t_min (1),
             t_max (4),
             t_step ('step_no') as ?dist ) .
    FILTER ( ?s = <http://id.myopenlink.net/dataspace/person/KingsleyUyiIdehen#this> )
  }
ORDER BY ?dist DESC 3
LIMIT 50

## See LOD live results.

Transitivity: Variant II

## Find all entities associated with the entity denoted by
## <http://id.myopenlink.net/dataspace/person/KingsleyUyiIdehen#this>
## via the foaf:knows relation.

## Do so in a manner that uses a Transitive Closure
## to include aggregates and distances between
## the entities in the foaf:knows relation

SELECT ?o ?dist
       (
         (
           SELECT COUNT (*)
           WHERE
             {
               ?o foaf:knows ?xx
             }
         )
       )
WHERE
  {
    {
      SELECT ?s ?o
      WHERE
        {
          ?s foaf:knows ?o
        }
    }
    OPTION ( TRANSITIVE,
             t_distinct,
             t_in(?s),
             t_out(?o),
             t_min (2),
             t_max (4) ,
             t_step ('step_no') as ?dist ) .
    FILTER ( ?s = <http://id.myopenlink.net/dataspace/person/KingsleyUyiIdehen#this> )
    FILTER ( !(isblank(?o))) .
  }
ORDER BY ?dist DESC 3
LIMIT 50

## See LOD live results.

Transitivity using Named Graphs

## Determine how two entities (type: Person)
## are connected using the foaf:knows relation:

SELECT ?link ?g ?step ?path
WHERE
  {
    {
      SELECT ?s ?o ?g
      WHERE
        {
          graph ?g {?s foaf:knows ?o }
        }
    }
    OPTION ( TRANSITIVE,
             t_distinct,
             t_in(?s),
             t_out(?o),
             t_no_cycles,
             t_shortest_only,
             t_step (?s) as ?link,
             t_step ('path_id') as ?path,
             t_step ('step_no') as ?step,
             t_direction 3 ) .
    FILTER ( ?s = <http://www.w3.org/People/Berners-Lee/card#i>
          && ?o = <http://myopenlink.net/dataspace/person/kidehen#this> )
  }
LIMIT 20

## See LOD live results.

Transitivity & Equivalence Relation (owl:sameAs)

## Find all co-referents of the
## IRI <http://dbpedia.org/resource/New_York>
## i.e., other IRIs that denote the same
## thing as <http://dbpedia.org/resource/New_York> .

SELECT ?syn
WHERE
  {
    {
      SELECT ?x ?syn
      WHERE
        {
          {
            ?x owl:sameAs ?syn
          }
          UNION
          {
            ?syn owl:sameAs ?x
          }
        }
    }
    OPTION ( transitive, t_in (?x), t_out (?syn), t_distinct, t_min (0) )
    FILTER ( ?x = <http://dbpedia.org/resource/New_York> ) .
  }

## See dbpedia live results.
## See LOD live results.

Transitivity, Equivalence Relation, and Named Graphs

## "Find all graphs that contain
## owl:sameAs for "New York":

SELECT ?g ?x count (*) as ?count
WHERE
  {
    {
      SELECT ?x ?alias ?g
      WHERE
        {
          {
            GRAPH ?g
              {
                ?x owl:sameAs ?alias
              }
          }
          UNION
          {
            GRAPH ?g
              {
                ?alias owl:sameAs ?x
            }
          }
        }
      }
    OPTION ( TRANSITIVE,
              t_in (?x),
              t_out (?alias),
              t_distinct,
              t_min (1)
           ) .
    FILTER ( ?x = <http://dbpedia.org/resource/New_York> ) .
  }

## See dbpedia live results.
## See LOD live results.

Transitive Closure, Named Graphs, via RDF Schema Subsumption Reasoning 1

## Transitivity enhanced Subsumption Reasoning

## Meaning: subClasses of subClasses are incorporated
## into the query solution by way of Transitive Closure

SELECT ?y
FROM <http://dbpedia.org/resource/classes/yago#>
WHERE
  {
    {
      SELECT *
      WHERE
        {
          ?x rdfs:subClassOf ?y .
        }
    }
    OPTION ( TRANSITIVE, t_distinct, t_in (?x), t_out (?y) ) .
    FILTER ( ?x = <http://dbpedia.org/class/yago/AlphaReceptor105609111> )
  }

## See dbpedia live results.

Transitive Closure, Named Graphs, via RDF Schema Subsumption Reasoning 2

## Transitivity enhanced Subsumption Reasoning

## Meaning: subClasses of subClasses of
## <http://dbpedia.org/class/yago/Receptor105608868>
## are incorporated into the query solution
## by way of Transitive Closure

SELECT ?y
FROM <http://dbpedia.org/resource/classes/yago#>
WHERE
  {
    {
      SELECT *
      WHERE
        {
          ?x rdfs:subClassOf ?y .
        }
    }
    OPTION ( TRANSITIVE, t_distinct, t_in (?y), t_out (?x) ) .
    FILTER ( ?y = <http://dbpedia.org/class/yago/Receptor105608868> )
  }

## See dbpedia live results.

Transitivity enhanced Relatedness between two entities

## Incorporate Transitive Closures into determining 10
## relations that associate the entity denoted by
## <http://dbpedia.org/resource/New_York>
## with other entities

SELECT DISTINCT ?s ?p ?o
       bif:either(isIri(?o),'URI',datatype(?o)) AS ?type
WHERE
  {
    ?anchor ?pp ?s
    OPTION ( TRANSITIVE,
               t_min (0),
               t_max (2),
               t_in (?anchor),
               t_out (?s),
               t_no_cycles,
               t_distinct ) .
    FILTER ( ?anchor = <http://dbpedia.org/resource/New_York>)
    ?s ?p ?o .
  }
ORDER BY ?s
LIMIT 100

## See dbpedia live results.
## See LOD live results.

Inference Rules & Reasoning



Inference Rules & Reasoning

Inference Rule Creation & Loading

## Create an Inference Rule denoted by the
## literal identifier "skos-trans"

PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

INSERT INTO GRAPH <urn:rules.skos>
  {
    skos:broader rdfs:subPropertyOf skos:broaderTransitive .
    skos:narrower rdfs:subPropertyOf skos:narrowerTransitive
  };

rdfs_rule_set ('skos-trans', 'urn:rules.skos');

Inference Rule: SKOS Concept Scheme Example 1

## Find entities that are subcategories of "category:Protestant_churches"
## placed no deeper than 3 levels within the concept
## scheme hierarchy, filtered by a specific subcategory.
## This query demonstrates use of Inference Rule Context,
## sub-queries, and FILTER to find entities
## associated with "category:Protestant_churches".
## It also leverages the use of the TRANSITIVE OPTION
## which sets a 3-level traversal down a SKOS concept scheme hierarchy.

DEFINE input:inference "skos-trans"

PREFIX p: <http://dbpedia.org/property/>
PREFIX dbpedia: <http://dbpedia.org/resource/>
PREFIX category: <http://dbpedia.org/resource/Category:>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX geo: <http://www.georss.org/georss/>

SELECT DISTINCT ?c AS ?skos_broader
       ?trans AS ?skos_narrower
       ?dist AS ?skos_level
       ?m ?n ?p AS ?geo_point
WHERE
  {
    {
      SELECT ?c ?m ?n ?p ?trans ?dist
      WHERE
        {
          ?m rdfs:label ?n .
          ?m skos:subject ?c .
          ?c skos:broaderTransitive
              category:Protestant_churches .
          ?c skos:broaderTransitive ?trans
            OPTION ( TRANSITIVE,
                     t_distinct,
                     t_in (?c),
                     t_out (?trans),
                     t_max (3),
                     t_step ( 'step_no' ) as ?dist
                   ) .
          ?m p:abstract ?d .
          ?m geo:point ?p
          FILTER ( lang(?n) = "en" )
          FILTER ( lang(?d) = "en" )
        }
    }
    FILTER ( ?trans =
      <http://dbpedia.org/resource/Category:Churches_in_London> )
  }
ORDER BY ASC (?dist)

## See URIBurner live results.

Inference Rule: SKOS Concept Scheme Example 2

## This query makes use of Transitivity,
## Inference Rule Context, Sub-Queries and FILTERs:

SPARQL
DEFINE input:inference "skos-trans"
PREFIX p: <http://dbpedia.org/property/>
PREFIX dbpedia: <http://dbpedia.org/resource/>
PREFIX category: <http://dbpedia.org/resource/Category:>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX geo: <http://www.georss.org/georss/>

SELECT DISTINCT ?m ?n ?p ?d
WHERE
  {
    ?m rdfs:label ?n .
    ?m skos:subject ?c .
    ?c skos:broaderTransitive category:Churches_in_Paris
        OPTION (TRANSITIVE) .
    ?m p:abstract ?d .
    ?m geo:point ?p
    FILTER ( lang(?n) = "fr" )
    FILTER ( lang(?d) = "fr" )
  }

## See URIBurner live results.

Inference Rule: Yago Class hierarchy

## Execution of SQL stored procedure for loading
## Yago Class hierarchy rule into a Named Graph
SELECT ttlp_mt
  (
    file_to_string_output ( 'yago-class-hierarchy_en.nt'),
    '',
    'http://dbpedia.org/resource/classes/yago#'
  );

## Create an Inference Rule that references
## the Yago Class Hierarchy Named Graph

rdfs_rule_set
  (
    'http://dbpedia.org/resource/inference/rules/yago#',
    'http://dbpedia.org/resource/classes/yago#'
  );

DBpedia Inference rule Example

## Retrieve all individuals instances
## of Fiction Class which should include all Novels":

DEFINE input:inference "http://dbpedia.org/resource/inference/rules/yago#"
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dbpedia: <http://dbpedia.org/property/>
PREFIX yago: <http://dbpedia.org/class/yago/>
SELECT ?s ?n
FROM <http://dbpedia.org>
WHERE
  {
    ?s a <http://dbpedia.org/class/yago/Fiction106367107> .
    ?s dbpedia:name ?n .
  }

## See dbpedia live results.

DBpedia Inference rule Example with Literal Value

## Find all Fiction Books associated with a
## property "dbpedia:name" that has literal
## value: "The Lord of the Rings":

DEFINE input:inference "http://dbpedia.org/resource/inference/rules/yago#"
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dbpedia: <http://dbpedia.org/property/>
PREFIX yago: <http://dbpedia.org/class/yago/>

SELECT ?s
FROM <http://dbpedia.org>
WHERE
 {
  ?s a <http://dbpedia.org/class/yago/Fiction106367107> .
  ?s dbpedia:name "The Lord of the Rings"@en .
 }

## See dbpedia live results.

DBpedia Inference rule Example with Virtuoso's Full Text Index extension via bif:contains

## Variant with Virtuoso's Full Text Index
## extension via the bif:contains
## function/magic predicate

DEFINE input:inference "http://dbpedia.org/resource/inference/rules/yago#"
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dbpedia: <http://dbpedia.org/property/>
PREFIX yago: <http://dbpedia.org/class/yago/>

SELECT ?s ?n
FROM <http://dbpedia.org>
WHERE
 {
  ?s a <http://dbpedia.org/class/yago/Fiction106367107> .
  ?s dbpedia:name ?n .
  ?n bif:contains 'Lord and Rings'
 }

## See dbpedia live results.

Inference Rule: Relationship Vocab "urn:owl:inference:tests"

## "Relationship Vocabulary":

## Create Instance Data for Relationship Ontology
## Verify Ontology Data is in Quad Store
## Ontology: <http://vocab.org/relationship/> (Relationship Ontology)
## Use pragma to put latest in Quad store.

DEFINE get:soft "replace"
SELECT *
FROM <http://vocab.org/relationship/>
WHERE
  {
    ?s ?p ?o
  }
## Clean up instance data graph

CLEAR GRAPH <urn:owl:inference:tests>
## Create Instance Data for Relationship Ontology
PREFIX rel: <http://purl.org/vocab/relationship/>

INSERT into GRAPH <urn:owl:inference:tests>
  {
    <http://dbpedia.org/resource/Prince_William_of_Wales> rel:siblingOf <http://dbpedia.org/resource/Prince_Harry_of_Wales> .
    <http://dbpedia.org/resource/Elizabeth_Bowes-Lyon> rel:ancestorOf <http://dbpedia.org/resource/Elizabeth_II_of_the_United_Kingdom> .
    <http://dbpedia.org/resource/Elizabeth_II_of_the_United_Kingdom> rel:ancestorOf
    <http://dbpedia.org/resource/Charles%2C_Prince_of_Wales> .
    <http://dbpedia.org/resource/Charles%2C_Prince_of_Wales> rel:ancestorOf <http://dbpedia.org/resource/Prince_William_of_Wales> .
  };

## Verify Data

SELECT *
FROM <urn:owl:inference:tests>
WHERE
  {
    ?s ?p ?o
  }

## SQL mode
## Create Inference Rule that references the
## Relationship Ontology Named Graph

rdfs_rule_set ('urn:owl:inference:rules:tests', 'http://vocab.org/relationship/') ;

## Verify Rule's existence

SELECT *
FROM sys_rdf_schema;


owl:TransitiveProperty Reasoning

## Test owl:TransitiveProperty Reasoning
## Start with a specific URI
## Goal: See inferred Triples
## In this case, relationship between:
    <http://dbpedia.org/resource/Elizabeth_Bowes-Lyon>
## and her descendants:
    Queen Elizabeth, Prince Charles, Prince William, and Prince Harry)

DEFINE input:inference 'urn:owl:inference:rules:tests'
PREFIX rel: <http://purl.org/vocab/relationship/>

SELECT *
FROM <urn:owl:inference:tests>
WHERE
  {
    <http://dbpedia.org/resource/Elizabeth_Bowes-Lyon>
    rel:ancestorOf ?o
  }

## See URIBurner live results.
## See Tutorial Demonstrating Reasoning via SPARQL

owl:SymmetricalProperty Reasoning

## Test owl:SymmetricalProperty Reasoning
## Should show same result irrespective of
## rel:siblingOf URI in Subject or Object slots of Triple

DEFINE input:inference 'urn:owl:inference:rules:tests'
PREFIX rel: <http://purl.org/vocab/relationship/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT *
FROM <urn:owl:inference:tests>
WHERE
  {
    <http://dbpedia.org/resource/Prince_William_of_Wales>
    rel:siblingOf ?o
  }

## See URIBurner live results.
## See Tutorial Demonstrating Reasoning via SPARQL

owl:SymmetricalProperty Reasoning Variant II

## Test owl:SymmetricalProperty Reasoning
## Should show same result irrespective of
## rel:siblingOf URI in Subject or Object slots of Triple

DEFINE input:inference 'urn:owl:inference:rules:tests'
PREFIX rel: <http://purl.org/vocab/relationship/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT *
FROM <urn:owl:inference:tests>
WHERE
  {
    ?s rel:siblingOf
    <http://dbpedia.org/resource/Prince_William_of_Wales>
    OPTION (T_DISTINCT)
  }

## See URIBurner live results.

owl:inverseOf Reasoning

## Test owl:inverseOf Reasoning
## Should show triples exposing the inverseOf relation.
## In this case rel:ancestorOf instance data
## triples exist, so the system must infer
## rel:descendant Of triples

DEFINE input:inference 'urn:owl:inference:rules:tests'
PREFIX rel: <http://purl.org/vocab/relationship/>

SELECT *
FROM <urn:owl:inference:tests>
WHERE
  {
    <http://dbpedia.org/resource/Elizabeth_II_of_the_United_Kingdom>
    rel:descendantOf ?o
  }

## See URIBurner live results.
## See Tutorial Demonstrating Reasoning via SPARQL

owl:inverseOf Reasoning Variant II

## Test owl:inverseOf Reasoning
## Should show triples exposing the inverseOf relation.
## In this case rel:ancestorOf instance data
## triples exist, so the system must infer
## rel:descendant Of triples

DEFINE input:inference 'urn:owl:inference:rules:tests'
PREFIX rel: <http://purl.org/vocab/relationship/>

SELECT *
FROM <urn:owl:inference:tests>
WHERE
  {
    <http://dbpedia.org/resource/Prince_William_of_Wales>
    rel:descendantOf ?o OPTION (T_DISTINCT)
  }

## See URIBurner live results.

Inference Rule: Relationship Vocab and SKOS "urn:owl.test2.rules"

## "Relationship Vocabulary and SKOS":

## Graph Cleanup

CLEAR GRAPH <urn:owl.test2.tbox>
CLEAR GRAPH <urn:turnguard.com:test2.tbox>

## Load Instance Data into Quad Store
## PL Procedure

## SQL realm

DB.DBA.RDF_LOAD_RDFXML
  (
    http_get('http://www.w3.org/2009/08/skos-reference/skos-owl1-dl.rdf'),
    'no',
    'urn:owl.test2.tbox'
  );

DB.DBA.RDF_LOAD_RDFXML
  (
    http_get ('http://www.w3.org/2002/07/owl.rdf'),
    'no',
    'urn:owl.test2.tbox'
    );


PREFIX rdf:   <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX turng: <http://www.turnguard.com/>
PREFIX skos:  <http://www.w3.org/2004/02/skos/core#>

INSERT
  {
    GRAPH <urn:turnguard.com:test2.tbox>
      {
        turng:Music rdf:type skos:Concept .
        turng:Music skos:prefLabel "Music"@en .
        turng:Music skos:narrower turng:Pop .

        turng:Pop rdf:type skos:Concept .
        turng:Pop skos:prefLabel "POP"@en .
        turng:Pop skos:narrower turng:TechnoPop .

        turng:TechnoPop rdf:type skos:Concept .
        turng:TechnoPop skos:prefLabel "TECHNOPOP"@en .
        turng:TechnoPop skos:narrower turng:ElectroPop .

        turng:ElectroPop rdf:type skos:Concept .
        turng:ElectroPop skos:prefLabel "ELECTROPOP"@en .
      }
  };

SELECT * from <http://www.w3.org/2004/02/skos/core>
WHERE
  {
    {
      <http://www.w3.org/2004/02/skos/core#related> ?p ?o
    }
    UNION
    {
      ?s ?p <http://www.w3.org/2004/02/skos/core#related>
    }
  }

## Create Rules

## SQL Realm

rdfs_rule_set ('urn:owl.test2.rules', 'urn:owl.test2.tbox');

Example based on Relationship Vocab and SKOS

## Transitivity Query with SKOS concept hierarchy

DEFINE input:inference "urn:owl.test2.rules"
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT *
FROM <urn:turnguard.com:test2.tbox>
WHERE
  {
    <http://www.turnguard.com/ElectroPop> skos:broaderTransitive ?o
    OPTION (T_DISTINCT).
  }

## See URIBurner live results.

Inference Rule: "foaf-trans"

## "Negation using "COUNT"":
## with inference: "Find celebrities which"
## are not fans of their own fans:

SPARQL
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX sioc: <http://rdfs.org/sioc/ns#>

INSERT INTO GRAPH <urn:rules.skos>
  {
    foaf:knows rdfs:subPropertyOf skos:follows .
  };

rdfs_rule_set ('foaf-trans', 'urn:rules.skos');

Negation: COUNT with inference

## "Negation using "COUNT"
## with inference: "Find celebrities which"
## are not fans of their own fans":

SPARQL
DEFINE input:inference "foaf-trans"
PREFIX sioc: <http://rdfs.org/sioc/ns#>

SELECT ?celeb COUNT (*)
WHERE
  {
    ?claimant sioc:follows ?celeb .
    FILTER
      (
        !bif:exists
          (
            (
              SELECT (1)
              WHERE
                {
                  ?celeb sioc:follows ?claimant
                }
            )
          )
      )
  }
GROUP BY ?celeb
ORDER BY DESC 2
LIMIT 10

## See URIBurner live results.

Negation: COUNT without inference

## "Negation with "COUNT"
## without inference":

SELECT ?celeb COUNT (*)
WHERE
  {
    ?claimant sioc:follows ?celeb .
    FILTER
      (
        !bif:exists
          (
            (
              SELECT (1)
              WHERE
                {
                  ?celeb sioc:follows ?claimant
                }
            )
          )
      )
  }
GROUP BY ?celeb
ORDER BY DESC 2
LIMIT 10

## See URIBurner live results.

Co-reference Union Expansion Inference Rule Example

## "Conditional use of owl:sameAs inference rule":

DEFINE input:same-as "yes"

PREFIX geonames: <http://www.geonames.org/ontology#>
SELECT ?s ?z
WHERE
  {
    ?s geonames:parentFeature ?z
  }
LIMIT 100

## See URIBurner live results.

SPARQL-BI



SPARQL-BI

SPARQL-BI Condition Example bif:either

## "Condition usage of
bif:either ( in cond any,
             in arg1 any,
             in arg2 any )
built-in SQL function":

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://dbpedia.org/property/>
SELECT ?team
      ( ( bif:either( ?ew = 'W', -1, 1)) * (?d + (((?m * 60) + ?s) / 3600.0)) as ?v )
  {
    ?team a dbo:HockeyTeam .
    ?team rdfs:label 'New Jersey Devils'@en .
    ?team dbp:city ?cityname .
    ?city rdfs:label ?cityname .
    ?city dbp:longd ?d ;
          dbp:longm ?m ;
          dbp:longs ?s ;
        dbp:longew ?ew .
  }

SPARQL-BI Condition Example bif:locate

## "Usage of
bif:locate ( in string_exp1 varchar,
             in string_exp2 varchar,
             [in start integer] )
built-in SQL function":

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://dbpedia.org/property/>
SELECT ?team
      ( ( bif:locate( 'W', ?ew )) * (?d + (((?m * 60) + ?s) / 3600.0)) as ?v )
  {
    ?team a dbo:HockeyTeam .
    ?team rdfs:label 'New Jersey Devils'@en .
    ?team dbp:city ?cityname .
    ?city rdfs:label ?cityname .
    ?city dbp:longd ?d ;
          dbp:longm ?m ;
          dbp:longs ?s ;
        dbp:longew ?ew .
  }

BOUND Expressions



BOUND Expressions

FILTER with "!BOUND()" expression Example

## "Usage of FILTER .. !BOUND()" expression
## It should be used with an OPTIONAL.
## Without OPTIONAL all variables from triple
## patterns will be bound in every result by definition."

SELECT DISTINCT ?s
WHERE
  {
    ?s <http://dbpedia.org/ontology/position> ?pos.
    ?s <http://purl.org/dc/terms/subject>
      <http://dbpedia.org/resource/Category:Premier_League_clubsgt>.
    ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#typegt>
      <http://dbpedia.org/class/yago/PremierLeagueClubs>.
    OPTIONAL {?s <http://dbpedia.org/property/leaguegt> ?o.}
    FILTER (!BOUND (?o))
  }
LIMIT 10

IFP Inferences



IFP Inferences

Inverse Functional Properties and Same As

## "Usage of IFP inference as a transparent
## addition of a subquery into the join sequence."

SELECT ?f
WHERE
 {
  ?k foaf:name "Kjetil Kjernsmo" .
  {
    SELECT ?org ?syn
    WHERE
      {
        ?org ?p ?key .
        ?syn ?p ?key .
        FILTER
          ( bif:rdf_is_sub
            ( "b3sifp", ?p, <b3s:any_ifp>, 3 )
          &&
          ?syn != ?org
          )
      }
  }
  OPTION
    (
      TRANSITIVE ,
      T_IN (?org),
      T_OUT (?syn),
      T_MIN (0),
      T_MAX (1)
    )
  FILTER ( ?org = ?k ) .
  ?syn foaf:knows ?f .
 }
## See URIBurner live results.

RDF
SPARQL
SQL
OpenLink
SIOC
WG
SPARUL
ARQ
XQuery
XPath
URI
Vocabulary
IFP
RIF
RDFS
OWL
RDBMS
ODBC
JDBC
GET
POST
QL