我正在使用 Apache Jena 的 Java API 来存储和检索文档以及其中的单词。为此,我决定设置以下数据结构:
_dataset = TDBFactory.createDataset("./database");
_dataset.begin(ReadWrite.WRITE);
Model model = _dataset.getDefaultModel();
Resource document= model.createResource("http://name.space/Source/DocumentA");
document.addProperty(RDF.value, "Document A");
Resource word = model.createResource("http://name.space/Word/aword");
word.addProperty(RDF.value, "aword");
Resource resource = model.createResource();
resource.addProperty(RDF.value, word);
resource.addProperty(RSS.items, "5");
document.addProperty(RDF.type, resource);
_dataset.commit();
_dataset.end();
上面的代码示例表示一个由五 (5) 个单词(“aword”)组成的文档(“文档 A”)。文档中单词的出现次数被计数并存储为属性。单词也可以出现在其他文档中,因此与特定文档中的特定单词相关的出现计数通过空白节点链接在一起。 (我不完全确定这种结构是否有意义,因为我对这种存储信息的方式相当陌生,所以请随时提供更好的解决方案!)
我的主要问题是:如何获得所有不同单词的列表以及它们在所有文档中出现的总和?
最佳答案
在我看来,您的数据模型有点非常规。通过您的代码,您最终会得到如下所示的数据(采用 Turtle 表示法),并且以非常规方式使用 rdf:type 和 rdf:value:
:doc rdf:value "document a" ;
rdf:type :resource .
:resource rdf:value :word ;
:items 5 .
:word rdf:value "aword" .
这很不寻常,因为通常您不会获得有关资源类型属性的如此复杂的信息。但从 SPARQL 的角度来看,rdf:type 和 rdf:value 与其他属性一样,您仍然可以通过简单的查询来检索您要查找的信息。它看起来或多或少像这样(尽管您需要定义一些前缀等):
select ?word (sum(?n) as ?nn) where {
?document rdf:type ?type .
?type rdf:value/rdf:value ?word ;
:items ?n .
}
group by ?word
该查询将为每个单词生成一个结果,每个结果都是与该单词关联的 :items 属性的所有值的总和。 Stack Overflow 上有很多问题都有使用 Jena 运行 SPARQL 查询的示例。例如,(我通过 Google 找到的第一个):Query Jena TDB store .
关于java - 在 Apache Jena 中聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28030307/