How to get *all* superclasses of a Wikidata entity with SPARQL?

Viewed 513

I am interested in visualizing the Wikidata class hierarchy to create graphs like directed graph of superclasses of vectorspace entity

I know how I can get direct superclasses of a Wikidata entity. For this I use SPARQL code like:

SELECT ?item ?itemLabel 
WHERE 
{
    wd:Q125977 wdt:P279 ?item.
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

where wdt:P279 denotes the subclass of-property.

However, this direct method requires many single requests to the Wikidata API.

How is it possible to get the same information with a single SPARQL query?

(Note that the example graph above only shows an abbreviated version. The final desired graph of all superclasses is 13 levels deep and has 69 nodes which means 68 single requests, see this jupyter notebook if interested.)

2 Answers

You could use a query like this to create your taxonomy (with labels) as triples directly.

CONSTRUCT {
  ?item1 wdt:P279 ?item2.
  ?item1 rdfs:label ?item1Label.
  ?item2 rdfs:label ?item2Label.
}
WHERE {
  SELECT ?item1 ?item2 ?item1Label ?item2Label
   WHERE {
    wd:Q125977 (wdt:P279*) ?item1, ?item2.
    FILTER(EXISTS { ?item1 wdt:P279 ?item2. })
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  }
}

I think you need a query like the following:

SELECT ?class ?classLabel ?superclass ?superclassLabel
WHERE 
{
    wd:Q125977 wdt:P279* ?class.
    ?class wdt:P279 ?superclass.
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

where wdt:P279* is a zero-or-more path connecting a class with (a superclass of) one of its superclasses.

This will generate a mapping "class->superclass" containing all what you need for building the graph that you illustrated.

Related