SPARQL 简介

关于 SPARQL 的详细内容,请参考 http://www.w3.org/TR/rdf-sparql-query/#syntaxTerms 。

 

SPARQL 是一种RDF 查询语言。其全称为 SPARQL Protocol and RDF Query Language,是一种递归定义。

本文将用几个简单的例子对 SPARQL 进行简要说明。

一个简单的例子

数据如下:

<http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> "SPARQL Tutorial" .
  



 

查询语句如下:

SELECT ?title
WHERE
{
  <http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> ?title .
}    


那么所得到的查询结果为:

title

"SPARQL Tutorial"

第2个例子

数据如下:

@prefix foaf:  <http://xmlns.com/foaf/0.1/> .

_:a  foaf:name   "Johnny Lee Outlaw" .
_:a  foaf:mbox   <mailto:jlow@example.com> .
_:b  foaf:name   "Peter Goodguy" .
_:b  foaf:mbox   <mailto:peter@example.org> .
_:c  foaf:mbox   <mailto:carol@example.org> .


查询语句如下:

PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE
  { ?x foaf:name ?name .
    ?x foaf:mbox ?mbox }


查询结果为:

namembox
"Johnny Lee Outlaw"<mailto:jlow@example.com>
"Peter Goodguy"<mailto:peter@example.org>

第3个例子

数据如下:

@prefix org:    <http://example.com/ns#> .

_:a  org:employeeName   "Alice" .
_:a  org:employeeId     12345 .

_:b  org:employeeName   "Bob" .
_:b  org:employeeId     67890 .


查询使用了另一种查询方式 "Construct" ,之前我们使用的都是 "Select" 方式,并返回一个 RDF 图。查询语句如下:

PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
PREFIX org:    <http://example.com/ns#>

CONSTRUCT { ?x foaf:name ?name }
WHERE  { ?x org:employeeName ?name }


所得结果为:

@prefix org: <http://example.com/ns#> .
      
_:x foaf:name "Alice" .
_:y foaf:name "Bob" .


可以序列化为 RDF/XML格式:

<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:foaf="http://xmlns.com/foaf/0.1/"
    >
  <rdf:Description>
    <foaf:name>Alice</foaf:name>
  </rdf:Description>
  <rdf:Description>
    <foaf:name>Bob</foaf:name>
  </rdf:Description>
</rdf:RDF>


其他

Order by 的例子 ---- 按emp 降序排列

PREFIX     :    <http://example.org/ns#>
PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
PREFIX xsd:     <http://www.w3.org/2001/XMLSchema#>

SELECT ?name
WHERE { ?x foaf:name ?name ; :empId ?emp }
ORDER BY DESC(?emp)


如果是曾旭则 ASC 可以省略

Instinct 的例子 ---- 去除重复

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT DISTINCT ?name WHERE { ?x foaf:name ?name }


Offset 与 Limit 的例子 ---- 取出 从10(OFFSET)个之后的5(LIMIT)个数据

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>

SELECT  ?name
WHERE   { ?x foaf:name ?name }
ORDER BY ?name
LIMIT   5
OFFSET  10


关于 SPARQL 的更多内容,请参考 http://www.w3.org/TR/rdf-sparql-query/#syntaxTerms 。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值