本文主要展現下如何使用apache jena對RDF文檔進行SPARQL查詢html
資源描述框架(Resource Description Framework),一種用於描述Web資源的標記語言。使用XML語法和RDF Schema(RDFS)來將元數據描述成爲數據模型。apache
SPARQL(SPARQL Protocol and RDF Query Language),是爲RDF開發的一種查詢語言和數據獲取協議,它是爲W3C所開發的RDF數據模型所定義,可是能夠用於任何能夠用RDF來表示的信息資源。框架
Jena是一個Java工具箱用於開發基於RDF與OWL語義(semantic)Web應用程序。它提供了一個RDF API;ARP,一個RDF解析器;SPARQL,W3C RDF查詢語言;一個OWL API;和基於規則的RDFS與OWL接口。ARQ是Jena中的SPARQL查詢引擎。maven
<dependency> <groupId>org.apache.jena</groupId> <artifactId>jena-core</artifactId> <version>3.7.0</version> </dependency> <dependency> <groupId>org.apache.jena</groupId> <artifactId>jena-arq</artifactId> <version>3.7.0</version> </dependency>
<?xml version="1.0"?> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cd="http://www.example.com/cd#"> <rdf:Description rdf:about="http://www.example.com/cd/EmpireBurlesque"> <cd:artist>Bob Dylan</cd:artist> <cd:country>USA</cd:country> <cd:company>Columbia</cd:company> <cd:price>10.90</cd:price> <cd:year>1985</cd:year> </rdf:Description> <rdf:Description rdf:about="http://www.example.com/cd/Hideyourheart"> <cd:artist>Bonnie Tyler</cd:artist> <cd:country>UK</cd:country> <cd:company>CBS Records</cd:company> <cd:price>9.90</cd:price> <cd:year>1988</cd:year> </rdf:Description> </rdf:RDF>
@Test public void testJenaQuery(){ Model model = ModelFactory.createDefaultModel(); model.read(this.getClass().getClassLoader().getResourceAsStream("demo.rdf"), null); String queryString = "PREFIX cd: <http://www.example.com/cd#> \n " + "SELECT ?name where { ?item cd:artist ?name }"; Query query = QueryFactory.create(queryString); QueryExecution qe = QueryExecutionFactory.create(query, model); ResultSet results = qe.execSelect(); ResultSetFormatter.out(System.out, results, query); }
輸出ide
------------------ | name | ================== | "Bonnie Tyler" | | "Bob Dylan" | ------------------
SPARQL是針對RDF的查詢語言,相似SQL,可是又不盡相同,略有點學習成本,有待深刻研究下。工具