【问题标题】:How to list the objects of rdf statements?如何列出 rdf 语句的对象?
【发布时间】:2013-06-28 11:42:55
【问题描述】:

我想通过任何 RDF 谓词选择与给定主题资源相关的资源列表。

例如,如果我的模型中的资源是ex:aliceex:bobex:peterex:Ben,并且我的模型包含:

ex:alice ex:meet ex:bob.  
ex:alice foaf:knows ex:Peter.  
ex:alice ex:talk :ben.  

我将如何编写一个方法来返回资源列表,这些资源是给定特定资源作为主题的任何三元组的对象?例如,如果我给:

resourcesRelatedToResource( alice );

我希望有一个包含 Bob、Peter 和 Ben 的列表。

【问题讨论】:

  • 您能否先回到您提出的类似问题?尤其是stackoverflow.com/questions/15557778/… 非常相似(我提供了答案)。
  • 是的,但正如我上面提到的,仅通过使用 resourceName 对象列表必须返回......而不是通过资源和属性。
  • 您似乎在另一个问题stackoverflow.com/questions/15935783/… 中尝试了一些东西,但有一条评论要求提供更多详细信息。请先回答这个问题,而不是提出新问题。
  • 举个例子,我几乎可以弄清楚 OP 想要什么,所以我编辑了问题以说出我 认为 他/她在问什么,然后提供了我的回答!

标签: rdf jena ontology


【解决方案1】:

使用 Jena API,如果您调用 listStatements 时将作为通配符的主语、宾语或谓词的参数为空。因此,您只想传递主题 Alice,并收集匹配三元组的对象(如果它们是对象)。 Jena 有一个捷径:给定资源r,调用:

r.listProperties()

相当于:

r.getModel().listStatements( r, null, (RDFNode) null )

所以:

public void test() {
    Model m = /*... your model here ...*/;

    // get a reference to the Alice resource
    Resource alice = m.getResource( NS + "alice" );

    Set<Resource> result = resourcesRelatedToResource( alice );
}

/** Return a set of the resources related to the given input 
  * resource via any predicate */
protected Set<Resource> resourcesRelatedToResource( Resource r ) {
    // we don't care about duplicates, so use a Set
    Set<Resource> objs = new HashSet<Resource>();

    // iterate over the triples with alice as subject
    for (StmtIterator i = r.listProperties(); i.hasNext(); ) {
        RDFNode obj = i.nextStatement().getObject();

        if (obj.isResource()) {
            objs.add( obj.asResource() );
        }
    }

    return objs;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 2012-08-10
    相关资源
    最近更新 更多