Get State/Province of a city with SPARQL query

2019-06-07 21:17发布

问题:

I have the following SPARQL query:

SELECT ?item ?itemLabel WHERE {
  ?item wdt:P17 wd:Q16;
    (wdt:P31/(wdt:P279*)) wd:Q515.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

which, in this case, returns cities in Canada. I would also like to to display states/procinces, e.g., the expected output should be

...
Montreal    Quebec
...

or, if I were to run the query for US cities

...
Los Angeles    California
...

How can the query be extended to display states/provinces?

回答1:

You have to follow a path via the property located in the administrative territorial entity and then find some point to stop, i.e. here once the entity is a province of Canada:

SELECT ?item ?itemLabel ?regionLabel 
WHERE { ?item wdt:P17 wd:Q16; 
              (wdt:P31/(wdt:P279*)) wd:Q515; 
              wdt:P131* ?region . 
        ?region wdt:P31 wd:Q11828004 
        SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } 
}

More generally for states of a country, we have to find some generic term that denotes it. This triple pattern would do it:

 ?region (wdt:P31/(wdt:P279*)) wd:Q107390

However, property paths are horrible for triples stores and likely to time out.

Here's a query that at least returns the top level region for a country:

select ?region ?regionLabel 
{ VALUES ?country {wd:Q30} # get the top level regions of the country 
  ?region wdt:P17 ?country . 
  ?region wdt:P31/wdt:P279* wd:Q10864048 . 
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } }