SPARQL 未绑定变量 ||查询绑定变量(如果未绑定)
SPARQL Unbound variables || Query to bind a variable if it's unbound
我正在尝试编写一个查询,将一个变量绑定到一个值,如果它还没有被绑定的话。
例如,它可能看起来像这样的伪代码:
OPTIONAL {
FILTER (some filter)
BIND ("I bound this variable" as ?variable)
}
OPTIONAL {
FILTER (!BOUND(?variable))
BIND ("This variable was unbound, but is now bound"
}
基本上,我有一个可能有也可能没有分配值的变量,如果没有,我想分配一个,但我无法使用 FILTER (!BOUND(?variable))
之类的方法进行查询。
您要查找的是 COALESCE 函数。
例如,假设您有以下数据:
@prefix : <http://example.com/> .
:john a :Person ;
:hasChild :anna , :will .
:anna a :Person ;
:hasChild :charlie .
:will a :Person .
:charlie a :Person .
然后是 SPARQL 查询:
SELECT ?person ?child
WHERE {
?person a :Person .
OPTIONAL { ?person :hasChild ?c }
BIND(COALESCE(?c, "Has no children.") AS ?child)
}
请注意 COALESCE
可以接受 2 个以上的参数,例如如果我们将数据稍微更改为:
@prefix : <http://example.com/> .
:john a :Person ;
:hasDaughter :anna ;
:hasSon :will .
:anna a :Person ;
:hasSon :charlie .
:will a :Person .
:charlie a :Person .
即我们说 child 是儿子还是女儿,那么我们可以发出这样的查询:
SELECT ?person ?child
WHERE {
?person a :Person .
OPTIONAL { ?person :hasDaughter ?daughter }
OPTIONAL { ?person :hasSon ?son }
BIND(COALESCE(?daughter, ?son, "Has no children.") AS ?child)
}
这个 return 如果有女儿的话。如果做不到,它将 return 个儿子,如果同样做不到,它将 return “没有 child 人。”
我正在尝试编写一个查询,将一个变量绑定到一个值,如果它还没有被绑定的话。
例如,它可能看起来像这样的伪代码:
OPTIONAL {
FILTER (some filter)
BIND ("I bound this variable" as ?variable)
}
OPTIONAL {
FILTER (!BOUND(?variable))
BIND ("This variable was unbound, but is now bound"
}
基本上,我有一个可能有也可能没有分配值的变量,如果没有,我想分配一个,但我无法使用 FILTER (!BOUND(?variable))
之类的方法进行查询。
您要查找的是 COALESCE 函数。 例如,假设您有以下数据:
@prefix : <http://example.com/> .
:john a :Person ;
:hasChild :anna , :will .
:anna a :Person ;
:hasChild :charlie .
:will a :Person .
:charlie a :Person .
然后是 SPARQL 查询:
SELECT ?person ?child
WHERE {
?person a :Person .
OPTIONAL { ?person :hasChild ?c }
BIND(COALESCE(?c, "Has no children.") AS ?child)
}
请注意 COALESCE
可以接受 2 个以上的参数,例如如果我们将数据稍微更改为:
@prefix : <http://example.com/> .
:john a :Person ;
:hasDaughter :anna ;
:hasSon :will .
:anna a :Person ;
:hasSon :charlie .
:will a :Person .
:charlie a :Person .
即我们说 child 是儿子还是女儿,那么我们可以发出这样的查询:
SELECT ?person ?child
WHERE {
?person a :Person .
OPTIONAL { ?person :hasDaughter ?daughter }
OPTIONAL { ?person :hasSon ?son }
BIND(COALESCE(?daughter, ?son, "Has no children.") AS ?child)
}
这个 return 如果有女儿的话。如果做不到,它将 return 个儿子,如果同样做不到,它将 return “没有 child 人。”