尝试使用Jena的java api创建Sparql查询

时间:2012-11-06 16:56:27

标签: java sparql jena

我使用Apache Jena库在Java中创建了一个Ontology模型,然后我进入了比萨本体。 我正在尝试进行sparql查询,但表打印是空白的,虽然我的查询有正常的答案。 难道我做错了什么...? 这是代码:

OntModel model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_MICRO_RULE_INF);
String inputFileName="pizza.owl";
InputStream in = FileManager.get().open( inputFileName );
if (in == null) {
    throw new IllegalArgumentException(
         "File: " + inputFileName + " not found");
}
model.read(in, null);

String queryString =
        "prefix pizza: <www.co-ode.org/ontologies/pizza/pizza.owl#Pizza> "+        
        "prefix rdfs: <" + RDFS.getURI() + "> "           +
        "prefix owl: <" + OWL.getURI() + "> "             +
        "select ?pizza where {?pizza a owl:Class ; "      +
        "rdfs:subClassOf ?restriction. "                  +
        "?restriction owl:onProperty pizza:hasTopping ;"  +
        "owl:someValuesFrom pizza:PeperoniSausageTopping" +
        "}";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
com.hp.hpl.jena.query.ResultSet results =  qe.execSelect();

ResultSetFormatter.out(System.out, results, query);
qe.close();

1 个答案:

答案 0 :(得分:3)

你的前缀声明是错误的。您不小心包含了Pizza类的名称,也没有使用http协议前缀。更正了,它应该是:

"prefix pizza: <http://www.co-ode.org/ontologies/pizza/pizza.owl#> "+

前缀在RDF和SPARQL中工作的方式是用prefix:替换前缀定义的内容,结果字符串必须完全匹配资源的URI正试图匹配。它必须是完全匹配 - 即使字母的差异很大。

顺便说一句,您还可以通过FileManager

简化加载本体
OntModel model = ModelFactory.createOntologyModel( 
                                  OntModelSpec.OWL_MEM_MICRO_RULE_INF);
FileManager.get().readModel( model, "pizza.owl" );