如何使用Jena打印rdfs标签

时间:2017-11-16 14:39:18

标签: jena owl ontology rdfs

您好我为相关的药物和疾病创建了一个新的本体论;现在我查询它恢复与某种疾病相关的药物名称。 我的代码是:

public class Main {

public static void main(String[] args) {

    org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);
    FileManager.get().addLocatorClassLoader(Main.class.getClassLoader());
    Model model = FileManager.get().loadModel("Drugs_Diseases.owl");
    String strQuery = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "+
                       "PREFIX des: <http://www.entrez.com/> "+
                       "SELECT DISTINCT ?subject ?object "
                       + "WHERE {   "
                       + "?subject des:isDrugOfDisease ?object .  "
                       + "?object rdfs:label ?label . "
                       + "FILTER regex(str(?label), \"pain\") }";

    Query query = QueryFactory.create(strQuery);
    QueryExecution execQuery = QueryExecutionFactory.create(query, model);
    try{
        ResultSet results = execQuery.execSelect();

        while(results.hasNext()){
            QuerySolution sol = results.nextSolution();
            RDFNode node = sol.get("subject");
            String stringPrint = node.asNode().toString();
            System.out.println(stringPrint);
        }
    } finally {
        execQuery.close();

}}
}

此查询的结果是:

http://www.entrez.com/DAP000017
http://www.entrez.com/DAP000021

但我的意图是:

Diazepam 
Dextropropoxyphene
在OWL中我有:

 <owl:Class rdf:about="http://www.entrez.com/DAP000021">
    <entrez:isDrugOfDisease>
      <owl:Class rdf:about="http://orpha.net/ORDO/Orphanet_#DIS_ID_75"/>
    </entrez:isDrugOfDisease>
    <entrez:id>DAP000021</entrez:id>
    <rdfs:label>Diazepam</rdfs:label>
  </owl:Class>

1 个答案:

答案 0 :(得分:1)

SPARQL只返回您选择的内容,因此,您必须在SPARQL查询中选择标签:

SELECT DISTINCT ?drug ?disease ?drugLabel WHERE
 ?drug des:isDrugOfDisease ?disease .
 ?drug rdfs:label ?drugLabel .
 ?disease rdfs:label ?label . 
 FILTER regex(str(?label), \"pain\") 
}

在代码中,从解决方案对象中获取标签:

while(results.hasNext()){
        QuerySolution sol = results.nextSolution();
        RDFNode node = sol.get("drug");
        String stringPrint = node.asNode().toString();
        System.out.println(stringPrint);
        // label
        String label = sol.getLiteral("drugLabel").getLexicalForm();
        System.out.println(label);
}

注意,我更改了变量名称。通常,如果对变量使用有意义的名称,则更容易阅读和理解查询。