使用 Java 针对 DBPedia 的 SPARQL 查询

SPARQL query against DBPedia using Java

我想使用 Java 在 DBPedia 上查询。下面是我的代码,它没有 return corrrect result.I 想要从 [http://dbpedia.org/page/Ibuprofen page and label name. but it returns only http://dbpedia.org/resource/Ibuprofen 获得摘要部分 11 次。如果可能的话,你能告诉我错误在哪里吗?这是我的代码:

import org.apache.jena.query.ParameterizedSparqlString;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.ResultSet;
import org.apache.jena.query.ResultSetFormatter;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.ResourceFactory;

public class JavaDBPediaExample {

    public static void main(String[] args) {
        ParameterizedSparqlString qs = new ParameterizedSparqlString(""
                + "prefix rdfs:    <http://www.w3.org/2000/01/rdf-schema#>\n"
                + "PREFIX dbo:     <http://dbpedia.org/ontology/>"
                + "\n"
                + "select ?resource where {\n"
                + "  ?resource rdfs:label ?label.\n"
                + "  ?resource dbo:abstract ?abstract.\n"
                + "}");

        Literal ibuprofen = ResourceFactory.createLangLiteral("Ibuprofen", "en");
        qs.setParam("label", ibuprofen);

        QueryExecution exec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", qs.asQuery());

        ResultSet results = exec.execSelect();

        while (results.hasNext()) {

            System.out.println(results.next().get("resource"));
        }

        ResultSetFormatter.out(results);
    }
}

您有多个结果,因为 DBPedia 中有多种语言变体。找出您想要的语言并相应地更改下面的过滤器。您也可以在查询中包含标签模式,而不是通过编程方式进行。根据 ASKW 的评论,您还没有将抽象变量绑定到结果。

基本上您的代码应该如下所示:

public static void main(String[] args) {
        ParameterizedSparqlString qs = new ParameterizedSparqlString(""
                + "prefix rdfs:    <http://www.w3.org/2000/01/rdf-schema#>\n"
                + "PREFIX dbo:     <http://dbpedia.org/ontology/>"
                + "\n"
                + "select distinct ?resource ?abstract where {\n"
                + "  ?resource rdfs:label 'Ibuprofen'@en.\n"
                + "  ?resource dbo:abstract ?abstract.\n"
                + "  FILTER (lang(?abstract) = 'en')}");


        QueryExecution exec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", qs.asQuery());

        ResultSet results = exec.execSelect();

        while (results.hasNext()) {

            System.out.println(results.next().get("abstract").toString());
        }

        ResultSetFormatter.out(results);
    }