0

I have a structure that have different length from the root to leaf. I wish to output them into a list. I also wish all parents and grand parents are under market_segment. the maximum depth is 5 level, How do I bound the result to only Market_segment without going over to the parents of Market_segment. currenly this query will return parents of Market_Segment, if the path is shorter than 5.

PREFIX mdy: <http://www.owl-ontologies.com/mdys.owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?node ?parent ?gparent ?ggparent ?gggparent ?ggggparent
       WHERE {
                 ?node rdfs:subClassOf* mdy:Market_Segment                 
                   OPTIONAL {?node rdfs:subClassOf ?parent.
                    OPTIONAL {?parent rdfs:subClassOf ?gparent.
                    OPTIONAL {?gparent rdfs:subClassOf ?ggparent.
                    OPTIONAL {?ggparent rdfs:subClassOf ?gggparent.
                    OPTIONAL {?gggparent rdfs:subClassOf ?ggggparent.
                     }}}}}
}
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
Chao Chen
  • 1
  • 2
  • 1
    Do either [Calculate the depth of subclass in the OWL ontology](http://stackoverflow.com/q/26115488/1281433) or [Sparql query for children, grandchildren, .. of a class](http://stackoverflow.com/q/23094361/1281433) help? They're similar questions. You wouldn't get different variables (?parent, ?gparent, etc.) so easily, but you could get the depth of each node. – Joshua Taylor Oct 06 '14 at 21:49

1 Answers1

0

Use inverse property paths:

PREFIX mdy: <http://www.owl-ontologies.com/mdys.owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?node ?parent
   WHERE {
             ?node ^rdfs:subClassOf* mdy:Market_Segment  .
             ?node ^rdfs:subClassOf ?parent         
}

See also http://www.w3.org/TR/sparql11-query/#propertypaths

enridaga
  • 631
  • 4
  • 9