一. 基础概念
SPARQL即SPARQL Protocol and RDF Query Language的递归缩写,被专门设计用来访问和操作RDF数据,是语义网的核心技术之一。W3C的RDF数据存取小组(RDF Data Access Working Group, RDAWG)对其进行了标准化。2008年1月15日,SPARQL正式成为一项W3C推荐标准。
二. 查询
1. 简单查询
SELECT ?title
WHERE
{
<http://example.org/book/book1> <DCMI: DCMI Metadata Terms> ?title .
}
2. 多字段匹配
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE
{
?x foaf:name ?name .
?x foaf:mbox ?mbox
}
3. 数据属性匹配
# 字符类型
SELECT ?v WHERE { ?v ?p "cat" }
# 数字类型
SELECT ?v WHERE { ?v ?p 42 }
# 指定类型
SELECT ?v WHERE { ?v ?p "abc"^^<http://example.org/datatype#specialDatatype> }
4.条件过滤
模糊匹配(通过regex
函数可以进行字符串正则匹配,通过FILTER
进行过滤)
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?title
WHERE {
?x dc:title ?title FILTER regex(?title, "web", "i" )
}
数字比较
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX ns: <http://example.org/ns#>
SELECT ?title ?price
WHERE {
?x ns:price ?price .FILTER (?price < 30.5)
?x dc:title ?title .
}
5. OPTIONAL(可选值)
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE {
?x foaf:name ?name .OPTIONAL
{
?x foaf:mbox ?mbox
}
}
6. 组合查询(OPTIONAL + FILTER)
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX ns: <http://example.org/ns#>
SELECT ?title ?price
WHERE {
?x dc:title ?title .OPTIONAL
{
?x ns:price ?price . FILTER (?price < 30)
}
}
7. UNION
PREFIX dc10: <http://purl.org/dc/elements/1.0/>
PREFIX dc11: <http://purl.org/dc/elements/1.1/>
SELECT ?title
WHERE {
{
?book dc10:title ?title
}
UNION
{
?book dc11:title ?title
}
}
8. 排序
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name
WHERE {
?x foaf:name ?name ; :empId ?emp
}
ORDER BY ?name DESC(?emp)
9. 去重
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT DISTINCT ?name
WHERE {
?x foaf:name ?name
}
10. 判断是否存在
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
ASK {
?x foaf:name "Alice" ;
foaf:mbox <mailto:alice@work.example>
}