如何在Java/Kotlin的GraphDB插件中查询当前活动仓库?
GraphDB插件开发:执行SPARQL查询的问题
我正在使用GraphDB的Plugin API开发插件,需要从当前活动的GraphDB仓库中检索部分语句做后续处理,想要执行的SPARQL查询如下:
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> prefix proof: <http://www.ontotext.com/proof/> select ?rule ?s ?p ?o ?context where { values (?subject ?predicate ?object) {(<urn:Mary> <urn:hasChild> <urn:John>)} ?ctx proof:explain (?subject ?predicate ?object) . ?ctx proof:rule ?rule . ?ctx proof:subject ?s . ?ctx proof:predicate ?p . ?ctx proof:object ?o . ?ctx proof:context ?context . }
该查询需由proof plugin处理,只要查询格式正确且插件在目标仓库上运行即可自动生效。
RDF4J提供了向RepositoryConnection对象发送查询的示例代码:
Repository db = new SailRepository(new MemoryStore()); // Open a connection to the database try (RepositoryConnection conn = db.getConnection()) { String filename = "example-data-artists.ttl"; try (InputStream input = Example15SimpleSPARQLQuery.class.getResourceAsStream("/" + filename)) { // add the RDF data from the inputstream directly to our database conn.add(input, "", RDFFormat.TURTLE); } // We do a simple SPARQL SELECT-query that retrieves all resources of type `ex:Artist`, // and their first names. String queryString = "PREFIX ex: <http://example.org/> \n"; queryString += "PREFIX foaf: <" + FOAF.NAMESPACE + "> \n"; queryString += "SELECT ?s ?n \n"; queryString += "WHERE { \n"; queryString += " ?s a ex:Artist; \n"; queryString += " foaf:firstName ?n ."; queryString += "}"; TupleQuery query = conn.prepareTupleQuery(queryString); // A QueryResult is also an AutoCloseable resource, so make sure it gets closed when done. try (TupleQueryResult result = query.evaluate()) { // we just iterate over all solutions in the result... for (BindingSet solution : result) { // ... and print out the value of the variable binding for ?s and ?n System.out.println("?s = " + solution.getValue("s")); System.out.println("?n = " + solution.getValue("n")); } } } finally { // Before our program exits, make sure the database is properly shut down. db.shutDown(); }
目前遇到以下问题:
- 无法获取指向当前工作仓库的正确类型对象:插件API使用PluginConnection对象,但它不支持此类查询交互;虽然能列出localhost:7200的所有仓库,但无法区分当前活动仓库,且访问仓库需要知道用户自定义的ID/名称。
- 文档中基于配置文件的方案不可靠:无法确定其在GraphDB安装中的位置,在插件场景下不实用,且无法指明当前被查询的仓库。
- 考虑使用PluginConnection的getStatements()函数,但存在不足:无法实现上述复杂查询的逻辑,也无法处理如
?ctx proof:explain (?subject ?predicate ?object) .这类含RDF列表的语句。
内容的提问来源于stack exchange,提问作者Andrea Corradetti
相关产品推荐
相关产品推荐

