W3C home > Mailing lists > Public > public-sparql-dev@w3.org > April to June 2008

Expressing negation in SPARQL

From: Dau, Frithjof <frithjof.dau@sap.com>
Date: Thu, 22 May 2008 17:37:45 +0200
Message-ID: <EDFFA9D51148B34FAA0B828A82AAE70C7C0A8D@dewdfe1g.wdf.sap.corp>
To: <public-sparql-dev@w3.org>

Dear all,

Being a SPARQL-novice, and being interested in diagrammatic
query languages, I came to the question on how to express
negation within SPARQL. A toy example is a relation like

like    A  B  C  D  
A          X       
B       X  X
C       X  X  X  X
D

And I wanted to find a query which retrieves all pairs of
Person x,y where x does *not* like y. I scanned this list,
Did not find a solution, but some mails indicating that
Some sort of negation is not possible. Anyhow, I found
A solution, and simply write to this list to share this
With you, assuming that some might be interested.

The relation in turtle is:

@prefix : <http://example.org/> .
:A a :Person .
:B a :Person .
:C a :Person .
:D a :Person .
:A :like :B .
:B :like :A .
:B :like :B .
:C :like :A .
:C :like :B .
:C :like :C .
:C :like :D .

The following query yields the desired result:


PREFIX : <http://example.org/>
SELECT DISTINCT ?1 ?2  
FROM <http://www.dr-dau.net/sparql_example_1.ttl>
WHERE {
   ?1 a :Person .
   ?2 a :Person .
   OPTIONAL
   {
   ?3 :like ?4 .
   FILTER (?1 = ?3 && ?2 = ?4)
   }
   FILTER (!BOUND(?3) )
}
ORDER BY ?1 ?2


I ran the query on sparql.org, and it yields the pairs

A A
A C
A D
B C
B D
D A
D B
D C
D D

The idea behind this query can easily be extended to other forms of negations.
Hope that some of you find this helpful.

Regards
Frithjof



Frithjof Dau
Researcher
SAP Research CEC Dresden
SAP AG
Chemnitzer Straße 48
D-01187 Dresden, Germany
T +49 351 4811-6152
F +49 6227-78-51425
mailto:frithjof.dau@sap.com
www.sap.com

 
Received on Friday, 23 May 2008 02:21:25 GMT

This archive was generated by hypermail 2.2.0+W3C-0.50 : Friday, 23 May 2008 02:21:26 GMT