Search code examples
rdfsparqlsemanticssemantic-webdbpedia

For Loop in SPARQL


I have a simple problem. When I run this query on DBpedia SPARQL endpoint, I get a list of 5 movies URIs:

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

select ?film {
?film rdf:type <http://schema.org/Movie>.

}
limit 5

I am trying to access to all predicates and objects of every movie in the list. I tried this but it did not work.

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

select ?film ?p ?o {
?film rdf:type <http://schema.org/Movie>;
      ?p ?o.
}
group by ?film
limit 5

Any suggestion?


Solution

  • SPARQL is recursive by nature so no for loops required. This means, in relation to your 2nd example, it will match all predicates and objects where film is a type of movie. I believe you may be thinking your query is not working when it actually is but the limit on the amount of answers being returned is masking this.

    I suggest for retrieving a single film -

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> 
    select ?s ?o ?o where {
     ?s ?p ?o .
     FILTER (?s = ?film)
     {
      select ?film {
       ?film rdf:type <http://schema.org/Movie> .
      }
      group by ?film
      limit 1
     }
    }