Sparql query: find objects with same property objects

前端 未结 1 410
长发绾君心
长发绾君心 2021-01-24 08:25

Suppose we have a dataset that looks like this:

:person :wantsCD :cd1; :wantsCD :cd2 .
:storeA :sellsCD :cd1; sellsCD :c         


        
1条回答
  •  执笔经年
    2021-01-24 09:14

    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
    

    0 讨论(0)
提交回复
热议问题