在SPARQL查询中使用条件

3

我有一个SPARQL查询,类似于这样:

SELECT ?informationPath ?businessEntitylabel ?path ?sourced ?mastered ?delivered
WHERE {
?businessEntity dd:hasPropertyPath ?informationPath .
?businessEntity rdfs:label ?businessEntitylabel .
?informationPath dd:hasPath ?path .
OPTIONAL {
?informationPath a dd:SourcedData .
BIND("Yes" as ?sourced)
}
OPTIONAL {
?informationPath a dd:MasteredData .
BIND("Yes" as ?mastered)
}
OPTIONAL {
?informationPath a dd:DeliveredData .
BIND("Yes" as ?delivered)
}
} ORDER BY ?businessEntitylabel ?path

现在我想只有一列,而不是?sourced ?mastered ?delivered和名称为?traceability。该列将显示一个?informationPath是否为Mastered数据或Sourced数据或Delivered数据,并相应地我想要BIND(“Sourced data”作为?traceability)或(“Mastered data”作为?traceability)或(“Delivered data”作为?traceability)
我是SPARQL的新手,我想知道SPARQL中是否有任何可以用作的“if”语句-
if(?informationPath a dd:SourcedData)
BIND("SourcedData" as ?traceability)

任何帮助将不胜感激。

可能是将变量绑定到两个值中的一个,使用IF?的重复问题。 - Joshua Taylor
1
SPARQL确实有一个if运算符,并且在规范的17.4.1.2 IF中清楚地描述了它。在您的情况下,您可以执行类似于bind( if( …, "Sourced, if( …, "Delivered", if ( …, "Mastered", "Unknown" ) ) ) as ?traceability )的操作。 - Joshua Taylor
2个回答

4

使用 bindif

我认为这是如何在两个值之间绑定变量?的重复问题,我已经将其标记为重复,但if语句中的条件可能不是非常明显,因此我在此添加此示例作为答案。假设您有以下形式的数据:

@prefix : <https://dev59.com/xX7aa4cB1Zd3GeqPr5Ps/> .

:x1 a :A .
:x2 a :B .
:x3 a :C .
:x4 a :D .

然后您可以使用以下查询来获取一些结果:
prefix : <https://dev59.com/xX7aa4cB1Zd3GeqPr5Ps/>

select ?x ?typename where { 
  ?x a [] .
  bind( if ( exists { ?x a :A },
             "type A" ,
             if ( exists { ?x a :B }, 
                  "type B",
                  if ( exists { ?x a :C },
                       "type C",
                       "unknown type" )))
        as ?typename )
}

------------------------
| x   | typename       |
========================
| :x1 | "type A"       |
| :x2 | "type B"       |
| :x3 | "type C"       |
| :x4 | "unknown type" |
------------------------

使用 values

这种方法适用于使用ifexists结构检查各种值的情况。如果你有一个特定数量的案例需要检查,你可以使用values模拟一种case语句。为此,你可以像下面这样做,虽然这不会给你一个“未知”的情况。

prefix : <https://dev59.com/xX7aa4cB1Zd3GeqPr5Ps/>

select ?x ?typename where { 
  values (?type ?typename) { 
    (:A "type A")
    (:B "type B")
    (:C "type C")
  }
  ?x a ?type
}

------------------
| x   | typename |
==================
| :x1 | "type A" |
| :x2 | "type B" |
| :x3 | "type C" |
------------------

2

扩展 Joshua Taylor 的答案,由于 UNDEF 关键字的存在,您实际上也可以处理默认情况:

prefix : <https://dev59.com/xX7aa4cB1Zd3GeqPr5Ps/>

select ?x ?typename where { 
  values (?type ?typename) { 
    (:A "type A")
    (:B "type B")
    (:C "type C")
    (UNDEF "unknown type")
  }
  ?x a ?type
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接