Geerten Verweij
Geerten Verweij

Reputation: 33

filtering sparql results before doing an arbitrairy path query

To explain my question I will give a fruity example:

Let's say we have an RDF triple-store filled with 3 classes:

:Apple
:Orange
:Pear

And we have 1 property:

:friendsWith

Apples, oranges and pears can be friends with other apples, oranges and pears. The query that I want to implement is:

"Given apple/123, give me all apples and pears with which apple/123 is friends through anything but oranges."

My current version of this SPARQL query looks like this:

SELECT DISTINCT ?appleOrPear WHERE {
    <apple/123> :friendsWith* ?appleOrPear .
    FILTER NOT EXISTS {?appleOrPear a :Orange.}
}

This query does indeed give me only apples and pears that are connected to apple/123. However it would also give me apples and pears that are connected through oranges, which I don't want.

So what I need is a way for the results to be filtered before the arbitrairy path part of the query is done. In other words I want to ignore the whole :orange class for the entire query.

Is there any way to do this in SPARQL?

Upvotes: 2

Views: 145

Answers (1)

Damyan Ognyanov
Damyan Ognyanov

Reputation: 786

You may check that there is no node of type :Orange in the :friendsWith chain between <apple/123> and ?appleOrPear.

SELECT distinct ?appleOrPear WHERE {
    <apple/123> :friendsWith* ?appleOrPear .
    filter not exists {
        <apple/123> :friendsWith* ?x .
        ?x :friendsWith* ?appleOrPear .
        ?x a :Orange .
    }
}

Upvotes: 2

Related Questions