Jasper
Jasper

Reputation: 628

sparql complete tree from subject

When I have for example a person graph e.g. John and john has a work adress home adress phone numbers relations etc.

Is it possible to retrieve everything that is connected to john and to the subclasses of john without knowing what it is?

So that I can retrieve for example the following

John < address < house_number
     < mobile_number
     < company < address
               < function < office number < etc...

And retrieve this via:
     "John" rdfs:everything ?everything ... as deep as the tree goes.

Or do I need to know the graph?

Upvotes: 3

Views: 1232

Answers (2)

Chris
Chris

Reputation: 8978

This is a nice solution from Joshua Taylor it seems on Apache Jena the query is a little different.

SELECT ?o WHERE {
  :john (<>|!<>)+ ?o
}

Else it throws an error "Unresolved prefix :"

Upvotes: 0

Joshua Taylor
Joshua Taylor

Reputation: 85863

Your terminology is a bit off, as things like addresses, mobile numbers, etc., aren't subclasses of John. RDF is about triples (labeled directed edges), and John's address is the object of a triple that has the form John hasAddress AddressOfJohn. Speaking in graph based terms, it sounds like you're asking whether it's possible to retrieve all the things that are reachable by some directed path beginning at John. It's easier to work with concrete data, so let's suppose that you've got this data:

@prefix : <http://stackoverflow.com/q/20878795/1281433/> .

:john :hasAddress :addressOfJohn ;
      :hasMobileNumber :mobileNumber ;
      :hasCompany :company .

:addressOfJohn :hasHouseNumber :houseNumber .

:company :hasAddress :addressOfCompany ;
         :hasFunction :function .

SPARQL 1.1 added support for Property Paths, which a sort of like a regular expression language for sequences of properties, including typical operators like * (any number of repetition) and + (one or more). Unfortunately, you can't use variables in property paths, so you can't just do

:john ?p+ ?object

However, as noted in a similar question on answers.semanticweb.com SPARQL: property paths without specified predicates, you can construct a disjunction that will match every property. For instance, since : is a defined prefix and is thus an IRI, the pattern :|!: will match any property (since everything is either : or it isn't). That mans that (:|!:)+ is a genuine wildcard path. Thus, we can write a query like the following and get the corresponding results:

prefix : <http://stackoverflow.com/q/20878795/1281433/>

select ?object where { 
  :john (:|!:)+ ?object 
}
---------------------
| object            |
=====================
| :company          |
| :function         |
| :addressOfCompany |
| :mobileNumber     |
| :addressOfJohn    |
| :houseNumber      |
---------------------

Upvotes: 5

Related Questions