Search code examples
propertiessparqlwikidata

How to get the values of the P642 of-predicate applied to a previous statement in a SPARQL query for Wikidata?


I would like to get the provincial or territorial capital city in Canada with the names of the provinces.

SELECT ?item ?itemLabel ?provinceOrTerritoryLabel
    WHERE 
    {
      ?item wdt:P31 wd:Q21507383. # provincial or territorial capital city in Canada (Q21507383)
      wd:Q21507383 pq:P642 ?provinceOrTerritory.
     ?provinceOrTerritory wdt:P31 wd:Q11828004. # province of Canada (Q11828004)
      
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }

I thought that this should work but it is not the case.

Thank you very much for your help!

EDIT

My intention here is really to understand how to get a lot of wikidata that are related with the property "of (P642)". For instance, for Toronto (https://www.wikidata.org/wiki/Q172), we get:

instance of > provincial or territorial capital city in Canada > of (P642) > Ontario


Solution

  • (Edited answer, now almost making sense)

    This is the query you are asking for:

    SELECT ?capital ?capitalLabel ?of ?ofLabel WHERE {
      ?capital p:P31 ?statement.
      ?statement ps:P31 wd:Q21507383.
      OPTIONAL { ?statement pq:P642 ?of. }
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    

    Here's the link

    Running that, you'll see why I didn't quite follow you wishes earlier: the "of" qualifier P642 isn't really the way this is modelled most often, nor should it be.

    The reason is, among other things, that "of" is so entirely generic that it is close to breaking the whole idea of Wikidata.

    So that's why I immediately went a different route to get the provinces, territories & their capitals. Which wasn't perfect, either. There's an explicit property for capitals, and that's how you best get the data, which is actually complete:

    SELECT ?provinceOrTerritory ?provinceOrTerritoryLabel ?capital ?capitalLabel
    WHERE {
        ?provinceOrTerritory wdt:P31/wdt:P279  wd:Q2879;
        OPTIONAL { ?provinceOrTerritory wdt:P36 ?capital. }
        SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    

    (Link)