SPARQL查询结合DISTINCT与ORDER BY多变量返回空结果求助
SPARQL查询空结果及去重排序问题解决方案
核心问题定位
原查询存在2个基础错误,是导致执行结果不符合预期的核心原因:
- 缺失
dbo前缀声明:原查询中使用了dbo:命名空间,但未在开头声明对应的前缀地址,导致过滤条件strstarts(str(?s_type ), str(dbo:))无法正确执行 - 过滤逻辑重复且错误:末尾的过滤条件重复校验了
?s_type的命名空间,遗漏了对?o_type的命名空间校验,同时冗余的前缀声明也会增加解析异常概率
修复及实现方案
1. 基础错误修正
- 补全DBpedia的dbo前缀声明:
PREFIX dbo: <http://dbpedia.org/ontology/> - 删除重复的rdf、rdfs、owl前缀声明
- 将末尾重复的
s_type过滤条件修改为?o_type的命名空间校验
2. 去重+排序的正确实现
SPARQL语法中,去重关键字DISTINCT需要紧跟在SELECT之后,排序关键字ORDER BY需要放在WHERE子句结束之后,按?p升序排序直接写ORDER BY ?p即可,降序则用ORDER BY DESC(?p)
修复后的完整查询代码
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX dbo: <http://dbpedia.org/ontology/> SELECT DISTINCT ?s_type ?p ?o_type WHERE{ ?s ?p ?o. ?s rdf:type ?s_type. FILTER NOT EXISTS { ?s rdf:type ?type1 . ?type1 rdfs:subClassOf ?s_type. FILTER NOT EXISTS { ?type1 owl:equivalentClass ?s_type. } }. FILTER EXISTS { ?s_type rdfs:subClassOf ?superType1 . }. FILTER strstarts(str(?s_type), str(dbo:)). ?o rdf:type ?o_type. FILTER NOT EXISTS { ?o rdf:type ?type2 . ?type2 rdfs:subClassOf ?o_type. FILTER NOT EXISTS { ?type2 owl:equivalentClass ?o_type. } }. FILTER EXISTS { ?o_type rdfs:subClassOf ?superType2 . }. FILTER strstarts(str(?o_type), str(dbo:)). } ORDER BY ?p
内容的提问来源于stack exchange,提问作者Abdelghny Hamdy
相关产品推荐
相关产品推荐

