SPARQL查询:如何将ex:e到ex:a的路径合并为单列输出?
SPARQL查询:合并SKOS路径标签为单列结果
现有Turtle数据
@prefix skos: <http://www.w3.org/2004/02/skos/core#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix ex: <http://example.org/> . @prefix ex-sample: <http://example.org/sample/> . ex:a rdf:type skos:Concept . ex:a rdf:prefLabel "a" . ex:b rdf:type skos:Concept . ex:b rdf:prefLabel "b" . ex:c rdf:type skos:Concept . ex:c rdf:prefLabel "c" . ex:d rdf:type skos:Concept . ex:d rdf:prefLabel "d" . ex:e rdf:type ex-sample:sample . ex:e dct:subject ex:d . ex:e dct:subject ex:c .
查询需求
需要编写SPARQL查询,返回一列结果,展示从ex:e到ex:a的所有完整路径,每行用逗号分隔节点标签,期望输出:
row1: d,c,b,a row2: c,b,a
已尝试的问题查询
之前的查询能识别所有路径节点,但返回多行单个标签,无法合并为单列路径:
?target rdf:type ex:sample . ?target skos:prefLabel ?targetTitle . ?target dct:subject ?dctsubject . ?dctsubject skos:broader* ?furtherPath . ?furtherPath skos:prefLabel ?furtherPathLabel . }
前置补充
原Turtle数据缺失SKOS层级关联,需先添加以下三元组才能形成完整路径:
ex:d skos:broader ex:c . ex:c skos:broader ex:b . ex:b skos:broader ex:a .
解决方案SPARQL查询
使用GROUP_CONCAT函数将同一路径下的标签拼接为字符串,同时通过深度计算保证路径顺序:
PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ex: <http://example.org/> PREFIX ex-sample: <http://example.org/sample/> PREFIX dct: <http://purl.org/dc/terms/> SELECT (GROUP_CONCAT(?label; SEPARATOR=","; ORDER BY ?depth) AS ?path) WHERE { # 定位样本ex:e的所有主题节点作为路径起点 ex:e dct:subject ?startNode . # 遍历从起点到ex:a的所有层级节点 ?startNode skos:broader* ?node . ?node skos:prefLabel ?label . # 计算节点在路径中的深度,确保拼接顺序是起点→a BIND(COUNT(?intermediate) AS ?depth) WHERE { ?startNode skos:broader+ ?intermediate . ?intermediate skos:broader* ?node . } # 限定路径终点必须是ex:a FILTER(?node = ex:a) } # 按起点分组,每个起点对应一条完整路径 GROUP BY ?startNode
关键说明
skos:broader*匹配0或更多层级的向上关联,确保遍历从起点到ex:a的完整路径GROUP_CONCAT按深度顺序拼接同一起点下的所有节点标签,用逗号分隔成单列- 子查询计算节点深度,保证路径顺序从最具体的节点(d/c)到最宽泛的节点(a)
内容的提问来源于stack exchange,提问作者rose
相关产品推荐
相关产品推荐

