[英]Reversing a string in SPARQL
Is it possible to reverse a string in SPARQL, so, eg, "abc" becomes "cba". 是否可以在SPARQL中反转字符串,例如,“ abc”变为“ cba”。 Alternatively, is it possible to sort based on strings in reverse.
可替代地,可以基于相反的字符串排序。
I am particularly interested in a solution that would work on Wikidata Query Service . 我对在Wikidata Query Service上可以使用的解决方案特别感兴趣。
Well, you asked whether it's possible , not whether it's practical ... 好吧,您问是否有可能 ,而不是是否可行 ...
SELECT ?s (group_concat(?letter; separator='') AS ?r) {
BIND ("abcdefghijkl" AS ?s)
VALUES ?d1 { 0 1 2 3 4 5 6 7 8 9 }
VALUES ?d2 { 0 1 2 3 4 5 6 7 8 9 }
VALUES ?d3 { 0 1 2 3 4 5 6 7 8 9 }
BIND (100 * ?d3 + 10 * ?d2 + ?d1 + 1 AS ?i)
BIND (SUBSTR(?s, ?i, 1) AS ?letter)
}
GROUP BY ?s
The approach is similar to that in Finn's response, but it works for strings up to a length of 1000 characters. 该方法与Finn的响应中的方法类似,但适用于长度不超过1000个字符的字符串。 This would be used as a subquery within a larger query.
这将用作较大查询中的子查询。 Aggregates like
group_concat
don't guarantee a particular order, so this query relies on the implementation-dependent ordering used by Blazegraph, and may jumble up the string on a different implementation. 诸如
group_concat
聚合不保证特定顺序,因此此查询依赖于Blazegraph使用的与实现相关的顺序,并且可能使字符串在其他实现上混乱。
If the use case is sorting by the last characters of a string in reverse order, then this could be tweaked so that it's guaranteed to include the last n characters of the string. 如果用例按相反的顺序按字符串的最后一个字符排序,则可以对其进行调整,以确保包括字符串的最后n个字符。
There is no "reverse string" function in SPARQL 1.1 . SPARQL 1.1中没有“反向字符串”功能。
There is no ORDER BY
modifier that delivers the ordering you're looking for. 没有提供要查找的
ORDER BY
修饰符 。
Many if not most programming and scripting languages do have "reverse string" and "sort" methods, so I'd suggest investigating whether your (unnamed) development environment has such. 许多(如果不是大多数的话)编程和脚本语言确实具有“反向字符串”和“排序”方法,因此我建议调查您(未命名)的开发环境是否具有这种方法。
This pathological implementation apparently works (up to a certain string length, here 12) in Blazegraph/Wikidata Query Service: 这种病理实现显然在Blazegraph / Wikidata查询服务中有效(最多达到特定的字符串长度,此处为12):
SELECT ?s ?r {
BIND("abcdefghijkl" AS ?s)
BIND(CONCAT(SUBSTR(?s, 12, 1), SUBSTR(?s, 11, 1), SUBSTR(?s, 10, 1),
SUBSTR(?s, 9, 1), SUBSTR(?s, 8, 1), SUBSTR(?s, 7, 1),
SUBSTR(?s, 6, 1), SUBSTR(?s, 5, 1), SUBSTR(?s, 4, 1),
SUBSTR(?s, 3, 1), SUBSTR(?s, 2, 1), SUBSTR(?s, 1, 1)) AS ?r)
}
Here's a query targeting Virtuoso that provides the desired solution, courtesy of a sub-query. 这是一个针对Virtuoso的查询,通过子查询提供了所需的解决方案。
SELECT ?str (GROUP_CONCAT(?letter; separator="") AS ?reverse)
WHERE {
{
SELECT ?str ?charAt
WHERE {
VALUES ?str { "abcdefghijk" }
VALUES ?d1 { 0 1 2 3 4 5 6 7 8 9 10 }
BIND(STRLEN(?str) - ?d1 AS ?charAt)
FILTER(?charAt > 0)
}
}
BIND(SUBSTR(?str,?charAt,1) AS ?letter)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.