Re: question about OPTIONAL and UNION key words

> 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

Received on Thursday, 28 May 2009 07:43:54 UTC