Friday, 29 October 2010

SPARQL RDF Query Language and RDF Containers (i.e. rdf:Seq, rdf:Bag and rdf:Alt)

SQPARQL and RDF
SPARQL is the query language for RDF. Most of us learn SQL langauge for database first and then we learn about SPARQL and RDF. RDF is a datamodel which supports a simple structure of Subject, Predicate and Object.

After SPARQL basic is learned, then here comes the trouble of querying RDF containers. There are three kinds of containers in RDF, namely, Seq, Bag and Alt. So, how do we query the following RDF graph about bags. It would be something like this from looking at the RDF/XML.

PREFIX rdf .
PREFIX cd .
SELECT ?artist
WHERE 
{
 cd:Artist ?bag.
?bag rdf:li ?artists.
} 

It won't give us any results because the actual graph and the representation form are different. Lets see the RDFXML and RDF graph for some examples.

RDF Bag




John
      Paul
      George
      Ringo
    
  









RDF Sequence





  
    
      George
      John
      Paul
      Ringo 







RDF Alt (Alternate)




  
    
      CD
      Record
      Tape
    
  









From the above RDF graphs, we can see that tough these are annotated by <rdf:li>, in the real representation they are represented as rdf:_1, rdf#_2, rdf#_3, .... And the type of the container, i.e. semantic of the list is defined by using rdf:type property to the corresponging container type (bag, seq, alt). That's the reason the above SPARQL query doesn't work. Here is the query that works.

  PREFIX dc: <http://purl.org/dc/elements/1.1/> .
  PREFIX asn: <http://purl.org/ASN/schema/core/> .
  PREFIX gemq: <http://purl.org/gem/qualifiers/> .
  PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
SELECT ?statement ?type
WHERE
{
  ?doc a asn:StandardDocument ;  gemq:hasChild ?seq.
  ?seq ?t ?statement.
  ?statement a ?type.

}

In the above query, a unbounded variable "?t" is used to get all the elements of the container.  I ran into this pitfall once and it took me an hour to figure that out. So, I decided to share this so that you won't ran into it and spend hours on that.


References: Sample RDF data from http://www.w3schools.com/rdf/rdf_containers.asp

1 comment: