我正在尝试创建一个SPARQL查询来查找Jim知道的所有人,然后查找Jim知道的人知道哪些人,然后就像链一样。
例如我有:
Jim knows Clare and Antoine
Clare knows Jim and David
Antoine knows David and Clare
David knows Clare
结果是:
result1: Clare, Antoine
result2: Jim, David, David, Clare
result3: Clare, David, Clare, Clare, Jim, David
或多或少我做了类似树的东西。
我想要的是将result1
,result2
和result3
合并到result4
。所以result4
将是:
result4: clare, antoine, jim, david, david, clare, clare, david, clare, clare, jim, david.
然后使用DISTINCT
删除重复项。我怎么能实现这个目标呢?
SELECT ?Result1 ?Result2 ?Result3
WHERE{
{
base:Knows dc:Names _:BN1 .
_:BN1 dc:FName "Jim";
dc:KnownFName ?Result1 .
}
.
{
base:Knows dc:Names _:BN2 .
_:BN2 dc:FName ?Result1;
dc:KnownFName ?Result2 .
}
.
{
base:Knows dc:Names _:BN3 .
_:BN3 dc:FName ?Result2;
dc:KnownFName ?Result3 .
}
}
答案 0 :(得分:4)
我们假设您的示例表示如下:
<http://example.com/person/1> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/2> .
<http://example.com/person/1> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/3> .
<http://example.com/person/2> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/1> .
<http://example.com/person/2> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/4> .
<http://example.com/person/3> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/4> .
<http://example.com/person/3> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/2> .
<http://example.com/person/4> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/2> .
<http://example.com/person/1> <http://www.w3.org/2000/01/rdf-schema#label> "Jim" .
<http://example.com/person/2> <http://www.w3.org/2000/01/rdf-schema#label> "Clare" .
<http://example.com/person/3> <http://www.w3.org/2000/01/rdf-schema#label> "Antoine" .
<http://example.com/person/4> <http://www.w3.org/2000/01/rdf-schema#label> "David" .
然后,您可以使用SPARQL的UNION功能通过合并三个单独查询的结果来实现您的目标。可以使用SPARQL属性路径更简洁地表达它:
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT DISTINCT * WHERE {
{ SELECT * WHERE {
<http://example.com/person/1> foaf:knows/rdfs:label ?knowsName .
} }
UNION
{ SELECT * WHERE {
<http://example.com/person/1> foaf:knows/foaf:knows/rdfs:label ?knowsName .
} }
UNION
{ SELECT * WHERE {
<http://example.com/person/1> foaf:knows/foaf:knows/foaf:knows/rdfs:label ?knowsName .
} }
}
您还可以通过单个属性路径表达式获取knows
谓词的完整传递闭包:
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT * WHERE {
<http://example.com/person/1> foaf:knows+/rdfs:label ?knowsName .
}
...如果您的triplestore支持SPARQL 1.1。否则你将不得不使用推理或重复查询来完全关闭。