0

I am writing SPARQL queries on Wikidata entities, and I would like to get all the entities matching "is entity Q3 OR one of its subclasses".

I know how to get the subclasses only with the following query :

SELECT DISTINCT ?item
WHERE {
{ ?item wdt:P279 wd:Q3 . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

But I would like to also have the original parent entity (here Q3) in the response. How should I modify my query so that Q3 is also returned ?

Ewaren
  • 1,343
  • 1
  • 10
  • 18

2 Answers2

1

In order to get entities matching something, you will need to use wdt:P31, i.e. "instance of". wdt:P279 is "subclass of"

In terms of your query, I'd use something like this:

SELECT DISTINCT ?itemLabel ?superClassLabel
WHERE {
 ?item wdt:P31/wdt:P279* ?superClass 
    VALUES ?superClass {wd:Q3}

SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
Valerio Cocchi
  • 1,891
  • 1
  • 6
  • 18
  • This is not really what I am asking for unfortunately. I want to modify my query so that it returns all the same results + an extra row with "wd:Q3" in it. I don't want instances of Q3, I want Q3 itself. – Ewaren Jul 09 '20 at 20:39
1

I ended up finding the solution myself : I needed to add a ? (which means "0 or 1") after the property in my query.

So it becomes :

SELECT DISTINCT ?item
WHERE {
{ ?item wdt:P279? wd:Q3 . } # here is the extra "?" after "wdt:P279"
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

And now this properly returns Q3 AND all of its subclasses.

Ewaren
  • 1,343
  • 1
  • 10
  • 18