Java 语义网编程系列五: Jena+sparql实现语义数据查询

Sparql 是语义网的查询语言,是w3c推荐的一个标准,一下演示了之前设计的本体文件的查询,实现了"benz"车拥有者的姓名的查询。

 

/**



 * 语义数据查询



 * @param spaqrlString



 * @param queryModel



 * @param var



 */



     public void queryBySpaqrl( String spaqrlString , Model queryModel , String var )



             {



            Query query =         QueryFactory.create(spaqrlString);



            QueryExecution queryExecution = QueryExecutionFactory.create(query,queryModel);



            ResultSet resultSet = queryExecution.execSelect();



            while(resultSet.hasNext())



                    {



                            QuerySolution querySolution = resultSet.nextSolution();



                            RDFNode rdfNode = querySolution.get(var);



                            System.out.println(var +" is " + rdfNode.toString());



                    }



             }

 

Sparql 语句

@Test



public void testJenaSparql()



{



JenaModelSpaqrl  jenaModelSpaqrl = new JenaModelSpaqrl();



jenaModel= new JenaModel();



StringBuffer querystringBuffer = new StringBuffer();



querystringBuffer.append("PREFIX s1" + ": <" + defaultNameSpace + ">");



querystringBuffer.append(



"select ?name" +



" where { " +



"?car s1:hasBrand \"Benz\"."+



"?car s1:hasOwner ?person."+



"?person s1:hasName ?name}"



);



jenaModelSpaqrl.queryBySpaqrl(querystringBuffer.toString(), jenaModel.createOntologyModel(OntModelSpec.OWL_DL_MEM, pathFile) ,"?name");



}

最终结果

你可能感兴趣的:(java)