Sparql query: find objects with same property obje

2019-02-28 15:05发布

Suppose we have a dataset that looks like this:

:person :wantsCD :cd1; :wantsCD :cd2 .
:storeA :sellsCD :cd1; sellsCD :cd2; sellsCD :cd3 .
:storeB :sellsCD :cd1; sellsCD :cd10; sellsCD :cd100 .

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? The query should also work when the number of CD's the :person wants is unknown at runtime. I tried:

SELECT DISTINCT ?store ?cd
WHERE { 
 :person :wantsCD ?cd.
 ?store :sellsCD ?cd.
}

but this returns both :storeA and :storeB, since :storeB also sells :cd1.

标签: rdf sparql
1条回答
一夜七次
2楼-- · 2019-02-28 15:53

The Solution

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.
    }
  }
}

Notes

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
查看更多
登录 后发表回答