2

我想使用 Java 查询 DBPedia。下面是我的代码,它没有返回正确的结果。我想从 [ http://dbpedia.org/page/Ibuprofen页面和标签名称中获取抽象部分。但它只返回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);
    }
}
4

1 回答 1

7

您有多个结果,因为 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);
    }
于 2016-06-14T07:06:32.987 回答