简体   繁体   English

Apache Jena中的SPARQL查询

[英]SPARQL query in Apache Jena

I want to write a query similar to this -- 我想写一个与此类似的查询-

select ?s ?p ?o where {?s ?p ?o. ?s rdf:subClassOf + mySpecificSubjectValue +}

Is there any existing way to do this? 有没有现成的方法可以做到这一点? Or Do I have to do it manually by checking all subjects. 还是我必须通过检查所有主题来手动完成。 And also I don't want to use regex in query cause regex create some problems for example: base:hotel and base:hotelName 而且我也不想在查询中使用正则表达式,导致正则表达式产生一些问题,例如:base:hotel和base:hotelName

Jena has a set of classes useful to build a query instance. 耶拿(Jena)具有一组可用于构建查询实例的类。 Here is an example that builds a query like yours: 这是一个构建像您这样的查询的示例:

String yourclassuri =  "base:hotel" ;
    //Intialize the select statatment
    Query select = new Query();

    //set prefixes
    select.setPrefix("rdf","rdfurl");
    select.setPrefix("base","yourbaseurl");

    select.setQuerySelectType();
    select.addResultVar("s");
    select.addResultVar("p");
    select.addResultVar("o");

    final ElementPathBlock elementPathBlock = new ElementPathBlock();

    //create the first pattern in the where
    final Node s = NodeFactory.createVariable("s");
    final Node p = NodeFactory.createVariable("p");
    final Node o = NodeFactory.createVariable("o");
    elementPathBlock.addTriple(new Triple(s,p,o));

    //create the last pattern
    final Node subclass = NodeFactory.createURI("rdf:subClassOf");
    final Node rdfclass = NodeFactory.createURI(yourclassuri);
    elementPathBlock.addTriple(new Triple(s,subclass,rdfclass));

    select.setQueryPattern(elementPathBlock);

    //serialize the query in a string
    String query = select.serialize();

    //output select ?s ?p ?o where {?s ?p ?o. ?s rdf:subClassOf base:hotel}

Sources: Jena javadoc 资料来源: 耶拿javadoc

Notice that you can use a ParametrizedSparqlString but it seems ineffective when you want to inject prefixed names (like base:name ). 请注意,您可以使用ParametrizedSparqlString,但是当您要插入前缀名称(例如base:name )时,它似乎无效。 The Javadoc also warns about possible SPARQL inject problems: Javadoc还警告可能的SPARQL注入问题:

SPARQL Injection Notes SPARQL注射说明

While this class was in part designed to prevent SPARQL injection it is by no means foolproof because it works purely at the textual level. 尽管此类的部分目的是为了防止SPARQL注入,但它绝不是万无一失的,因为它仅在文本级别起作用。 The current version of the code addresses some possible attack vectors that the developers have identified but we do not claim to be sufficiently devious to have thought of and prevented every possible attack vector. 当前版本的代码解决了开发人员已经确定的一些可能的攻击媒介,但我们并没有声称自己足够狡猾以至于无法考虑并阻止所有可能的攻击媒介。

I suspect that query building is a bit more safer against this kind of attacks. 我怀疑查询构建对于这种攻击更为安全。 Also here it is an other aswer about the limits of ParameterizedSparqlString. 另外这是关于ParameterizedSparqlString的限制的另一种说法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM