列出包含字符串的域

时间:2011-08-07 14:19:04

标签: ontology jena

首先,我是Jena的新手。我创建了一个本体,我有4个类,程序,买家,供应商和邮政编码。我有以下属性:

  1. 程序hasBuyer买家
  2. 程序hasSupplier Supplier
  3. 供应商拥有ZipCode邮政编码
  4. 买方拥有ZipCode邮政编码
  5. 我想知道的是Jena中返回包含字符串“3333”的所有域名的最佳方法。

    例如:

    • 程序1的买方1有邮政编码333,供应商1有邮政编码333,供应商2有邮政编码334。
    • 程序2的买方2有邮政编码331,供应商2有邮政编码334,供应商2有邮政编码335.
    • 程序3的买方3有邮政编码333,供应商1有邮政编码333,供应商3有邮政编码335.

    结果必须是:

    • 程序 - 程序1和程序3
    • 买方 - 买方1和买方3
    • 供应商 - 供应商1

    NG

1 个答案:

答案 0 :(得分:1)

首先,你不能使用“供应商2与邮政编码334”,然后“供应商2与邮政编码335”,因为它是同一个人,你会看到“供应商2与邮政编码334和邮政编码334“在申请中两次。

有一些变体的实现。

使用普通的Jena API:

Model model; // your model
Resource supplierClass = model.getResource(YOUR_NS + "Supplier");
Resource buyerClass = model.getResource(YOUR_NS + "Buyer");
Resource procClass = model.getResource(YOUR_NS + "Procedure");
Property zipCodeProp = model.getProperty(YOUR_NS + "zipCode");
Property hasBuyerProp = model.getProperty(YOUR_NS + "hasBuyer");
Property hasSupplierProp = model.getProperty(YOUR_NS + "hasSupplier");
StmtIterator iter = 
        model.listStatements(new SimpleSelector(null, zipCodeProp, "333"));
while (iter.hasNext()) {
    Resource subject = iter.next().getSubject();
    if (!subject.hasProperty(RDF.type))
        continue;
    Resource subjectClass = subject.getPropertyResourceValue(RDF.type);
    SimpleSelector sel;
    if (subjectClass.equals(supplierClass))
        sel = new SimpleSelector(null, hasSupplierProp, subject);
    else if (subjectClass.equals(buyerClass))
        sel = new SimpleSelector(null, hasBuyerProp, subject);
    else
        continue;
    StmtIterator innerIter = model.listStatements(sel);
    while (innerIter.hasNext()) {
        Resource proc = innerIter.next().getSubject();
        if (!proc.hasProperty(RDF.type) || 
                !proc.getPropertyResourceValue(RDF.type).equals(procClass))
            continue;
        // now you can retrieve linked entities from this procedure
    }
}

和SPARQL查询:

PREFIX yourns: <YOUR_NS>
SELECT DISTINCT ?proc
{
    ?proc a yourns:Procedure;
          yourns:hasBuyer ?buyer;
          yourns:hasSupplier ?supplier.
    ?supplier zipCode ?supplierZip.
    ?buyer zipCode ?buyerZip.
    FILTER (?supplierZip = '333' || ?buyerZip = '333')
}

进一步使用ARQ:

Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
    QuerySolution qs = results.next();
Resource proc = qs.getResource("proc");
    // now again you can retrieve linked entities
}