Home > database >  How to search a list of Wikidata IDs and return the P31 ("instance of") property using SPA
How to search a list of Wikidata IDs and return the P31 ("instance of") property using SPA

Time:03-04

How do I get the instance type(s) (i.e., property=P31 and associated labels) for multiple Wikidata IDs in a single query? Ideally, I want to output a list with the columns: Wikidata ID | P31 ID | P31 Label, with multiple rows used if a Wikidata ID has more than one P31 attached.

I am using the web query service, which works well in part, but I am struggling to understand the syntax. I have so far managed to work out how to process a list of items, and return each one as a row (simple I know!), but I can't work out how to generate a new column that gives the P31 item:

SELECT ?item 
WHERE {
  VALUES ?item { wd:Q1347065 wd:Q731635 wd:Q105492052 }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

I have found the following from a previusly answered question here, which returns multiple rows per an item of interest, but this requires specifying the P31 type at the outset, which is what I am looking to generate.

Any help would be appreciated as I am really stuck understanding the syntax.

Update: I have now worked out how to return P31s for a single ID. I need to expand this query to receive a list of IDs, and include the ID as a column:

SELECT ?item ?itemLabel
 WHERE
 {
   wd:Q18656 wdt:P31 ?item.
   SERVICE wikibase:label { bd:serviceParam wikibase:language  "[AUTO_LANGUAGE]". }
 } 

CodePudding user response:

If I correctly understood your problem, you can use the following query:

SELECT ?item ?class ?classLabel
WHERE {
  VALUES ?item { wd:Q1347065 wd:Q731635 wd:Q105492052 }
  ?item wdt:P31 ?class .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Here, first you fix the possible values for ?item, then you say that ?item is instance of a certain ?class and contestually you also retrieve the label for such ?class.

  • Related