SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
An Introduction to SPARQL Optionals
Julian Dolby
Kavitha Srinivas
Why Do We Need OPTIONALS?
Deals with sparsity in graph data. A simple example where
this is useful:
John age 42
John lastName Smith
John spouse Mary
John homeState New_York
New_York isIn NorthEast
Todd age 42
Todd lastName Doe
Todd homeState Connecticut
Connecticut isIn NorthEast
Tom age 42
Say we want to find all the people who are aged 42 and live in
the NorthEast, and optionally their spouses names, if its
known. OPTIONAL allows you to express that.
What does it mean?
The best way to understand what an optional means
is to think of it as extending the immediately
preceding pattern.
And extending it means that it can bind variables
that have not been bound in its preceding pattern;
for variables that have been bound by the preceding
pattern, the optional must match the value
A working dataset
AS mailbox mailto:alice@example.net
AS name Alice
AS nick WhoMe?
BD mailbox mailto:bert@example.net
BD name Bert
EF mailbox mailto:eve@example.net
EF nick DuckSoup
Many of the examples here are from Jena’s ARQ suite
The SIMPLEST CASE
Simplest case: optional pattern extends bindings from the
preceding pattern, and provides binding for 'name' in the
OPTIONAL pattern.
ResultSet:
SELECT ?x ?mbox ?name
{
?x mailbox ?mbox .
OPTIONAL { ?x name ?name } .
}
x mbox name
AS mailto:alice@example.net Alice
BD mailto:bert@example.net Bert
EF mailto:eve@example.net NULL
Multiple OPTIONALS
Optional left-associative (like minus), so a optional b
optional c is really ((a optional b) optional c).
ResultSet:
SELECT ?x ?mailbox ?name ?nick
{
?x mailbox ?mbox .
OPTIONAL { ?x name ?name } .
OPTIONAL { ?x nick ?nick }.
}
x mbox name nick
AS mailto:alice@example.net Alice WhoMe?
BD mailto:bert@example.net Bert NULL
EF mailto:eve@example.net NULL DuckSoup
Multiple OPTIONALS Contd.
Note that the second optional binds values to a variable bound by another optional. Thus,
the inner pattern will bind x, mbox and optionally label. If it binds label, then the outer
pattern has to match it and cannot extend it. So result will have all mbox properties, and
all name properties that have an mbox. The outer pattern extends these results. If a
subject has no name property, then any nick property for it will be returned. If it does
have a name property, then a nick property will be returned only if its target matches a
name property for the same subject.
However, only label is projected. So then, if there is a name property, label will be bound
to that. If not, then it will bind any nick property. Thus, for Alice, we should see the
name and no nickname.
ResultSet
SELECT ?label
{
?x mailbox ?mbox .
OPTIONAL { ?x name ?label } .
OPTIONAL { ?x nick ?label } .
}
Label
Alice
Bert
DuckSoup
AS, BD, EF all have mailboxes. All should match for main.
Optional 1: Extends with name for AS and BD, null for EF.
Optional 2: Extends optional 1 result set with nickname for EF, since
for the AS and BD, nick HAS to match bindings of label in optional 1.
Multiple OPTIONALS Contd.
SELECT ?label
{
?x mailbox ?mbox .
OPTIONAL { ?x name ?label } .
OPTIONAL { ?x nick ?label } .
}
SELECT ?label
{
?x mailbox ?mbox .
OPTIONAL {
{ ?x name ?label } UNION
{ ?x nick ?label } .
}
}
Multiple OPTIONAL clauses binding the same variable is similar to yet subtly different
from a UNION inside the OPTIONAL. The lefthand query gets ‘nick’ labels for
mailboxes that have no ‘name’; the righthand query gets all ‘nick’ and ‘name’ labels for any
mailbox.
Label
Alice
Bert
DuckSoup
Label
Alice
Bert
DuckSoup
WhoMe?
Multiple OPTIONAL clauses binding the same variable is rarely what you want
OPTIONAL WITH EMPTY
Here, no pattern to extend (i.e., the pattern is empty). An
empty pattern binds no variables, so the optional ‘extends’
the empty result set with any of its variables. Note this is
equivalent to dropping the OPTIONAL altogether.
ResultSet:
SELECT ?x ?nick
{
OPTIONAL { ?x nick ?nick }.
}
x nick
AS WhoMe?
EF DuckSoup
NESTING OPTIONALS
In the nested optional case, we have (a OPTIONAL (b OPTIONAL c)). Note this
differs from the case where we have two optionals that are not nested. In this case, the
main pattern once again matches all three individuals, but the optionals being nested
means the second optional has the result of the first optional as its main pattern. Thus, the
results have mbox, and optionally nick, and possibly name if it has nick too. In particular,
the name of bert is not returned, since it has no nick property. Note that b first extends a,
and then c will extend b.
ResultSet
SELECT ?x ?mbox ?name ?nick
{
?x mailbox ?mbox .
OPTIONAL {
?x nick ?nick
OPTIONAL { ?x name ?name }
}
}
x mbox name nick
AS mailto:alice@example.net Alice WhoMe?
BD mailto:bert@example.net NULL NULL
EF mailto:eve@example.net NULL DuckSoup
NO-OP OPTIONALS
In this case, the optional does not really have any new variables to bind. ?nick is already
bound to “Who Me”, so the optional is a no-op.
ResultSet
SELECT ?nick
{
AS nick ?nick .
OPTIONAL {AS name ?nick}
}
nick
WhoMe?
More complex optionals
The optional pattern here contains an AND. That is, it can
extend bindings from the preceding pattern for ?x only
when ?x has both nick and name. Only Alice will have
bindings for ?nick and ?name.
ResultSet:
SELECT ?x ?mbox ? nick ?name
{
?x mailbox ?mbox .
OPTIONAL {
?x nick ?nick .
?x name ?name } .
}
x mbox name nick
AS mailto:alice@example.net Alice WhoMe?
BD mailto:bert@example.net NULL NULL
EF mailto:eve@example.net NULL NULL
OPTIONAL and FILTER
FILTER applies only to pattern containing it
OPTIONAL only vs. main pattern
SELECT ?x ?name
{
?x mailbox ?mbox .
OPTIONAL {
?x name ?name .
FILTER (?name = “Bert”)
} .
}
SELECT ?x ?name
{
?x mailbox ?mbox .
OPTIONAL {
?x name ?name .
}
FILTER (?name = “Bert”)
}
x name
AS NULL
EF NULL
BD Bert
x name
BD Bert
Disconnected Optionals
The optional pattern extends bindings from the preceding
pattern but shares no variables in common. Basically this
will be a cross product.
ResultSet:
SELECT ?x ?nick ?name
{
?x nick ?nick .
OPTIONAL { ?y name ?name } .
}
x nick y Name
AS WhoMe? AS Alice
AS WhoMe? BD Bert
EF DuckSoup AS Alice
EF DuckSoup BD Bert
Cross products generally perform terribly; avoid them
Disconnected Optionals
And filters
The optional pattern extends bindings from the preceding
pattern but shares no variables in common. Basically this
will be a cross product.
ResultSet:
SELECT ?x ?nick ?name
{
?x nick ?nick .
OPTIONAL { ?y name ?name FILTER (?x=AS) } .
}
x nick y Name
AS WhoMe? AS Alice
AS WhoMe? BD Bert
EF DuckSoup NULL NULL
OPTIONAL and negation
OPTIONAL can test for absence of triples
Uses FILTER and not(bound(?v))
FILTER for ?v to be NULL, i.e. not exist
SELECT ?x ?mbox
{
?x mailbox ?mbox .
OPTIONAL { ?x name ?name }
FILTER (not(bound(?name))
}
x mbox
EF mailto:eve@example.net
EF is the only entity with no name property
SPARQL 1.1 Negation
SPARQL 1.1 added explicit negation
obviates not(bound(?v))
SELECT ?x ?mbox
{
?x mailbox ?mbox .
FILTER NOT EXISTS {
?x name ?name }
}
x mbox
EF mailto:eve@example.net
EF is the only entity with no name property
SPARQL 1.1 Minus
MINUS computes set difference
expresses some forms of negation
SELECT ?x ?mbox
{
?x mailbox ?mbox .
MINUS {
?x name ?name
}
}
x mbox
EF mailto:eve@example.net
subtract entities with name from entities with mailbox

Weitere ähnliche Inhalte

Was ist angesagt?

게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
Amazon Web Services Korea
 

Was ist angesagt? (20)

Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step Guide
 
워크로드 특성에 따른 안전하고 효율적인 Data Lake 운영 방안
워크로드 특성에 따른 안전하고 효율적인 Data Lake 운영 방안워크로드 특성에 따른 안전하고 효율적인 Data Lake 운영 방안
워크로드 특성에 따른 안전하고 효율적인 Data Lake 운영 방안
 
Amazon RDS Deep Dive
Amazon RDS Deep DiveAmazon RDS Deep Dive
Amazon RDS Deep Dive
 
SHACL by example
SHACL by exampleSHACL by example
SHACL by example
 
SPARQL Cheat Sheet
SPARQL Cheat SheetSPARQL Cheat Sheet
SPARQL Cheat Sheet
 
AWS CDK를 활용한 게임 데이터 파이프라인 구축 방안 [레벨 200] - 발표자: Douglas Lima, 데브옵스 컨설턴트, AWS ...
AWS CDK를 활용한 게임 데이터 파이프라인 구축 방안 [레벨 200] - 발표자: Douglas Lima, 데브옵스 컨설턴트, AWS ...AWS CDK를 활용한 게임 데이터 파이프라인 구축 방안 [레벨 200] - 발표자: Douglas Lima, 데브옵스 컨설턴트, AWS ...
AWS CDK를 활용한 게임 데이터 파이프라인 구축 방안 [레벨 200] - 발표자: Douglas Lima, 데브옵스 컨설턴트, AWS ...
 
AWS DevOps와 ECR을 통한 Elastic Beanstalk 배포 환경 구축 및 타 환경과의 비교
AWS DevOps와 ECR을 통한 Elastic Beanstalk 배포 환경 구축 및 타 환경과의 비교AWS DevOps와 ECR을 통한 Elastic Beanstalk 배포 환경 구축 및 타 환경과의 비교
AWS DevOps와 ECR을 통한 Elastic Beanstalk 배포 환경 구축 및 타 환경과의 비교
 
AWS Summit Seoul 2023 | 혁신의 키워드는 '조직'과 '문화' - 하이브리드 클라우드 플랫폼과 agile 조직이 만드는 혁신
AWS Summit Seoul 2023 | 혁신의 키워드는 '조직'과 '문화' - 하이브리드 클라우드 플랫폼과 agile 조직이 만드는 혁신AWS Summit Seoul 2023 | 혁신의 키워드는 '조직'과 '문화' - 하이브리드 클라우드 플랫폼과 agile 조직이 만드는 혁신
AWS Summit Seoul 2023 | 혁신의 키워드는 '조직'과 '문화' - 하이브리드 클라우드 플랫폼과 agile 조직이 만드는 혁신
 
Oracle REST Data Services Best Practices/ Overview
Oracle REST Data Services Best Practices/ OverviewOracle REST Data Services Best Practices/ Overview
Oracle REST Data Services Best Practices/ Overview
 
Networking Many VPCs: Transit and Shared Architectures - NET404 - re:Invent 2017
Networking Many VPCs: Transit and Shared Architectures - NET404 - re:Invent 2017Networking Many VPCs: Transit and Shared Architectures - NET404 - re:Invent 2017
Networking Many VPCs: Transit and Shared Architectures - NET404 - re:Invent 2017
 
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
 
Deep Dive into Amazon ECS & Fargate
Deep Dive into Amazon ECS & FargateDeep Dive into Amazon ECS & Fargate
Deep Dive into Amazon ECS & Fargate
 
AWS Summit Seoul 2023 | Confluent와 함께하는 실시간 데이터와 클라우드 여정
AWS Summit Seoul 2023 | Confluent와 함께하는 실시간 데이터와 클라우드 여정AWS Summit Seoul 2023 | Confluent와 함께하는 실시간 데이터와 클라우드 여정
AWS Summit Seoul 2023 | Confluent와 함께하는 실시간 데이터와 클라우드 여정
 
Visual studio.net
Visual studio.netVisual studio.net
Visual studio.net
 
How to use IAM roles grant access to AWS
How to use IAM roles grant access to AWSHow to use IAM roles grant access to AWS
How to use IAM roles grant access to AWS
 
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
 
Webinar AWS 201 - Using Amazon Virtual Private Cloud (VPC)
Webinar AWS 201 - Using Amazon Virtual Private Cloud (VPC)Webinar AWS 201 - Using Amazon Virtual Private Cloud (VPC)
Webinar AWS 201 - Using Amazon Virtual Private Cloud (VPC)
 
Amazon Cognito와 함께 서버리스를..! - 이재일 (강남비기너모임) :: AWS Community Day 2017
Amazon Cognito와 함께 서버리스를..! - 이재일 (강남비기너모임) :: AWS Community Day 2017Amazon Cognito와 함께 서버리스를..! - 이재일 (강남비기너모임) :: AWS Community Day 2017
Amazon Cognito와 함께 서버리스를..! - 이재일 (강남비기너모임) :: AWS Community Day 2017
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
[Solutions] computer graphics question paper 2018 tutorialsduniya.com
[Solutions] computer graphics question paper 2018   tutorialsduniya.com[Solutions] computer graphics question paper 2018   tutorialsduniya.com
[Solutions] computer graphics question paper 2018 tutorialsduniya.com
 

Andere mochten auch (8)

Home Theater: Surround Sound Formats
Home Theater: Surround Sound FormatsHome Theater: Surround Sound Formats
Home Theater: Surround Sound Formats
 
Surround sount system
Surround sount systemSurround sount system
Surround sount system
 
Dolby Laboratories Pitch
Dolby Laboratories PitchDolby Laboratories Pitch
Dolby Laboratories Pitch
 
Dolby atmos-cinema-technical-guidelines
Dolby atmos-cinema-technical-guidelinesDolby atmos-cinema-technical-guidelines
Dolby atmos-cinema-technical-guidelines
 
Top Indian Brands on Social Media - June 2013
Top Indian Brands on Social Media - June  2013Top Indian Brands on Social Media - June  2013
Top Indian Brands on Social Media - June 2013
 
Dolby atmos explained
Dolby atmos explainedDolby atmos explained
Dolby atmos explained
 
Oscars 2016: Winners and Highlights
Oscars 2016: Winners and  HighlightsOscars 2016: Winners and  Highlights
Oscars 2016: Winners and Highlights
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Using SPARQL Optionals

  • 1. An Introduction to SPARQL Optionals Julian Dolby Kavitha Srinivas
  • 2. Why Do We Need OPTIONALS? Deals with sparsity in graph data. A simple example where this is useful: John age 42 John lastName Smith John spouse Mary John homeState New_York New_York isIn NorthEast Todd age 42 Todd lastName Doe Todd homeState Connecticut Connecticut isIn NorthEast Tom age 42 Say we want to find all the people who are aged 42 and live in the NorthEast, and optionally their spouses names, if its known. OPTIONAL allows you to express that.
  • 3. What does it mean? The best way to understand what an optional means is to think of it as extending the immediately preceding pattern. And extending it means that it can bind variables that have not been bound in its preceding pattern; for variables that have been bound by the preceding pattern, the optional must match the value
  • 4. A working dataset AS mailbox mailto:alice@example.net AS name Alice AS nick WhoMe? BD mailbox mailto:bert@example.net BD name Bert EF mailbox mailto:eve@example.net EF nick DuckSoup Many of the examples here are from Jena’s ARQ suite
  • 5. The SIMPLEST CASE Simplest case: optional pattern extends bindings from the preceding pattern, and provides binding for 'name' in the OPTIONAL pattern. ResultSet: SELECT ?x ?mbox ?name { ?x mailbox ?mbox . OPTIONAL { ?x name ?name } . } x mbox name AS mailto:alice@example.net Alice BD mailto:bert@example.net Bert EF mailto:eve@example.net NULL
  • 6. Multiple OPTIONALS Optional left-associative (like minus), so a optional b optional c is really ((a optional b) optional c). ResultSet: SELECT ?x ?mailbox ?name ?nick { ?x mailbox ?mbox . OPTIONAL { ?x name ?name } . OPTIONAL { ?x nick ?nick }. } x mbox name nick AS mailto:alice@example.net Alice WhoMe? BD mailto:bert@example.net Bert NULL EF mailto:eve@example.net NULL DuckSoup
  • 7. Multiple OPTIONALS Contd. Note that the second optional binds values to a variable bound by another optional. Thus, the inner pattern will bind x, mbox and optionally label. If it binds label, then the outer pattern has to match it and cannot extend it. So result will have all mbox properties, and all name properties that have an mbox. The outer pattern extends these results. If a subject has no name property, then any nick property for it will be returned. If it does have a name property, then a nick property will be returned only if its target matches a name property for the same subject. However, only label is projected. So then, if there is a name property, label will be bound to that. If not, then it will bind any nick property. Thus, for Alice, we should see the name and no nickname. ResultSet SELECT ?label { ?x mailbox ?mbox . OPTIONAL { ?x name ?label } . OPTIONAL { ?x nick ?label } . } Label Alice Bert DuckSoup AS, BD, EF all have mailboxes. All should match for main. Optional 1: Extends with name for AS and BD, null for EF. Optional 2: Extends optional 1 result set with nickname for EF, since for the AS and BD, nick HAS to match bindings of label in optional 1.
  • 8. Multiple OPTIONALS Contd. SELECT ?label { ?x mailbox ?mbox . OPTIONAL { ?x name ?label } . OPTIONAL { ?x nick ?label } . } SELECT ?label { ?x mailbox ?mbox . OPTIONAL { { ?x name ?label } UNION { ?x nick ?label } . } } Multiple OPTIONAL clauses binding the same variable is similar to yet subtly different from a UNION inside the OPTIONAL. The lefthand query gets ‘nick’ labels for mailboxes that have no ‘name’; the righthand query gets all ‘nick’ and ‘name’ labels for any mailbox. Label Alice Bert DuckSoup Label Alice Bert DuckSoup WhoMe? Multiple OPTIONAL clauses binding the same variable is rarely what you want
  • 9. OPTIONAL WITH EMPTY Here, no pattern to extend (i.e., the pattern is empty). An empty pattern binds no variables, so the optional ‘extends’ the empty result set with any of its variables. Note this is equivalent to dropping the OPTIONAL altogether. ResultSet: SELECT ?x ?nick { OPTIONAL { ?x nick ?nick }. } x nick AS WhoMe? EF DuckSoup
  • 10. NESTING OPTIONALS In the nested optional case, we have (a OPTIONAL (b OPTIONAL c)). Note this differs from the case where we have two optionals that are not nested. In this case, the main pattern once again matches all three individuals, but the optionals being nested means the second optional has the result of the first optional as its main pattern. Thus, the results have mbox, and optionally nick, and possibly name if it has nick too. In particular, the name of bert is not returned, since it has no nick property. Note that b first extends a, and then c will extend b. ResultSet SELECT ?x ?mbox ?name ?nick { ?x mailbox ?mbox . OPTIONAL { ?x nick ?nick OPTIONAL { ?x name ?name } } } x mbox name nick AS mailto:alice@example.net Alice WhoMe? BD mailto:bert@example.net NULL NULL EF mailto:eve@example.net NULL DuckSoup
  • 11. NO-OP OPTIONALS In this case, the optional does not really have any new variables to bind. ?nick is already bound to “Who Me”, so the optional is a no-op. ResultSet SELECT ?nick { AS nick ?nick . OPTIONAL {AS name ?nick} } nick WhoMe?
  • 12. More complex optionals The optional pattern here contains an AND. That is, it can extend bindings from the preceding pattern for ?x only when ?x has both nick and name. Only Alice will have bindings for ?nick and ?name. ResultSet: SELECT ?x ?mbox ? nick ?name { ?x mailbox ?mbox . OPTIONAL { ?x nick ?nick . ?x name ?name } . } x mbox name nick AS mailto:alice@example.net Alice WhoMe? BD mailto:bert@example.net NULL NULL EF mailto:eve@example.net NULL NULL
  • 13. OPTIONAL and FILTER FILTER applies only to pattern containing it OPTIONAL only vs. main pattern SELECT ?x ?name { ?x mailbox ?mbox . OPTIONAL { ?x name ?name . FILTER (?name = “Bert”) } . } SELECT ?x ?name { ?x mailbox ?mbox . OPTIONAL { ?x name ?name . } FILTER (?name = “Bert”) } x name AS NULL EF NULL BD Bert x name BD Bert
  • 14. Disconnected Optionals The optional pattern extends bindings from the preceding pattern but shares no variables in common. Basically this will be a cross product. ResultSet: SELECT ?x ?nick ?name { ?x nick ?nick . OPTIONAL { ?y name ?name } . } x nick y Name AS WhoMe? AS Alice AS WhoMe? BD Bert EF DuckSoup AS Alice EF DuckSoup BD Bert Cross products generally perform terribly; avoid them
  • 15. Disconnected Optionals And filters The optional pattern extends bindings from the preceding pattern but shares no variables in common. Basically this will be a cross product. ResultSet: SELECT ?x ?nick ?name { ?x nick ?nick . OPTIONAL { ?y name ?name FILTER (?x=AS) } . } x nick y Name AS WhoMe? AS Alice AS WhoMe? BD Bert EF DuckSoup NULL NULL
  • 16. OPTIONAL and negation OPTIONAL can test for absence of triples Uses FILTER and not(bound(?v)) FILTER for ?v to be NULL, i.e. not exist SELECT ?x ?mbox { ?x mailbox ?mbox . OPTIONAL { ?x name ?name } FILTER (not(bound(?name)) } x mbox EF mailto:eve@example.net EF is the only entity with no name property
  • 17. SPARQL 1.1 Negation SPARQL 1.1 added explicit negation obviates not(bound(?v)) SELECT ?x ?mbox { ?x mailbox ?mbox . FILTER NOT EXISTS { ?x name ?name } } x mbox EF mailto:eve@example.net EF is the only entity with no name property
  • 18. SPARQL 1.1 Minus MINUS computes set difference expresses some forms of negation SELECT ?x ?mbox { ?x mailbox ?mbox . MINUS { ?x name ?name } } x mbox EF mailto:eve@example.net subtract entities with name from entities with mailbox