Search code examples
sparqlrdfsemantic-webowlontology

SPARQL getting an intersecting set


I following data:

:A :hasCity City1
:A :hasCity City2
:A :hasCity City3
:A :hasCity City4

:K :hasCity City1
:K :hasCity City2

......

I'm trying to find all subjects that have cities 1 and 2 so I wrote the query:

select ?s 
{
   ?s :hasCity ?city.
   FILTER (?city =:City1 && ?city=:City2)
}

But, I don't get back any results.

if I just do:

select ?s 
{
   ?s :hasCity ?city.
   FILTER (?city =:City1)
}

I get back A,K,Q,M and if I just do:

select ?s 
{
   ?s :hasCity ?city.
   FILTER (?city =:City2)
}

I get back A,K,L

so when I use the && operator, I should get back A&K, right? Am I missing something?


Solution

  • What you need to do is ask for all subjects that share the same set of objects, using a triple pattern on the same property. You'd end up with a very simple query:

    SELECT ?s {?s :hasCity :City1, :City2}
    

    With :hasSubject, if you want to keep the one-line query, you just ask for the inverse of the property:

    SELECT ?s { ?s ^:hasSubject :City1, :City2}
    

    When using = , you need to ensure you compare apples with apples. For example ?a = ?b, or str(?a) = str(<b>).