【问题标题】:Jena: Property Paths when building queries programmaticallyJena:以编程方式构建查询时的属性路径
【发布时间】:2014-11-05 19:54:01
【问题描述】:

我正在尝试使用 Jena 提供的 API 以编程方式构建 SPARQL 查询。 为了简单起见,我想要这样的东西:

SELECT *
WHERE {
  ?typ rdfs:subClassOf+ myns:SomeType .
}

问题是rdfs:subClassOf+,它使用了属性路径。我尝试像这样构建查询:

    query = new Query();
    query.setQuerySelectType();
    query.addResultVar("typ");
    ElementTriplesBlock triplePattern = new ElementTriplesBlock();
    Node typ = NodeFactory.createVariable("typ");
    Node sometype = ...; // Assume OK

    triplePattern.addTriple(new Triple(typ, 
            ResourceFactory.createProperty(RDFS.subClassOf.getURI() + "+").asNode(),
            sometype));
    query.setQueryPattern(triplePattern);

如果我没有属性路径,即在 SPARQL 中它只说 rdfs:subClassOf,我可以选择:

    triplePattern.addTriple(new Triple(typ, 
            RDFS.subClassOf.asNode(),
            sometype));

哪个有效。但是我无法在 URI 中指定路径修饰符来构建属性,因为我得到了:

Caused by: com.hp.hpl.jena.shared.InvalidPropertyURIException: http://www.w3.org/2000/01/rdf-schema#subClassOf+
  at com.hp.hpl.jena.rdf.model.impl.PropertyImpl.checkLocalName(PropertyImpl.java:67)
  at com.hp.hpl.jena.rdf.model.impl.PropertyImpl.<init>(PropertyImpl.java:56)
  at com.hp.hpl.jena.rdf.model.ResourceFactory$Impl.createProperty(ResourceFactory.java:296)
  at com.hp.hpl.jena.rdf.model.ResourceFactory.createProperty(ResourceFactory.java:144)
  ... (test class)

所以问题是,如何通过 Java API 在 Jena 中指定这样的查询。我知道我可以使用属性路径语法从字符串中进行查询,但不能在以编程方式构建查询时。

【问题讨论】:

    标签: java rdf sparql jena


    【解决方案1】:

    我想我是在多修修补补之后找到的。

    首先,如果 WHERE {...} 部分将使用任何路径,则必须使用 ElementPathBlock,因为尝试将路径添加到 ElementTripleBlock 会引发异常。然后,不是添加 Triple,而是添加 TriplePath。代码:

        ElementPathBlock triplePattern = new ElementPathBlock();
        Node typ = NodeFactory.createVariable("typ");
        Node sometype = ...; // Assume OK
        // This represents rdfs:subClassOf+
        Path pathSubClassOfPlus = PathFactory.pathOneOrMore1(
            PathFactory.pathLink(RDFS.subClassOf.asNode())
        );
        // This represents the SPARQL: ?typ rdfs:subClassOf+ sometype .
        TriplePath subClassOfPlus = new TriplePath(typ, pathSubClassOfPlus, sometype)
        triplePattern.addTriplePath(subClassOfPlus);
        // ... One can also add regular Triple instances afterwards
        query.setQueryPattern(triplePattern);
    

    【讨论】:

    • 如果这对你有用,别忘了接受答案。
    • 这让我非常头疼。谢谢!!
    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多