简体   繁体   English

SPARQL查询中的“或”

[英]“or” in a SPARQL query

I don't quite understand why in SPARQL they haven't implemented the basic logic operators. 我不太明白为什么在SPARQL中他们没有实现基本的逻辑运算符。 However in most of the cases is possible to obtain the same result in a number of way. 然而,在大多数情况下,可以以多种方式获得相同的结果。

The purpose of this question is to have a quick reference for the possible way troughs that can substitute an "or" statement. 这个问题的目的是快速参考可以用“或”语句替代的低谷。

Here's what I can think of: 这是我能想到的:

1) UNION 1) UNION

eg: 例如:

SELECT * WHERE
{  { ?s :propA ?o } UNION { ?s :propB ?o }  }

-not often suitable because it can became very verbose because - 通常不合适,因为它可能变得非常冗长,因为

SELECT * WHERE { 
    { GRAPH ?g {?s ?p ?o. ?o ?pp ?data1}} UNION 
    { GRAPH ?g {?s ?p ?o. ?o ?pp ?data2}}
} 

doesn't work as 不起作用

SELECT * WHERE { 
    GRAPH ?g {
       ?s ?p ?o. 
       {?o ?pp ?data1} UNION 
       {?o ?pp ?data2} 
    }
 }

(at least not with Stardog) (至少没有Stardog)

2) FILTER 2) FILTER

eg: 例如:

SELECT * WHERE
    { 
        ?s ?p ?o.
        FILTER (?p = :propA || ?p = :propB )
    }

Any other ideas? 还有其他想法吗?

I'm not entirely sure why you say SPARQL doesn't supply 'the basic logic operators', because your own examples clearly show that it does: it provides logical-OR ( || ) and logical-AND ( && ) as part of FILTER conditions, and disjunctive graph patterns using UNION (of course, conjunctive graph patterns need no special syntax). 我不完全确定为什么你说SPARQL不提供'基本逻辑运算符',因为你自己的例子清楚地表明它确实:它提供逻辑-OR( || )和逻辑&&&& )作为一部分FILTER条件和使用UNION析取图模式(当然,连接图模式不需要特殊语法)。

Other variations of OR -like constructs are also possible. OR样结构的其他变体也是可能的。 For queries of the form "this particular value must be one of these possibilities" you can use the set membership operator, IN : 对于“此特定值必须是这些可能性之一”形式的查询,您可以使用set membership运算符IN

SELECT * 
WHERE { 
    ?s ?p ?o.
    FILTER (?p IN (:propA, :propB, :propC ) )
}

You can also use the VALUES clause for this kind of pattern: 您还可以将VALUES子句用于此类模式:

SELECT * 
WHERE {
    VALUES ?p { :propA :propB :propC } 
    ?s ?p ?o.
}

Update I forgot one, perhaps the simplest. 更新我忘了一个,也许是最简单的。 For queries such as yours, where you are looking for a few alternatives for a property name, you can actually use a property path expression as well, like so: 对于像你这样的查询,你正在寻找一些属性名称的替代品,你也可以实际使用属性路径表达式,如下所示:

SELECT * 
WHERE {
    ?s :propA|:propB|:propC ?o.
}

If you want to trace which predicate lead to which object then this is universal solution for "OR" : 如果要跟踪哪个谓词导致哪个对象,那么这是“OR”的通用解决方案:

SELECT DISTINCT ?s ?o1 ?o2 
WHERE {
  {
     ?s p1 ?o1 .
     OPTIONAL
     {
        ?s p2 ?o2 .
     }
  } 
  UNION 
  {
     ?s p2 ?o2 .
     OPTIONAL
     {
        ?s p1 ?o1 .
     }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM