[英]Adding age (integer literals) to Jena RDF triples, and querying on them with SPARQL
我正在嘗試學習使用Jena和RDF Triples的基礎知識。 由於也可以使用Oracle數據庫,因此按照其指南運行一些示例程序,例如Example7-18 SPARQL OPTIONAL Query 。 該示例按編寫的方式工作正常。 它允許匹配查詢,例如
where {?s <u:parentOf> ?o}
where {<u:John> <u:parentOf> <u:Mary>}
我要做的是給約翰,瑪麗和吉爾一個年齡,這樣我就可以按照SPARQL中的示例:作弊表 ,第10頁中的說明查詢和過濾年齡:
A . B . FILTER ( …expr… )
where {?s <u:parentOf> ?o . ?o <u:isAge> ?a . filter ( ?a < 20 ) }
使用當前的三元組代碼,我只能添加字符串/ URI節點,盡管我可以創建三元組,例如<u:John> <u:isAge> <u:35>
,但我無法進行過濾和與之進行比較該年齡的<運算符,所以它不是很有用。
我已經四處尋找了,我懷疑這樣做很簡單,但是很難找到代碼示例。
請注意,您需要一個像"35"^^xsd:int
或"35^^xsd:integer
這樣的對象,它們是文字,而不是<u:35>
它是(可能是格式錯誤的)URI)。在我看來,示例是,它以某種不尋常的方式進行工作,並且根據文檔,它使用了一些不推薦使用的方法,無論如何,您可以看到它使用Node類(工廠類)中的方法創建URI節點:
Node.createURI("u:John")
Node.createURI("u:parentOf")
Node.createURI("u:Mary")
Node類中有五個createLiteral方法,您可以使用createLiteral(String lex,RDFDatatype dtype)創建具有數據類型的文字。 不過,該方法已被棄用,您實際上應該使用NodeFactory中的方法之一 。
綜上所述,我不知道示例是否有理由使用圖接口創建三元組而不是模型接口。 您已經有了以下模型:
ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName);
如果使用模型接口,該任務將更容易完成,該接口具有諸如createTypedLiteral之類的方法,因此您只需調用createTypedLiteral(30)
並獲取合適的文字即可。 這是一個例子:
import java.math.BigInteger;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
public class CreateAndQueryExample {
/**
* @param args
*/
public static void main(String[] args) {
// You should be able to replace this with the Oracle model
// producing code.
Model model = ModelFactory.createDefaultModel();
Resource john = model.createResource( "urn:ex:John" );
Resource mary = model.createResource( "urn:ex:Mary" );
Property age = model.createProperty( "urn:ex:age" );
// Using Model.add method
model.add( john, age, model.createTypedLiteral( new BigInteger( "25" ))); // "25"^^xsd:integer
// model.add( john, age, model.createTypedLiteral( 25 )); // "25"^^xsd:int
// model.add( john, age, model.createTypedLiteral( 25l )); // "25"^^xsd:long
// Using the Resource.addProperty method
mary.addProperty( age, model.createTypedLiteral( new BigInteger( "35" )));
Query query = QueryFactory.create( "select * where { ?s <urn:ex:age> ?age . filter ( ?age < 30 ) }" );
QueryExecution exec = QueryExecutionFactory.create( query, model );
ResultSetFormatter.out( exec.execSelect() );
}
}
-----------------------
| s | age |
=======================
| <urn:ex:John> | 25 |
-----------------------
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.