3

I'm studying SPARQL and I have a doubt about queries.

Suppose I have a simple ontology like the following

:Jack a :Worker ; :worksAt :Project1,:Project2
:Bob  a :Worker ; :worksAt :Project2,:Project3
:Mike a :Worker ; :worksAt :Project3,:Project1

Now I want to ask for the couple of workers who worked on the same project. If I try something like

SELECT ?x,?y
WHERE
{
    ?x :worksAt ?p
    ?y :worksAt ?p

}

What happens is that the query also analyzes cases where ?x and ?y are the same resource, hence I have stuff like [Jack,Jack] in the results.

If I do

 SELECT ?x,?y
    WHERE
    {
        ?x :worksAt ?p
        ?y :worksAt ?p
        FILTER (?x != ?y)
    }

the query works properly, but for very complicated queries I find myself doing hundreds of FILTERs like that one.

Is there a better way to specify that ?x and ?y must be different resources? Thank you in advance for your answers!

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Stefano Kira
  • 175
  • 2
  • 3
  • 16
  • 1
    `FILTER (str(?x) > str(>y))` avoids the duplicates of (x,y) and (y,x) – AndyS Feb 07 '16 at 17:54
  • 2
    Could you elaborate on *hundreds of filters like that one*? – Tomasz Pluskiewicz Feb 07 '16 at 19:21
  • It would be easier to answer if you had a non-trivial example. Both the [DISTINCT](https://www.w3.org/TR/sparql11-query/#modDistinct) and [SAMPLE](https://www.w3.org/TR/sparql11-query/#defn_aggSample) might help here. You could also use the same variable for different query paths and join the solution sets with `UNION`. On the other hand, `FILTER(?x != ?y)` clauses could also be preferrable over a complicated query in terms of readability and conciseness, esp. if you are generating the queries dynamically. – kba Feb 07 '16 at 21:47
  • 1
    I don't want to flag as a duplicate just yet, but is this answered by [Using SPARQL to locate a subject with multiple occurrences of same property](http://stackoverflow.com/questions/18919742/using-sparql-to-locate-a-subject-with-multiple-occurrences-of-same-property)? I'm not sure what else an answer to this would add beyond that one. – Joshua Taylor Feb 08 '16 at 01:49
  • 2
    Note that your query *can* be more concise, as `?p ^:worksAt ?x, ?y . filter (?x != ?y)` (or with `filter (str(?x) < str(?y))`, as AndyS notes). – Joshua Taylor Feb 08 '16 at 15:34
  • It's worth noting that you haven't presented a sample _ontology,_ but a sampling of _instance data._ An [ontology](http://dbpedia.org/resource/Ontology_(information_science)) is a vocabulary, the rough RDF equivalent of an SQL schema. The triples you've provided, [instance data](http://dbpedia.org/resource/Instance_data), are the rough equivalent of data in SQL-style tables. – TallTed Feb 08 '16 at 19:17

0 Answers0