在 SPARQL 中,获取每个内容的前 n 项的查询确实很棘手,而且目前还没有很好的方法来做到这一点。它几乎总是归结为一些奇怪的黑客行为。首先,带前缀声明的数据:
@prefix : <urn:ex:>
:p1 :has_position 1 .
:p2 :has_position 2 .
:p3 :has_position 3 .
:p4 :has_position 4 .
然后查询。这select行中有一个长字符串连接,但这只是为了去掉问题中描述的前缀。在这种情况下,“黑客”是认识到两个最近的点q and r将最大限度地减少数量|p − q| + |p − r|,所以我们可以计算该数量并取值q and r这给了我们。您还需要确保对q and r,否则你会得到重复的结果(因为你可以交换q and r).
prefix : <urn:ex:>
select ?p (concat(strafter(str(?q),str(:)),", ",strafter(str(?r),str(:))) as ?neighbors) {
?p :has_position ?pos1 .
?q :has_position ?pos2 .
?r :has_position ?pos3 .
filter(?p != ?q && ?p != ?r)
filter(str(?q) < str(?r))
filter not exists {
?qq :has_position ?pos22 .
?rr :has_position ?pos33 .
filter(?p != ?qq && ?p != ?rr)
filter(str(?qq) < str(?rr))
filter((abs(?pos1 - ?pos22) + abs(?pos1 - ?pos33)) <
(abs(?pos1 - ?pos2) + abs(?pos1 - ?pos3)))
}
}
-------------------
| p | neighbors |
===================
| :p1 | "p2, p3" |
| :p2 | "p1, p3" |
| :p3 | "p2, p4" |
| :p4 | "p2, p3" |
-------------------
现在,您还可以使用子查询来执行此操作,该子查询查找每个的最小数量p,然后在外部查询中找到q and r产生它的值:
prefix : <urn:ex:>
select ?p (concat(strafter(str(?q), str(:)), ", ", strafter(str(?r), str(:))) as ?neighbors) {
{ select ?p (min(abs(?pos1 - ?pos2) + abs(?pos1 - ?pos3)) as ?d) {
?p :has_position ?pos1 .
?q :has_position ?pos2 .
?r :has_position ?pos3 .
filter(?p != ?q && ?p != ?r)
filter(str(?q) < str(?r))
}
group by ?p
}
?p :has_position ?pos1 .
?q :has_position ?pos2 .
?r :has_position ?pos3 .
filter(?p != ?q && ?p != ?r)
filter(str(?q) < str(?r))
filter(abs(?pos1 - ?pos2) + abs(?pos1 - ?pos3) = ?d)
}
-------------------
| p | neighbors |
===================
| :p1 | "p2, p3" |
| :p2 | "p1, p3" |
| :p3 | "p2, p4" |
| :p4 | "p2, p3" |
-------------------