简体   繁体   中英

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

Jena has a set of classes useful to build a query instance. 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

Notice that you can use a ParametrizedSparqlString but it seems ineffective when you want to inject prefixed names (like base:name ). The Javadoc also warns about possible SPARQL inject problems:

SPARQL Injection Notes

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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