是否可以使用 if 语句来确定在 SPARQL 的 where 子句中使用哪种图形模式?

Is it possible to use if statements to determine which graph pattern to use in where clause in SPARQL?

所以我对 SPARQL 还很陌生。我知道在 SPARQL 中不能以这种方式使用 if 语句,但我想知道是否有某种方法可以完成我想要完成的事情,即根据绑定的值匹配不同的图形模式。

SELECT ...
WHERE {
    // ...set ?x to some count
    IF (?x = 0) {
       // series of graph patterns
    }
    ELSE {
       // different series of graph patterns
    }
}

我看到的大多数示例只是基于 if 语句设置特定绑定的值,这不是我想要做的。 else 中的图形模式在计算上很昂贵,除非有必要,否则我不想 运行 它。

您不能像您在示例中显示的那样进行操作,但您可以使用如下所示的 UNION 模式:

SELECT ...
WHERE {
  {
     // ... set ?x to some value
     // series of graph patterns
     FILTER(?x = 0)
  }
UNION
  {
     // ... set ?x to some value
     // different series of graph patterns
     FILTER(?x != 0)
  }
}

请注意,如果您希望过滤器在子图模式内工作,则需要在模式内绑定 ?x。如果 SPARQL 引擎优化得很好,则应在匹配图形模式之前评估过滤器,但您也可以尝试放置过滤器,例如,在 ?x 的绑定和图形模式之间。