替换Jena中SPARQL查询中的变量

时间:2015-02-20 05:11:57

标签: java sparql rdf jena

我需要在SPARQL查询中替换一些变量(indx,placx,datx,tempx),并且我使用以下代码:

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());

在跑步时,它只是打印出来:
                 INSERT DATA {:indx:locatedIn:placx;:onDate datx;:测量tempx。}
如何在查询中成功插入值?

更新#1
代码中引入的更改如下:

                    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());  

我的输出为:

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

我不知道我在哪里做错了。我需要一个输出,如:

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

即,ind1应该没有引号,尖括号,而#和date应该没有引号。 locatedIn是一个objecttypeProperty和onDate,度量是Datatype属性。实际上,我需要逐行读取CSV中的数据并插入到本体中。为此,我想编写脚本,我将读取CSV行并在SPARQL字符串中转换相同的行。在下一步中,我将使用此字符串创建更新SPARQL查询。

1 个答案:

答案 0 :(得分:1)

您需要使用变量,而不是查询中的常量。例如,您的字符串最初应为:

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

然后您可以使用各种setXXX功能。但请注意,不仅仅是setLiteral。你不应该使用setLiteral来设置?indx的值,因为文字不能是RDF中三元组的主题。对于这种情况,您需要使用setIri。有关完整列表,请参阅ParameterizedSparqlString的文档。