2016-06-14 67 views
0

我想使用Java在DBPedia上進行查詢。以下是我的代碼,它不會返回正確的結果。我想從[http://dbpedia.org/page/Ibuprofen頁面和標籤名稱中獲取摘要部分。但它只返回http://dbpedia.org/resource/Ibuprofen 11次。如果可能,你能告訴我哪裏錯了嗎?這是我的代碼:使用Java針對DBPedia的SPARQL查詢

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); 
    } 
} 
+1

如果你想要得到的抽象,那麼你當然要選擇變量'abstract'查詢。你必須在這個變量上調用'get',即'get(「abstract」)'或者'getLiteral(「abstract」)''。看起來你從某處複製了代碼?我在問,因爲我想知道你沒有看到自己的問題。 – AKSW

+0

請注意,資源的URI是「http:// dbpedia.org/resource/Ibuprofen」的「資源」,而不是「頁面」。在Web瀏覽器中,您會自動重定向到「頁面」版本,但「資源」版本是實際的資源。 –

+0

是的代碼實際上是從另一個來源,只有查詢是我的 – developer

回答

4

您有多個結果,因爲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); 
    } 
+1

好的答案。另外 - 正如@JoshuaTaylor總是說的那樣 - 建議使用SPARQL的'LANGMATCHES'功能。 – AKSW

+0

@aksw感謝您的支持。:) –

+0

是的,我明白我的錯誤。謝謝你的幫助! – developer