Reputation: 947
Considering the following dataset I am trying to find all friends-of-friends but stop expanding the path as soon as one of the friends is e.g. a Lawyer.
:Ben :knows :Lena .
:Lena :knows :Grek .
:Grek :knows :John .
:John :knows :Bill .
:Ben :knows :Peter .
:Peter :knows :Cece .
:Cece :knows :Joe .
:Joe :knows :Mike .
:Cece :profession :Lawyer .
The expected result is:
Ben, Lena, Grek, John, Bill, Peter
What I am doing now is:
SELECT ?friend
WHERE {
:BEN :knows+ ?friend.
FILTER NOT EXISTS { ?friend ^:knows*/:profession :Lawyer}
}
For bigger datasetes this is just way to slow and actually holds a lot of data in memory that is irrelevant.
Is it possible to cut the path expansion instead of filtering the results afterwards?
Thanks!!
Upvotes: 2
Views: 147
Reputation: 466
There is no way to "cut" a property path expression like this in SPARQL.
Moreover, I don't think the query you are currently using does what you want. It will exclude any person who is known by a lawyer, regardless if the lawyer is on a path of :knows links from Ben. For example, if Alice was a lawyer, and Alice knew Bill, Bill would no longer be included in the results. I think this is a better query for what you describe:
PREFIX : <http://example.org/>
SELECT ?friend WHERE {
:Ben :knows+ ?friend.
MINUS {
:Ben :knows+ ?lawyer .
?lawyer :profession :Lawyer ; :knows* ?friend .
}
}
Depending on the SPARQL system you are using, the use of MINUS
instead of FILTER NOT EXISTS
may also have better performance.
Upvotes: 4