0

I need the complete hierarchy that is under Food Q2095. All levels of subclasses should also be included. Additionally all entities that are attached to a (sub)class.

How can I query this?

SELECT ?node WHERE {?node ?pred wd:Q2095}

Direct query at wikidata

Thank you.

ozz
  • 175
  • 1
  • 11
  • All subclasses can be retrieved by `SELECT ?node WHERE {?node wdt:P279* wd:Q2095}` - not sure what you mean by "level", nor do I understand what you mean by "all entities" of a subclass. All entities for each subclasses would lead to a very large result depending on the chosen superclass. – UninformedUser May 24 '20 at 10:49
  • SPARQL is not really made for path queries, but you can get the distance of a class with `SELECT ?cls (count(?tmp) as ?distance) WHERE { ?cls wdt:P279* ?tmp . ?tmp wdt:P279+ wd:Q2095 . } group by ?cls order by asc(?distance)` - though there might be corner cases like cycles in the hierarchy resp. multiple paths which obviously will lead to wrong results – UninformedUser May 24 '20 at 10:57
  • Thanks. The second question points me in the right direction – ozz May 24 '20 at 16:45

1 Answers1

1

Try this:

SELECT ?subclass ?entity ?predicate 
WHERE{
   ?subclass wdt:P279* wd:Q2095
   {?entity ?predicate ?subclass }
  UNION 
  {?subclass ?predicate ?entity }
       }

The first part of the body of the query makes sure your subclass eventually leads to food.

The second looks for entities that are attached to the subclass, i.e. are either the object or the subject of a triple containing the said subclass.

Depending on whether you want to restrict the scope of the predicate. (i.e. avoid rdfs:label and others), you can use something like this too:

?predicate a owl:ObjectProperty .

under the first line of the body of the query.

@UninformedUser's comment shows you how to get the level of the subclass.

Valerio Cocchi
  • 1,891
  • 1
  • 6
  • 18