Suppose we have a dataset that looks like this:
:person :wantsCD :cd1; :wantsCD :cd2 .
:storeA :sellsCD :cd1; sellsCD :c
I'm interested in finding the stores that sell all the CD's :person wants, i.e. (:storeA). Is it possible to get this result with a SPARQL query?
Yes, the trick is to do something that matches all the stores, and then filters out those for which there is a CD that the person wants that the store does not have:
select ?store where {
#-- matches every store that sells any CD.
?store :sellsCD []
#-- make sure there is no CD that the person wants
#-- that the store does not sell.
filter not exists {
:person :wantsCD ?cd #-- There is no CD that :person wants
filter not exists {
?store :sellsCD ?cd #-- that ?store does not sell.
}
}
}
Thank you very much for providing sample data to work with. Just as a note that might make your life a bit easier, in addition to the ;
notation that you used in, e.g.:
:person :wantsCD :cd1; :wantsCD :cd2
there's also a ,
notation for multiple objects of the same property. You can write that line as:
:person :wantsCD :cd1, :cd2