傳統 Web 依賴關聯式資料庫與 SQL,語義 Web 採用 RDF (Resource Description Framework) 描述資料,SPARQL (SPARQL Protocol and RDF Query Language) 進行查詢與操作。RDF 以「主詞-謂詞-受詞」三元組表示知識,保留資料語意,支援動態結構與跨資料源連結。
-- SQL
SELECT realname, dob, location
FROM UserTable WHERE realname = 'John Smith';
-- SPARQL
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
PREFIX rdf: <https://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?uri ?name ?dob ?location
FROM <https://www.example.org/graph>
WHERE {
?uri rdf:type foaf:Person ;
foaf:name 'John Smith' ;
foaf:birthday ?dob ;
foaf:location ?location .
}
SPARQL 查詢模式匹配 RDF 圖結構,雖然較冗長,但天然支援分散式資料整合與動態結構。
-- SQL
INSERT INTO UserTable (realname, dob, location)
VALUES ('John Smith', '1985-01-01', 'Bristol, UK');
-- SPARQL
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
PREFIX rdf: <https://www.w3.org/1999/02/22-rdf-syntax-ns#>
INSERT DATA {
GRAPH <https://www.example.com/graph> {
<https://www.example.org/graph/johnsmith#me>
rdf:type foaf:Person ;
foaf:name 'John Smith' ;
foaf:birthday '1985-01-01T00:00:00'^^xsd:dateTime ;
foaf:location 'Bristol, UK' .
}
}
<?php
require 'vendor/autoload.php'; // 使用 EasyRdf 或 ARC2 函式庫
class SemanticCRUD {
private $sparqlEndpoint;
public function __construct($endpoint) {
$this->sparqlEndpoint = $endpoint;
}
private function query($sparql) {
$ch = curl_init($this->sparqlEndpoint);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => 'query=' . urlencode($sparql),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Accept: application/sparql-results+json']
]);
return json_decode(curl_exec($ch), true);
}
public function read($name) {
$sparql = "PREFIX foaf: <https://xmlns.com/foaf/0.1/>
SELECT ?uri ?dob ?location WHERE {
?uri a foaf:Person ;
foaf:name '$name' ;
foaf:birthday ?dob ;
foaf:location ?location .
}";
return $this->query($sparql);
}
public function create($uri, $name, $dob, $location) {
$sparql = "PREFIX foaf: <https://xmlns.com/foaf/0.1/>
INSERT DATA {
GRAPH <https://example.org/graph> {
<$uri> a foaf:Person ;
foaf:name '$name' ;
foaf:birthday '$dob' ;
foaf:location '$location' .
}
}";
// 需支援 SPARQL/Update 的端點
return $this->update($sparql);
}
private function update($sparql) {
// 類似 query 但發送至 update 端點
}
}