I am looking to get a sub graph of a given node to a given k level
of depth as shown in the following image for k=2.
If I go to https://dbpedia.org/sparql and select a ?city
I want to get all the details of the city graph to say 5 levels. I am looking for a generic query that do not need to have knowledge of the graph to fetch the data like below.
CONSTRUCT {
?city a ?plebs .
?mayor foaf:gender ?gender.
?city dbo:country ?ctr .
?city dbo:populationTotal ?pop.
?city dbo:leaderParty ?party .
?city rdfs:label ?cityName .
?party dbo:ideology ?ideology
} WHERE {
?plebs rdfs:subClassOf dbo:Settlement.
?city a ?plebs .
?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader | dbo:leaderName) ?mayor .
?mayor foaf:gender ?gender.
?city dbo:populationTotal ?pop .
?city rdfs:label ?cityName .
?city dbo:country ?ctr .
?city dbo:leaderParty ?party .
?party dbo:ideology ?ideology .
FILTER(str(?gender) = "female")
}
ORDER BY DESC(?pop)
How can I write a generic SPARQL query that can work on any database for a given node?
It's actually pretty easy:
construct {
?s ?p ?o.
?o ?op ?oo.
?oo ?oop ?ooo.
?ooo ?ooop ?oooo.
?oooo ?oooop ?ooooo.
}
where {
bind(city:_London as ?s)
?s ?p ?o.
optional {
?o ?op ?oo.
optional {
?oo ?oop ?ooo.
optional {
?ooo ?ooop ?oooo.
optional {
?oooo ?oooop ?ooooo.
}
}
}
}
}
The construct statement will return the graph of all outbound links from the city in question, and any time you have a null returned, that triple will simply not be constructed.