Query DBpedia with Sparql using VALUES

2019-09-21 21:47发布

问题:

When I run this code in java I am getting error, I think the error occurred because of "String values". I am not sure about adding it but I got this idea from my previous question's answer which I asked in this site Query DBpedia to get abstract for different inputs

    public static void DbpediaResultSparql() { 
    String values = "New York";
    String service = "http://dbpedia.org/sparql";

    String sparqlQueryString2 = "PREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>"+
           "PREFIX  dbpedia-owl: <http://dbpedia.org/ontology/>"+
           "PREFIX  dbpedia: <http://dbpedia.org/resource/>"+

               "SELECT DISTINCT  ?abstract"+
               "WHERE"+
                 "{ _:b0 rdfs:label ?name ."+
                   "_:b0 dbpedia-owl:abstract ?abstract"+
                   "FILTER langMatches(lang(?abstract), 'en')"+
                  "?name { " + values +" @en }"+
                "}" ;                 

    Query query = QueryFactory.create(sparqlQueryString2);
    ARQ.getContext().setTrue(ARQ.useSAX);
    // Executing SPARQL Query and pointing to the DBpedia SPARQL Endpoint
    QueryExecution qexec = QueryExecutionFactory.sparqlService(
            "http://DBpedia.org/sparql", query);
    // Retrieving the SPARQL Query results
    ResultSet results = qexec.execSelect();
    // Iterating over the SPARQL Query results
    while (results.hasNext()) {
        QuerySolution soln = results.nextSolution();
        // Printing DBpedia entries' abstract.
        System.out.println(soln.get("?abstract"));
    }
    qexec.close();
 }

回答1:

You're not going to get useful answers with code like

"SELECT DISTINCT  ?abstract"+ "WHERE"

"_:b0 dbpedia-owl:abstract ?abstract"+ "FILTER langMatches(lang(?abstract), 'en')"

because it turns into

SELECT DISTINCT ?abstractWHERE

_:b0 dbpedia-owl:abstract ?abstractFILTER

and you don't want variables named ?abstractWHERE or ?abstractFILTER.

This doesn't make any sense either:

String values = "New York";
"?name { " + values +" @en }"

You'd end up with

?name { New York@en }

I expect that what you wanted was

values ?name { "New York"@en }

I'd suggest you take a look into ParameterizedSparqlStrings, and be sure to put terminating newlines, or at least whitespace, in your code. If you had just printed out the query, you could drop it into sparql.org's query validator and you'd have seen the problem right away.

You can write the query like this:

select distinct ?abstract where {
  values ?name { "New York"@en }
  [ rdfs:label ?name ;
    dbpedia-owl:abstract ?abstract ]
  filter langMatches(lang(?abstract),'en')
}

SPARQL Results

If you only have the one value for the ?name and you're not selecting that variable, you can just write it in the query:

select distinct ?abstract where {
  [ rdfs:label "New York"@en ;
    dbpedia-owl:abstract ?abstract ]
  filter langMatches(lang(?abstract),'en')
}