如何在 Java 中构建 SPARQL 查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7250189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to build SPARQL queries in java?
提问by Martin Schlagnitweit
Is there a library, which is able to build SPARQL queries programmatically like the CriteriaBuilder
in JPA or to build the queries like with a PreparedStatement
for SQL?
是否有一个库,它能够像CriteriaBuilder
在 JPA 中那样以编程方式构建 SPARQL 查询,或者像使用PreparedStatement
for SQL那样构建查询?
Similar (for SQL): Cleanest way to build an SQL string in Java
类似(对于 SQL):在 Java 中构建 SQL 字符串的最简洁方法
采纳答案by user205512
You can build queries programmatically in Jena using two methods: syntax or algebra. There's an introductionin the jena wiki.
您可以使用两种方法在 Jena 中以编程方式构建查询:语法或代数。耶拿维基有介绍。
Using the algebra you'd do something like:
使用代数你会做这样的事情:
Op op;
BasicPattern pat = new BasicPattern(); // Make a pattern
pat.add(pattern); // Add our pattern match
op = new OpBGP(pat); // Make a BGP from this pattern
op = OpFilter.filter(e, op); // Filter that pattern with our expression
op = new OpProject(op, Arrays.asList(Var.alloc("s"))); // Reduce to just ?s
Query q = OpAsQuery.asQuery(op); // Convert to a query
q.setQuerySelectType(); // Make is a select query
(taken from the wiki page)
(取自维基页面)
It's not CriteriaBuilder
(nor was it intended to be), but is some of the way there. You OpJoin
rather than AND, OpUnion
when you want to OR, etc. The pain points are expressions in my experience: you probably want to parse them from a string.
它不是CriteriaBuilder
(也不是有意为之),而是某种方式。你OpJoin
而不是 AND,OpUnion
当你想要 OR 时,等等。痛点是我的经验中的表达式:你可能想从一个字符串中解析它们。
回答by RobV
The recent versions of Jena have added a StringBuilder
style API for building query/update strings and parameterizing them if desired.
Jena 的最新版本添加了一个StringBuilder
样式 API,用于构建查询/更新字符串并根据需要对其进行参数化。
This class is called ParameterizedSparqlString
, here's an example of using it to create a query:
此类名为ParameterizedSparqlString
,这是使用它创建查询的示例:
ParameterizedSparqlString queryStr = new ParameterizedSparqlString();
queryStr.setNSPrefix("sw", "http://skunkworks.example.com/redacted#");
queryStr.append("SELECT ?a ?b ?c ?d");
queryStr.append("{");
queryStr.append(" ?rawHit sw:key");
queryStr.appendNode(someKey);
queryStr.append(".");
queryStr.append(" ?rawHit sw:a ?a .");
queryStr.append(" ?rawHit sw:b ?b .");
queryStr.append(" ?rawHit sw:c ?c . ");
queryStr.append(" ?rawHit sw:d ?d .");
queryStr.append("} ORDER BY DESC(d)");
Query q = queryStr.asQuery();
Disclaimer- I'm the developer who contributed this functionality to Jena
免责声明- 我是向 Jena 贡献此功能的开发人员
See What's the best way to parametize SPARQL queries?for more discussion on doing this across various APIs.
请参阅参数化 SPARQL 查询的最佳方法是什么?有关跨各种 API 执行此操作的更多讨论。
回答by Heiner Reinhardt
I implemented SPARQL Java- a kind of DSL for writing SPARQL queries in Java.
我实现了SPARQL Java——一种用 Java 编写 SPARQL 查询的 DSL。
It solves the problem with IDE's auto formatting of concatenated SPARQL query strings and things like that.
它解决了 IDE 对连接的 SPARQL 查询字符串和类似内容的自动格式化的问题。
As for example:
例如:
String shortQuery = Q.prefix("books", "http://example.org/books#")
.select("?book ?authorName", new where() {
{
$("?book books:author ?author");
$("?author books:authorName ?authorName");
}
}).get();
回答by Jan Zyka
I recently started to use Sesame query builder. It looks promising except it doesn't provide much documentation and I struggled to find examples. Here is simple sample which may help you to get started:
我最近开始使用芝麻查询构建器。它看起来很有希望,只是它没有提供太多文档,而且我很难找到示例。这是一个简单的示例,可以帮助您入门:
ParsedTupleQuery query = QueryBuilderFactory
.select("pubProperty", "pubPropertyValue")
.group()
.atom(cmResource(resourceId), LinkPublicationsTransformation.REFERENCE_URI, "pubUri")
.atom("pubUri", "pubProperty", "pubPropertyValue")
.filter(isLiteral("pubPropertyValue"))
.closeGroup()
.query();
Just note that isLiteral
and cmResource
are my own little static helper classes. isLiteral
stands for new IsLiteral(new Var("..."))
for example where the latter one create URI with my heavily used prefix.
请注意,isLiteral
和cmResource
是我自己的小型静态助手类。isLiteral
代表new IsLiteral(new Var("..."))
例如其中后者创建URI与我频繁使用的前缀。
You might be then also interested in SPARQLQueryRenderer
which can turn ParsedQuery
into String
which may be convenient for further usage.
然后您可能还对SPARQLQueryRenderer
哪些可以ParsedQuery
变成String
哪些可以方便进一步使用感兴趣。
If you end up using String(Builder)
approach what I discourage you to do have at least a look on RenderUtils
from sesame-queryrendered
which has all the convenient methods to add <
>
around URIs, escape special characters etc.
如果你最终使用String(Builder)
的方法是什么我不鼓励你这样做至少有一看RenderUtils
,从sesame-queryrendered
拥有所有方便的方法来添加<
>
各地的URI,转义特殊字符等。
回答by Jeen Broekstra
The Eclipse RDF4J framework(the successor of Sesame) offers a Repository API which is somewhat similar to JDBC - it allows you to create a prepared Query object and inject variable bindings before executing it:
在Eclipse中RDF4J框架(芝麻的继任者)提供了一个库API,它有点类似JDBC -它允许你创建一个准备好的查询对象,并注入变量绑定执行前:
String query = "SELECT * WHERE {?X ?P ?Y }";
TupleQuery preparedQuery = conn.prepareQuery(QuerLanguage.SPARQL, query);
preparedQuery.setBinding("X", someValue);
...
TupleQueryResult result = preparedQuery.evaluate();
In addition, RDF4J has a SparqlBuilder(originally known as spanqit) - a Java DSL for SPARQL which allows you to create SPARQL queries in code like this:
此外,RDF4J 有一个SparqlBuilder(最初称为 spanqit)——一种用于 SPARQL 的 Java DSL,它允许您在如下代码中创建 SPARQL 查询:
query.prefix(foaf).select(name)
.where(x.has(foaf.iri("name"), name))
.orderBy(name)
.limit(5)
.offset(10);
回答by anqit
I have just released a beta project to do just this, called Spanqit.
我刚刚发布了一个测试项目来做这个,叫做Spanqit。
I strove for readability and an intuitive interface, for example, here is some example Spanqit syntax for creating a query:
我努力提高可读性和直观的界面,例如,以下是一些用于创建查询的 Spanqit 语法示例:
query.prefix(foaf).select(name)
.where(x.has(foaf.iri("name"), name))
.orderBy(name)
.limit(5)
.offset(10);
Check it out, and feel free to comment and suggest improvements!
检查一下,并随时发表评论并提出改进建议!
回答by cWarren
Jena provides a QueryBuilder in the Extras package.
Jena 在 Extras 包中提供了一个 QueryBuilder。
https://jena.apache.org/documentation/extras/querybuilder/index.html
https://jena.apache.org/documentation/extras/querybuilder/index.html
It does what you want.
它做你想做的。
回答by Guido
You can use the Jena Semantic Framework(SPARQL documentation). Also take a look at this related question. Sadly, its syntax is closer to a SQL PreparedStatement than to the JPA.
您可以使用Jena 语义框架(SPARQL 文档)。也看看这个相关的问题。遗憾的是,它的语法更接近于 SQL PreparedStatement 而不是 JPA。