Sparql query: find objects with same property objects

可紊 提交于 2019-12-31 03:50:06

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/27607609/sparql-query-find-objects-with-same-property-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!