Search code examples
sparqldbpedia

SPARQL for direct dbpedia resource OR wikiPageRedirects


I'm trying to query data from dbpedia by a country's name. I want it to find it whether there is a resource for that country or via its existence in wikiPageRedirects. Here is a working version:

PREFIX res: <http://dbpedia.org/resource/>
PREFIX ont: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT ?country ?capital ?label 
WHERE {
    { res:Dominion_of_Canada ont:capital ?capital .
    ?capital rdfs:label ?label }
UNION
    { res:Dominion_of_Canada ont:wikiPageRedirects ?country .
    ?country ont:capital ?capital .
    ?capital rdfs:label ?label }

FILTER (lang(?label) = "en") 
} 

I'd like (if possible), to factor out the ?country. Is it possible to assign a resource to a variable such that the SPARQL query looks like the following?

SELECT ?country ?capital ?label
WHERE {
{ ?country EXISTS res:Dominion_of_Canada } # to get the idea across
UNION
{ res:Dominion_of_Canada ont:wikiPageRedirects ?country }

?country ont:capital ?capital .
?capital rdfs:label ?label .
FILTER (lang(?label) = "en")
}

As ever, speed is important, too. If the resource exists, then it'd be better if it skipped searching on wikiPageRedirects.


Solution

  • Checking whether a resource "exists" or not is a bit vague, since IRIs are just constant data. The question is really whether DBpedia contains any triples about a particular resource. In your case, you're wanting to know whether it it redirects to anything else, or if it has properties of its own. A property path of the form dbpedia:France dbpedia-owl:wikiPageRedirects* ?country is really probably the best way to do that. If there are no redirect links, then ?country is dbpedia:France, and if there are, then ?country is the value of the redirects. The only way to "check" is to look for those triples. I think that means you will end up with something like this (similar to what's shown in my answer to another question involving redirects):

    select ?country ?anthem ?author {
      #-- The only way to really "check" that the resource 
      #-- "exists" and is not a redirect, is by checking 
      #-- whether it has any redirect links.  If it doesn't,
      #-- then ?country is dbpedia-owl:France, like you want
      #-- and if it does, then then you want to follow them.
      dbpedia:France dbpedia-owl:wikiPageRedirects* ?country .
    
      #-- I'm using anthem and author here because 
      #-- it doesn't look like there was reliable information
      #-- about the capital.
      ?country dbpedia-owl:anthem ?anthem .                  
      ?anthem dbpprop:author ?author .
    }
    

    SPARQL results