sparqlwikidata

Imitate behaviour of Wikidata tree in SPARQL


I am trying to reproduce the Wikidata generic tree behaviour (like this) in SPARQL. The concept is that we have an initial tag (Fruit (Q3314483)) and we can change the depth of the tree to get the child of the initial. For example:

- Q3314483 (Fruit)
-- Q89 (Apple)
-- Q169 (Mango)
---- Q599314 (Osteen)
---- Q2663618 (Alphonso)
-- Q196 (Cherry)
...

I am stuck with SPARQL query as I never worked with it before. In particular, there is the thing that I looked for but the problem I can not add depth parameter to this snippet:

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

Can you please help of how to change the script to limit the depth equals 1 to get only the following:

- Q3314483 (Fruit)
-- Q89 (Apple)
-- Q169 (Mango)
-- Q196 (Cherry)
...

Thanks!


Solution

  • When you write wdt:P279*, you are asking for any (even empty) path from the subject and the object of your triple.

    If you don't want to allow a generic path buth ask only for direct subclasses, you can just remove the asterisk *.

    Then, if you wish to ask for path of specific lenght, you can build them as wdt:P279/wdt:P279 (length 2), wdt:P279/wdt:P279/wdt:P279 (length 3), etc.