我们使用下面的数据集作为例子:
@prefix ab: <http://learningsparql.com/ns/addressbook#> .
@prefix d: <http://learningsparql.com/ns/data#> .
# Richard information
d:i0432 ab:firstName "Richard" .
d:i0432 ab:lastName "Mutt" .
d:i0432 ab:homeTel "(229) 276-5135" .
d:i0432 ab:nick "Dick" .
d:i0432 ab:email "richard49@hotmail.com" .
# Cindy information
d:i9771 ab:firstName "Cindy" .
d:i9771 ab:lastName "Marshall" .
d:i9771 ab:homeTel "(245) 646-5488" .
d:i9771 ab:email "cindym@gmail.com" .
# Craig infomation
d:i8301 ab:firstName "Craig" .
d:i8301 ab:lastName "Ellis" .
d:i8301 ab:workTel "(245) 315-5486" .
d:i8301 ab:email "craigellis@yahoo.com" .
d:i8301 ab:email "c.ellis@usairwaysgroup.com" .
FILTER
关键字用于过滤掉不符合条件的数据。
以下语句:
PREFIX ab: <http://learningsparql.com/ns/addressbook#>
SELECT ?first ?last
WHERE {
?s ab:firstName ?first ;
ab:lastName ?last .
OPTIONAL { ?s ab:workTel ?workNum . }
FILTER (!bound(?workNum))
}
bound()
function returnstrue
if the variable passed as a parameter is bound(that is, if it’s been assigned a value) andfalse
otherwise.
查询结果:
-------------------------
| first | last |
==========================
| "Cindy" | "Marshall" |
| "Richard" | "Mutt" |
--------------------------
该查询语句得到的是拥有 ab:fistName
和 ab:lastName
但又没有 ab:workTel
的人。
在SPARQL 1.1中,又引入 FILTER NOT EXISTS
和 MINUS
语句,借助他们,上面的查询语句可以改写成下面这样的语句:
PREFIX ab: <http://learningsparql.com/ns/addressbook#>
SELECT ?first ?last
WHERE {
?s ab:firstName ?first ;
ab:lastName ?last .
FILTER NOT EXISTS { ?s ab:workTel ?workNum }
}
PREFIX ab: <http://learningsparql.com/ns/addressbook#>
SELECT ?first ?last
WHERE {
?s ab:firstName ?first ;
ab:lastName ?last .
MINUS { ?s ab:workTel ?workNum }
}
在一些情况下,FILTER NOT EXISTS
与 MINUS
所得到的结果也会有些区别,需要根据情况和语义来使用。