如何用SPARQL查询按指定顺序返回<fruits>包含的资源?
SPARQL 查询实现按指定顺序返回包含的资源
问题背景
已知三元组存储中有如下数据:
<kiwi> rico:isOrWasIncludedIn <fruits> . <apple> rico:isOrWasIncludedIn <fruits> . <plum> rico:isOrWasIncludedIn <fruits> . <orange> rico:isOrWasIncludedIn <fruits> . <banana> rico:isOrWasIncludedIn <fruits> . <orange> rico:followsOrFollowed <plum> . <banana> rico:followsOrFollowed <kiwi> . <apple> rico:followsOrFollowed <orange> . <plum> rico:followsOrFollowed <banana> .
需要按 <kiwi> → <banana> → <plum> → <orange> → <apple> 的顺序返回<fruits>下的所有资源。
解法:递归查询构建顺序
可利用SPARQL的递归查询(WITH RECURSIVE)遍历顺序关系、记录节点位置,最终按位置排序输出:
WITH RECURSIVE ordered_fruits AS ( # 定位顺序起点:<fruits>中未被任何节点follow的资源(即kiwi) SELECT ?fruit AS ?item, 1 AS ?position WHERE { ?fruit rico:isOrWasIncludedIn <fruits> . FILTER NOT EXISTS { ?other rico:followsOrFollowed ?fruit . } } UNION # 递归遍历后续节点,递增位置序号 SELECT ?next_fruit AS ?item, ?position + 1 AS ?position WHERE { ordered_fruits ?item . ?next_fruit rico:followsOrFollowed ?item . ?next_fruit rico:isOrWasIncludedIn <fruits> . } ) # 按位置序号升序输出 SELECT ?item FROM ordered_fruits ORDER BY ?position
逻辑说明
- 起点定位:通过
FILTER NOT EXISTS筛选出没有被其他资源followsOrFollowed的水果,也就是顺序的起始节点<kiwi>,并标记位置为1。 - 递归遍历:以起始节点为基础,依次匹配后续的
followsOrFollowed关联节点,每次将位置序号加1,构建完整的顺序链。 - 排序输出:最后按位置序号升序排列,即可得到符合要求的资源顺序。
内容的提问来源于stack exchange,提问作者Isabi
相关产品推荐
相关产品推荐

