question about OPTIONAL and UNION key words

View: New views
2 Messages — Rating Filter:   Alert me  

question about OPTIONAL and UNION key words

by Mo Zhou :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

I recently read the specification. It is very helpful. However I got
confused by the difference between OPTIONAL and UNION key words. In
all queries using OPTIONAL, we can use UNION to write a query that
generates the same results. and vice versa.

for example:

select ?x ?mbox
where{
?x foaf:name ?name .
optional {?x foaf:mbox ?mbox} .
optional {?x foaf:homepage ?hpage}
}

will generate the same result as

select ?x ?mbox
where{
{?x foaf:name ?name } .
UNION
{?x foaf:mbox ?mbox} .
UNION
{?x foaf:homepage ?hpage}
}

So why the specification includes both OPTIONAL and UNION?

--
Thanks,
Mo



Re: question about OPTIONAL and UNION key words

by Richard Newman-8 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

> I recently read the specification. It is very helpful. However I got
> confused by the difference between OPTIONAL and UNION key words. In
> all queries using OPTIONAL, we can use UNION to write a query that
> generates the same results. and vice versa.
>
> ...

>
> So why the specification includes both OPTIONAL and UNION?

I'm afraid you've misread the spec.

You can rewrite some queries in the other form, but not in the way you  
think.

OPTIONAL binds a dependent clause to another; UNION executes clauses  
in parallel. Your first query:

   ?x foaf:name ?name .
   optional {?x foaf:mbox ?mbox}
   optional {?x foaf:homepage ?hpage}

can be approximately phrased in English as "find all ?x with a name.  
for each of those ?x, try to find their mailbox...".

Your second query:

   {?x foaf:name ?name }
   UNION
   {?x foaf:mbox ?mbox}
   UNION
   {?x foaf:homepage ?hpage}

is instead "find all people with names. also find all people with  
mboxes. also find all people with homepages".

You might find it helpful to consider the algebraic forms of these.  
The UNION query (pulled out of AllegroGraph) is:

(:union
   (:union
     (:bgp #(?x !<http://xmlns.com/foaf/0.1/name> ?name))
     (:bgp #(?x !<http://xmlns.com/foaf/0.1/mbox> ?mbox)))
   (:bgp #(?x !<http://xmlns.com/foaf/0.1/homepage> ?hpage)))

whilst the OPTIONAL query is:

(:left-join
   (:left-join
     (:bgp #(?x !<http://xmlns.com/foaf/0.1/name> ?name))
     (:bgp #(?x !<http://xmlns.com/foaf/0.1/mbox> ?mbox))
    t)
   (:bgp #(?x !<http://xmlns.com/foaf/0.1/homepage> ?hpage))
   t)

Quite different!

-R