Re: Modeling over-riding inheritance in a triple store

On 2 Aug 2012, at 21:54, James Rothering wrote:

> Is is possible to implement an inheritance hierarchy in a SPARQL query?
> In other words, is it possible to select all from a parent type, but
> overriding from a child type wherever an entry exists?
> 
> I.e., given this data:
> 	ex:parent001  	rdf:type  	ex:"Parent"
> 			ex:widgetName	ex:"test"
> 			ex:hasChild	ex:"child001"
> 			
> 	ex:child001	ex:widgetName	ex:"over-ridden widget".
> 
> Can I craft a select {?s ?p ?o} that will leave out the link between
> parent and child, yet return the over-ridden values of the predicates?
> i.e., that will return:
> 	ex:parent001  	rdf:type  	ex:"Parent"
> 			ex:widgetName	ex:"over-ridden widget".

You can do this with COALESCE in SPARQL 1.1:

SELECT ?id COALESCE(?tChild, ?t) AS ?type) ?type (COALESCE(?nChild, ?n) AS ?name)
WHERE {
   ?id rdf:type ?t .
    OPTIONAL {
       ?id ex:hasChild _:c1 .
       _:c1 rdf:type ?tChild .
    }
    ?id ex:widgetName ?n .
    OPTIONAL {
       ?id ex:hasChild _:c2 .
       _:c2 ex:widgetName ?nChild .
    }
}

This is binding the immediate values, and also binding the child values (where they exist) then returning the child values in preference to the parent ones.

You will get:

?id				?type		?name
ex:parent001	ex:Parent	"test"
ex:child001		ex:Parent	"over-ridden widget"

The OPTIONAL bits can be written more elegantly like OPTIONAL { ?id ex:hasChild/rdf:type ?tChild } if the store supports property paths.

- Steve

-- 
Steve Harris, CTO
Garlik, a part of Experian 
1-3 Halford Road, Richmond, TW10 6AW, UK
+44 20 8439 8203  http://www.garlik.com/
Registered in England and Wales 653331 VAT # 887 1335 93
Registered office: Landmark House, Experian Way, NG2 Business Park, Nottingham, Nottinghamshire, England NG80 1ZZ

Received on Friday, 3 August 2012 09:24:52 UTC