使用Jena ARQ API 查询RDF图

来源:互联网 发布:mac版下载视频软件 编辑:程序博客网 时间:2024/04/27 16:17

摘译自Jena ARQ文档

应用程序API位于主程序包com.hp.hpl.jena.queryJena提供了多个package,其中包含与系统相关的不同部分(执行引擎,解析器,以及测试单元等等),大多数应用只需要使用主程序包。应用程序只有当希望编程构建查询或者修改查询引擎的行为时才会直接使用其他的包

主要的类

· Query – 表示查询的类。其中包含了所有查询相关的细节。该类的对象一般是通过调用QueryFactory下的方法进行创建的,这些方法提供了对于不同解析器的访问

· QueryExecution代表了查询的一次执行过程。

· QueryExecutionFactory获得QueryExecution实例的类。

· DatasetFactory用于构建数据集,包括构建一个数据源DataSource (可更新的Dataset)

· SELECT查询相关的类:

· QuerySolution - A single solution to the query

· ResultSet - All the QuerySolutions. An iterator.

· ResultSetFormatter - turn a ResultSet into various forms; into text, into an RDF graph (Model, in Jena terminology) or as plain XML

SELECT queries

    构建SELECT查询的基本步骤如下所示。一个查询是使用QueryFactory从某个字符串创建的。querymodel(或者待查询的RDF数据集)之后被传递给QueryExecutionFactory用于产生查询执行的一个实例。结果Result在一个循环里处理,最后关闭查询执行(query execution)。

  import com.hp.hpl.jena.query.* ;


 String queryString = "prefix vCard:<http://www.w3.org/2001/vcard-rdf/3.0#>"
                      +"select ?x ?fname " 
                      +"from <file:/myeclipsworkspace/arq-test/pack1/rdf1.rdf>"
                      +"where {?x vCard:FN ?fname}";

 Query query = QueryFactory.create(queryString) ;

 QueryExecution qexec = QueryExecutionFactory.create(query, model) ;

 try {

    ResultSet results = qexec.execSelect() ;

    for ( ; results.hasNext() ; )

    {

      QuerySolution soln = results.nextSolution() ;

      RDFNode name = soln.get("fname") ;       // Get a result variable by name.

      Resource x = soln.getResource("x") ; // Get a result variable - must be a resource

      //Literal l = soln.getLiteral("VarL") ;   // Get a result variable - must be a literal

    System.out.println(name.toString()+" "+x.toString());
     }

 } finally { qexec.close() ; }

  输出结果是:

    Matt Jones http://somewhere/MattJones/
    Sarah Jones http://somewhere/SarahJones/
    Becky Smith http://somewhere/RebeccaSmith/
    John Smith http://somewhere/JohnSmith/

 

    显然这种格式不够好。后面会讲到如何使用ResultSetFormatter对结果进行格式化操作。

    注意一点,在结束的时候对查询执行进行close操作是必要的,因为与持久存储相连接的系统资源需要被释放掉。创建一个查询以及创建一个查询执行过程的步骤在某些情况下可以减少为一个步骤。

  import com.hp.hpl.jena.query.* ;


  String queryString = " .... " ;
  QueryExecution qexec = QueryExecutionFactory.create(queryString, model) ;
  try {
   ResultSet results = qexec.execSelect() ;
    . . .
  } finally { qexec.close() ; }

格式化结果集

    除了可以通过循环的形式处理结果集的每一行,我们也可以调用ResultSetFormatter的操作。

    例如,把结果表示成简单的文本形式(这种方法貌似存在问题,ARQ 2.60版本中的ResultSetFormatter没有定义任何构造函数)

    ResultSetFormatter fmt = new ResultSetFormatter(results, query) ;
    fmt.printAll(System.out) ;

或者简单的写作

 ResultSetFormatter.out(System.out, results, query) ;

输出结果如下:

 ----------------------------------------------------

 | x                                | fname         |

 ====================================================

 | <http://somewhere/MattJones/>    | "Matt Jones"  |

 | <http://somewhere/SarahJones/>   | "Sarah Jones" |

 | <http://somewhere/RebeccaSmith/> | "Becky Smith" |

 | <http://somewhere/JohnSmith/>    | "John Smith"  |

----------------------------------------------------

Example: Processing results

The results are objects from the Jena RDF API and API calls, which do not modify the model, can be mixed with query results processing:

  for ( ; results.hasNext() ; )
  {
      // Access variables: soln.get("x") ;
      RDFNode n = soln.get("x") ; // "x" is a variable in the query
      // If you need to test the thing returned
      if ( n.isLiteral() )
          ((Literal)n).getLexicalForm() ;
      if ( n.isResource() )
      {
         Resource r = (Resource)n ;
          if ( ! r.isAnon() )
          {
            ... r.getURI() ...
          }
      }
  }

Updates to the model must be carried out after the query execution has finished. Typically, this involves collecting results of interest in a local datastructure and looping over that structure after the query execution has finished and been closed.

CONSTRUCT Queries

CONSTRUCT 查询返回一个RDF图,类似的,查询执行过程在使用完毕的时候应该对其close

Query query = QueryFactory.create(queryString) ;
QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
Model resultModel = qexec.execConstruct() ;
qexec.close() ;

DESCRIBE Queries

DESCRIBE 查询返回一个RDF图。DESCRIBE操作具有不同的handler,可以由应用程序加载。

Query query = QueryFactory.create(queryString) ;
QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
Model resultModel = qexec.execDescribe() ;
qexec.close() ;

ASK Queries

操作Query.execAsk()返回一个boolean值,指示查询模式是否与图或者数据集匹配。

Query query = QueryFactory.create(queryString) ;
QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
boolean result = qexec.execAsk() ;
qexec.close() ;

Formatting XML results

The ResultSetFormatter class has methods to write out the SPARQL Query Results XML Format. See ResultSetFormatter.outputAsXML method.

Datasets

以上的所有例子都是针对单一model的查询。而SPARQL查询可以作用于一个数据集,它可能包含一个缺省图以及0个或者多个具名图(named graph)。可以使用DatasetFactory构建数据集。

String dftGraphURI = "file:default-graph.ttl" ;
List namedGraphURIs = new ArrayList() ;
namedGraphURIs.add("file:named-1.ttl") ;
namedGraphURIs.add("file:named-2.ttl") ;

Query query = QueryFactory.create(queryString) ;

Dataset dataset = DatsetFactory.create(dftGraphURI, namedGraphURIs) ;
QueryExecution qExec = QueryExecutionFactory.create(query, dataset) ;
try { ... }
finally { qExec.close() ; }

也可以使用已经存在的modelDataSource是可以更新的数据集。

DataSource dataSource = DatsetFactory.create() ;
dataSource.setDefaultModel(model) ;
dataSource.addNamedModel("http://example/named-1", modelX) ;
dataSource.addNamedModel("http://example/named-2", modelY) ;
QueryExecution qExec = QueryExecutionFactory.create(query, dataSource) ;