Search code examples
sparqlrdfowl

Getting limited answers using SPARQL


I have a RDF store with list of people and the cities/states they've lived in:

:P1 :hasLivedIn :NewYork

:P2 :hasLivedIn :NewYork
:P2 :hasLivedIn :California

Now, I'd like to use SPARQL to give me a list of all people who have lived in a particular city (e.g. newYork)

When I use this:

select * where { ?p :hasLivedIn :NewYork } 

gives me both :P1 and :P2 but I only want :P1 because only :P1 has lived in only :NewYork.

I can't blacklist the cities using a filter because the cities and states are too many. Is there a way to do this in SPARQL?

Thanks!


Solution

  • An alternative query to the one provided by @YMomb uses negation SPARQL 1.1:

    SELECT  ?p
    WHERE
      { ?p  :hasLivedIn  :NewYork
        FILTER NOT EXISTS { ?p  :hasLivedIn  ?place
                            FILTER ( ?place != :NewYork )
                          }
      }