Search code examples
sparqldbpedia

How to show only the string and not URI in SPARQL query result?


Having the following query, I desire to show only "Jorge Glas"

prefix dbp: <http://dbpedia.org/property/> 
prefix dbpedia:<http://dbpedia.org/resource/>
prefix dbpedia-owl:<http://dbpedia.org/ontology/>
SELECT str(?leader) as ?label
WHERE {
dbpedia:Ecuador dbpedia-owl:leader ?leader
}

I desire to show only "Jorge Glas"


Solution

  • There are a couple of ways to approach this. One is to use SPARQL REPLACE to get the string you want:

    REPLACE(?leader, "^.*/", "")
    

    That gets you "Jorge_Glas", then you can do the same to replace the underscore with a space:

    REPLACE(?x, "_", " ")
    

    However, this is not how you should use DBPedia resources. Most DBPedia resources have an rdfs:label that will give you the desired name result in multiple languages. So a first step is to find out what DBPedia has on these resources through an exploratory query:

    SELECT (str(?leader) as ?label) ?p ?o
    WHERE {
       dbpedia:Ecuador dbpedia-owl:leader ?leader .
       ?leader ?p ?o
    }
    

    You'll find that the matches for ?leader have rdfs:label properties in multiple languages. To get the English label, use the following:

    SELECT ?leaderName
    WHERE {
       dbpedia:Ecuador dbpedia-owl:leader ?leader .
       ?leader rdfs:label ?leaderName .
       FILTER (lang(?leaderName) = "en")
    }