SPARQL查询RDF本体

时间:2014-12-03 15:09:10

标签: rdf sparql

我正在尝试这个sparql查询,但我很难找出什么是错的。我想把所有含有这些成分的食谱都拿走。即: 食谱1:番茄 食谱2:番茄和盐 食谱3:番茄,盐,洋葱。

我有以下问题:

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rec:<http://www.receta.org#>

SELECT reduced ?r (count (?i) as ?cuantos) WHERE {

    ?x rdf:type rec:Receta .
    ?x rdfs:label ?r.

    filter not exists {
        ?x rec:Ingrediente ?i
        filter( ?i not in (rec:Tomato, rec:Salt) )
    }
}
GROUP BY ?r

我只会展示第一个。不是第二个而不是最后一个。

它只是一个例子,但实际上我想用更多的3个食谱来做,让我们说一个庞大的数据库,我想采取比番茄和盐更少成分的食谱。那么我怎么能修复我的查询呢?

我将尝试解释自己:

例如:

假设我有一个拥有数百种食谱的庞大数据库。其中一些是: 食谱1:番茄和盐 Receipe2:洋葱和肉 Receipe3:番茄和醋 Receipe4:巧克力和牛奶

在我的询问中,我说我想要配番茄,盐和醋的食谱。所以在这种情况下我想得到食谱1和食谱3,因为食谱1含有番茄和盐,食谱3含有番茄和醋,比我说的少一种成分。让我们说现在我添加了更多食谱:

食谱4:番茄 食谱5:盐 食谱6:番茄,醋,盐和洋葱 食谱6:番茄,醋,盐

如果我再次执行我的查询,我想拥有recipe1,recipe3,recipe4和recipe5。原因 那些食谱是含有这些成分或更少的食谱。我不希望食谱6的原因比我的要求更多的成分,甚至没有配方7。

谢谢!!!

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你会尝试指定一组成分,然后选择其成分是该成分的属性子集的配方(或者那些成分只是其中一部分的配方;你问题中的例子并没有明确说明。无论如何,不​​是用自然语言写出容易出错的例子,而是提供我们可以使用的数据更好,在这种情况下,它并不难要做到这一点。例如,这是一个包含九种食谱的小乌龟文件,每种食谱都有一些成分:

@prefix : <urn:ex:> .

:recipe1 :ingredient :tomato, :salt .
:recipe2 :ingredient :onion, :meat .
:recipe3 :ingredient :tomato, :vinegar .
:recipe4 :ingredient :chocolate, :milk .
:recipe5 :ingredient :tomato .
:recipe6 :ingredient :salt .
:recipe7 :ingredient :tomato, :vinegar, :salt, :onion .
:recipe8 :ingredient :tomato, :vinegar, :salt .
:recipe9 :ingredient :vinegar, :salt .

现在,我们可以编写一个查询来检索所有成分都在指定集合中的配方,并且仅保留那些具有少于(或小于或等于)某些特定数量的不同成分的配方。 (您不必包含 group_concat 的内容;我只是为了获得每个食谱的成分列表。)

prefix : <urn:ex:>

select ?recipe (group_concat(?ingredient;separator=', ') as ?ingredients) {
  ?recipe :ingredient ?ingredient
  filter not exists {
    ?recipe :ingredient ?other_ingredient
    filter( ?other_ingredient not in ( :salt, :tomato, :vinegar ) )
  }
}
group by ?recipe
having (count(distinct ?ingredient) < 3)
----------------------------------------------
| recipe   | ingredients                     |
==============================================
| :recipe9 | "urn:ex:salt, urn:ex:vinegar"   |
| :recipe5 | "urn:ex:tomato"                 |
| :recipe6 | "urn:ex:salt"                   |
| :recipe3 | "urn:ex:tomato, urn:ex:vinegar" |
| :recipe1 | "urn:ex:tomato, urn:ex:salt"    |
----------------------------------------------

如果您想要包含所有三种成分的食谱,您只需更改行

即可
having (count(distinct ?ingredient) < 3)

以下任何一个:

having (count(distinct ?ingredient) <= 3)

having (count(distinct ?ingredient) < 4)
相关问题