SPARQL : Find Difference and Common Elements in 2 Sets

1.3k views Asked by At

I am a newbie to SPARQL and struggling to achieve these 2 goals and need your help. I have 2 classes where I have stored the keywords of python and CPP respectively. Now I intend to find the common keywords from these 2 sets and also the difference between the 2 (meaning, keywords which exists in python but not in CPP and vice versa). I have tried MINUS and NOT EXISTS version of the queries but to no help. To find the difference in 2 sets, I tried the below query:

SELECT ?subject
    WHERE 
    { ?subject a python:Keywords. 
    { FILTER NOT EXISTS {?subject a cpp:Keywords} }
    }

To find the common elements in 2 sets, I tried the below query:

select ?subject
where{ ?subject a python:Keywords. FILTER  EXISTS { ?object a cpp:Keywords}
}

None of them are working. Please help

2

There are 2 answers

0
Joshua Taylor On

The problem in your code

In your first query, the problem is that you've put the filter inside of another set of braces. That is, you have:

SELECT ?subject
    WHERE 
    { ?subject a python:Keywords. 
    { FILTER NOT EXISTS {?subject a cpp:Keywords} }
    }

but should have instead:

SELECT ?subject
    WHERE 
    { ?subject a python:Keywords. 
      FILTER NOT EXISTS {?subject a cpp:Keywords}
    }

The difference is important, because the first is filtering the matches for the enclosing pattern, which doesn't actually have any effect.

The solution

After that, Abecee's answer is what you need. The intersection is simply things that are both types:

?x a :type1, :type2 

and the difference is things that are one type but not the other:

?x a :type1
filter not exists { ?x a :type2 }

Similar questions and answers

1
Abecee On
SELECT ?subject
  WHERE 
  { ?subject a python:Keywords .
    ?subject a cpp:Keywords .
  }

should give you the common keywords.

SELECT ?subject
  WHERE 
  { ?subject a python:Keywords. 
    FILTER NOT EXISTS {?subject a cpp:Keywords}
  }

should return python keywords, which are not cpp keywords.