如何将类表达式(从限制unionOf)转换为字符串?

时间:2019-06-25 17:18:41

标签: sparql jena protege

SPARQL查询返回的结果受allValuesFromunionOf的限制。我需要concat这些值,但是,当我使用bindstr函数时,结果为空白。

我尝试了bindstrgroup_concat函数,但是所有这些都没有成功。 Group_concat返回一个空白节点。

SELECT DISTINCT ?source  ?is_succeeded_by
WHERE {
    ?source rdfs:subClassOf ?restriction . 
    ?restriction owl:onProperty j.0:isSucceededBy . 
    ?restriction owl:allValuesFrom  ?is_succeeded_by .
    FILTER (REGEX(STR(?source), 'gatw-Invoice_match'))
}

Protegé中SPARQL查询的结果:

Result of SPARQL query in Protegé

1 个答案:

答案 0 :(得分:1)

您几乎无法在耶拿(Jena)中以编程方式获得“ xxx或yyy”之类的字符串, 由于它是曼彻斯特语法,一种OWL-API本机格式,因此Jena不支持。 任何类表达式实际上都是b节点,在原始RDF中没有像“或”这样的内置符号。

要将任何匿名类表达式表示为字符串,可以使用ONT-API, 这是一个基于耶拿的OWL-API,因此,SPARQL和Manchester语法均受支持。

这是一个基于披萨本体的示例:

// use pizza, since no example data provided in the question:
IRI pizza = IRI.create("https://raw.githubusercontent.com/avicomp/ont-api/master/src/test/resources/ontapi/pizza.ttl");
// get OWLOntologyManager instance from ONT-API
OntologyManager manager = OntManagers.createONT();
// as extended Jena model:
OntGraphModel model = manager.loadOntology(pizza).asGraphModel();

// prepare query that looks like the original, but for pizza
String txt = "SELECT DISTINCT ?source ?is_succeeded_by\n" +
        "WHERE {\n" +
        "    ?source rdfs:subClassOf ?restriction . \n" +
        "    ?restriction owl:onProperty :hasTopping . \n" +
        "    ?restriction owl:allValuesFrom  ?is_succeeded_by .\n" +
        "    FILTER (REGEX(STR(?source), 'Am'))\n" +
        "}";
Query q = new Query();
q.setPrefixMapping(model);
q = QueryFactory.parse(q, txt, null, Syntax.defaultQuerySyntax);

// from owlapi-parsers package:
OWLObjectRenderer renderer = new ManchesterOWLSyntaxOWLObjectRendererImpl();
// from ont-api (although it is a part of internal API, it is public):
InternalObjectFactory iof = new NoCacheObjectFactory(manager.getOWLDataFactory());

// exec SPARQL query:
try (QueryExecution exec = QueryExecutionFactory.create(q, model)) {
    ResultSet res = exec.execSelect();
    while (res.hasNext()) {
        QuerySolution qs = res.next();
        List<Resource> vars = Iter.asStream(qs.varNames()).map(qs::getResource).collect(Collectors.toList());
        if (vars.size() != 2)
            throw new IllegalStateException("For the specified query and valid OWL must not happen");
        // Resource (Jena) -> OntCE (ONT-API) -> ONTObject (ONT-API) -> OWLClassExpression (OWL-API)
        OWLClassExpression ex  = iof.get(vars.get(1).inModel(model).as(OntCE.class)).getObject();
        // format: 'class local name' ||| 'superclass string in ManSyn'
        System.out.println(vars.get(0).getLocalName() + " ||| " + renderer.render(ex));
    }
}

输出:

American ||| MozzarellaTopping or PeperoniSausageTopping or TomatoTopping
AmericanHot ||| HotGreenPepperTopping or JalapenoPepperTopping or MozzarellaTopping or PeperoniSausageTopping or TomatoTopping

使用的环境:ont-api:1.4.1,owl-api:5.1.11,jena-arq:3.12.0