【问题标题】:SPARQL Query Printing Literal in JenaJena 中的 SPARQL 查询打印文字
【发布时间】:2017-02-13 20:50:53
【问题描述】:

我正在尝试为此猫头鹰模型编写查询。

:Sensor rdf:type owl:Class;
:hasId rdf:type owl:DatatypeProperty,
                rdfs:domain :Sensor;
                rdfs:range xsd:int.
:MedicalCountainer rdf:type :owlNamedIndividual,
                            :Sensor;
                            :hasId "55"^^xsd:int .

我想使用 sensor-id 来检索传感器名称。 这是我在 Java 中的查询,但我不知道为什么它不打印任何内容。我知道我的问题是正确的,因为我会在 Protégé 中得到答案。

String file = "C:/users/src/data.ttl";
Model model = FileManager.get().loadModel(file);
String queryString = "PREFIX : <http://semanticweb.org/sensor#>" +
                     "SELECT ?sensor" +
                     "WHERE {?sensor :hasId \"55"\^^<xsd:int>}";
Query query = QueryFactory.create(queryString);
try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
          ResultSet result = qexec.execSelect();
          for ( ; result.hasNext(); ) {
                  QuerySolution soln = result.nextSolution();
                  Resource r = soln.getResource("sensor");
                  System.out.println(r);
          }
}

【问题讨论】:

  • 您正在查询变量“sensor”。然后,您检索“Valr”的文字。您是否尝试过检索“传感器”的文字?即soln.getLiteral("sensor");
  • 实际上,我注意到我的代码存在一个重大问题。循环不运行,这意味着“结果”为空。我更新了我的代码,我不知道是什么问题。

标签: java sparql jena semantic-web ontology


【解决方案1】:

SPARQL 查询中文字的使用是错误的。要么你使用

  1. 文字的前缀URI,即"55"^^xsd:int,或
  2. 您将完整的 URI 放入尖括号中,即"55"\^^&lt;http://www.w3.org/2001/XMLSchema#int&gt;

但不是两者的混合。

并且总是倾向于将所有 PREFIX 声明添加到 SPARQL 查询的开头,以确保正确解析所有 SPARQL 服务:

PREFIX : <http://semanticweb.org/sensor#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT ?sensor
WHERE {
  ?sensor :hasId "55"^^xsd:int
}

【讨论】:

  • 我正在使用乌龟,我知道你提到的第一种方式是正确的,但我得到了这个错误:org.apache.jena.query.QueryParseException: Line 2, column 63: Unresolved prefixed name: xsd:int 但是,你提到的第二种方式是有效的,但我只是打印空值。你知道吗,为什么?
  • 因为您必须在 SPARQL 查询的开头声明所有前缀。有时 API/工具确实提供了一些预定义的前缀,但为了使其在任何地方都能正常工作,最佳做法是添加查询中使用的所有前缀:PREFIX xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; 我也将此添加到我的答案中以供将来参考。
  • 非常感谢。你知道我为什么会空吗?在 protege 中,我得到了答案,但在这里我得到了这个查询的空值。
  • 因为您选择的唯一变量称为 ?sensor 而不是 Varl。此外,它是一种资源而不是文字,因此尚不清楚为什么您调用 getLiteral("Varl) 而不是 getResource("sensor")
  • 非常感谢,这是我第一次使用 JENA。这就是为什么我很困惑,除了stackoverflow我没有任何帮助。我更新了我的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
相关资源
最近更新 更多