SPARQL过滤器正则表达式和联合 [英] SPARQL filter regex and union

查看:134
本文介绍了SPARQL过滤器正则表达式和联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的本​​体有2个类:food foodSource. 我想使用SPARQL查询获取具有2种foodSource的类food的数据:

My ontology has 2 classes: food foodSource. I want to get the data for the class food with 2 kinds of foodSource using the SPARQL query:

SELECT ?food ?foodSource ?foodSource2
WHERE {
  {
    ?foodSource mpasi:data_memerlukanBahan ?memerlukanBahan.
    ?food ?memerlukanBahan ?value.
    FILTER  regex(str(?foodSource),"carrot")
  }
  UNION
  {
    ?foodSource2 mpasi:data_memerlukanBahan ?memerlukanBahan.
    ?food ?memerlukanBahan ?value.
    FILTER  regex(str(?foodSource2),"tomato")
  }
} 
order by ?food

我得到正确的结果.但是后来我想避免一些食物来源.那么,如何获得没有食物来源的食物呢?例如,我有3种食物:

I get the correct result. But then I want to avoid some food sources. So, how do can I get food that doesn't have a food source? For example, I have 3 kinds of food:

  • kedelai粥
  • 苹果酥
  • 番茄汤

然后我想要里面没有苹果的食物.因此,自然地,我只会得到kedelai粥和番茄汤. 我可以使用!regex来获得它吗?

Then i want food without apple inside it. So, naturally i just get kedelai porridge and tomato soup. Can i get it using !regex?

FILTER  (!regex(str(?foodSource),"apple")).

推荐答案

也许第一步是重构您的UNION语句.对于两个UNION图语句,前两个三元模式都相同,因此请将其移到UNION语句之外.然后只剩下两个FILTER语句,可以使用||表达式重写它们:

Perhaps a first step is to refactor your UNION statement. The first two triple patterns are the same for both UNION graph statements, so move those outside of your UNION statement. Then you're left with just the two FILTER statements, which can be re-written with an || expression:

SELECT ?food ?foodSource ?foodSource2
WHERE {
  ?foodSource mpasi:data_memerlukanBahan ?memerlukanBahan.
  ?food ?memerlukanBahan ?value.
  FILTER (regex(str(?foodSource),"carrot") || regex(str(?foodSource2),"apple"))
}

如@AKSW建议的那样,也许更好的方法是在正则表达式本身中执行or:

Perhaps better, as @AKSW suggests, is to perform the or in the regex itself:

FILTER regex(str(?foodSource),"carrot|apple")

由于SPARQL中的FILTER是一个正过滤器-它指出要允许的内容-因此胡萝卜"和苹果"是唯一可能的解决方案. 马铃薯"无法通过过滤器.

Since FILTER in SPARQL is a positive filter - it states what to let through - then "carrot" and "apple" are the only possible solutions. "potato" can't get through the filter.

但是,如果您想查找除马铃薯"以外的所有内容,那么您可以有两种否定选择:

However if you wanted to find everything but "potato", then you have a couple of negation choices:

FILTER (!regex(str(?foodSource),"potato"))

或通过正则表达式求反:

or via regex negation:

FILTER regex(str(?foodSource),"[^potato]")

这篇关于SPARQL过滤器正则表达式和联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆