3

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.)

logi-kal
  • 7,107
  • 6
  • 31
  • 43
cknoll
  • 2,130
  • 4
  • 18
  • 34

2 Answers2

6

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". }
  }
}
Valerio Cocchi
  • 1,891
  • 1
  • 6
  • 18
  • 1
    This is a very neat solution which provides sufficient information to construct the full version of the graph the OP wants to visualize. The clever bit is the use of the zero-length property path - it would be good if the answer included a description of how this key part works. – nickform Feb 16 '21 at 11:24
3

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.

logi-kal
  • 7,107
  • 6
  • 31
  • 43