Skip to content

Instantly share code, notes, and snippets.

@cv711
Last active April 15, 2023 07:01
Show Gist options
  • Save cv711/5875299 to your computer and use it in GitHub Desktop.
Save cv711/5875299 to your computer and use it in GitHub Desktop.
SPARQL queries to get the names of cities of the world, based on population from Wikipedia
-- just the city resource
SELECT DISTINCT ?citylabel ?countrylabel ?pop
WHERE {
?city rdf:type dbpedia-owl:City.
?city rdfs:label ?citylabel.
?city dbpedia-owl:country ?country.
?country rdfs:label ?countrylabel.
?city dbpedia-owl:populationTotal ?pop .
FILTER ( lang(?countrylabel) = 'en' and lang(?citylabel) = 'en' and ?pop>10000)
}
-- union over resources
SELECT DISTINCT *
WHERE {
{
?city rdf:type dbpedia-owl:Town;
rdfs:label ?label ;
dbpedia-owl:country ?country ;
dbpedia-owl:populationTotal ?pop .
FILTER ( lang(?label) = 'en' and ?pop>10000)
}
UNION
{
?city rdf:type dbpedia-owl:City;
rdfs:label ?label ;
dbpedia-owl:country ?country ;
dbpedia-owl:populationTotal ?pop .
FILTER ( lang(?label) = 'en' and ?pop>10000)
}
}
-- alternative source for data rdf:type dbpedia-owl:Settlement
@HRezaei
Copy link

HRezaei commented Nov 10, 2016

@UnpredictablePrashant
Copy link

You just need to add the prefix. This code might help you.

PREFIX  dbpedia-owl:  <http://dbpedia.org/ontology/>
PREFIX dbpedia: <http://dbpedia.org/resource>
PREFIX dbpprop: <http://dbpedia.org/property>
SELECT DISTINCT ?citylabel ?countrylabel ?pop
WHERE {
   ?city rdf:type dbpedia-owl:City.
   ?city rdfs:label ?citylabel.
   ?city dbpedia-owl:country ?country.
   ?country rdfs:label ?countrylabel.
   ?city dbpedia-owl:populationTotal ?pop .
   FILTER ( lang(?countrylabel) = 'en' and lang(?citylabel) = 'en' and ?pop>10000)
}

@sudoevans
Copy link

sudoevans commented Apr 15, 2023

This one really helped me:

I just limit the output so I could not get buffer error issues since my sparql code is local.

PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
PREFIX dbpedia: <http://dbpedia.org/resource>
PREFIX dbpprop: <http://dbpedia.org/property>

SELECT DISTINCT ?citylabel ?countrylabel ?pop
WHERE {
  ?city rdf:type dbpedia-owl:City .
  ?city rdfs:label ?citylabel .
  ?city dbpedia-owl:country ?country .
  ?country rdfs:label ?countrylabel .
  ?city dbpedia-owl:populationTotal ?pop .
  FILTER ( lang(?countrylabel) = 'en' and lang(?citylabel) = 'en' and ?pop > 10000000 )
}
ORDER BY DESC(?pop)
LIMIT 5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment