简体   繁体   中英

Replace variables within a SPARQL query in Jena

I need to replace some variables(indx, placx, datx, tempx) within a SPARQL query and for the same I am using following code:

ParameterizedSparqlString ps = new ParameterizedSparqlString();
ps.setCommandText("INSERT DATA" + 
            "{" + 
             ":indx :locatedIn :placx ;" + ":onDate datx ;" + ":measures tempx ." +              
            "}");
ps.setIri(":","http://www.example.com/tempsensor#");
ps.setLiteral("indx",ind);
ps.setLiteral("placx",plac);
ps.setLiteral("datx",dat);
ps.setLiteral("tempx",temp);

System.out.println(ps.toString());

On running, it simply prints out:
INSERT DATA{:indx :locatedIn :placx ;:onDate datx ;:measures tempx .}
How can I insert the values successfully within query?

UPDATE #1
Changes introduced in code are as:

  ps.setBaseUri("http://www.example.com/tempsensor#"); ps.setCommandText("PREFIX : <http://www.example.com/tempsensor#>\\n"+ "INSERT DATA\\n" + "{\\n" + " ?indx :locatedIn ?placx ;" + ":onDate ?datx ;" + " :measures ?tempx .\\n" + "}"); ps.setIri("?indx", ps.getBaseUri()+ind); ps.setIri("placx",ps.getBaseUri()+plac); ps.setLiteral("datx",dat); ps.setLiteral("tempx",temp); System.out.println(ps.toString()); 

I am getting output as:

PREFIX : <http://www.example.com/tempsensor#>
INSERT DATA
{
 <#ind1>  :locatedIn <#Delhi> ;:onDate "2015-02-01" ; :measures 13 .
}

I don't know where I am doing wrong. I need an output like:

 PREFIX : <http://www.example.com/tempsensor#>
    INSERT DATA
    {
     :ind1  :locatedIn :Delhi ; :onDate 2015-02-01 ; :measures 13 .
    }

ie, ind1 should be without quotes,angle brackets,and # and date should be without quotes. locatedIn is an objecttypeProperty and onDate and measures are Datatype properties. Actually, I need to read data from CSV row by row and insert into an ontology. For this I want to write the script where I will read row of CSV and convert the same in SPARQL string. In the next step, I will make a update SPARQL query with this string created.

You need to use variables , not constants in the query. Eg, your string should originally be:

insert data { ?indx :locatedIn ?placx ... }

Then you can use the various setXXX functions. However, note that there's more than just setLiteral. You shouldn't use setLiteral to set the value of ?indx here, because literals cannot be the subjects of triples in RDF. For that case, you'd want to use setIri. See the docs for ParameterizedSparqlString for the full list.

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