SPARQL计算多个图形中的三元组

时间:2015-02-03 18:01:23

标签: count sum sparql

我想在多个图表中计算三元组,这些图表属于某个类并总结。我设法计算每个图中这个类的三元组,但我无法计算总数。

初始查询:

PREFIX locah: <http://data.archiveshub.ac.uk/def/>
PREFIX bs: <http://localhost:3030/alod/bs>
PREFIX ne: <http://localhost:3030/alod/ne>

SELECT (count(?sBS) as ?BScount) (count(?sNE) AS ?NEcount) WHERE {
  {
    GRAPH bs: {
      ?sBS a locah:ArchivalResource
    }
  } UNION {
    GRAPH ne: {
      ?sNE a locah:ArchivalResource
    }
  }
}    

我的想法是简单地使用SUM()函数,因此SELECT将是这样的:

SELECT (count(?sBS) as ?BScount) (count(?sNE) AS ?NEcount) (SUM(?NEcount ?BScount) AS ?total )WHERE {

但这似乎不起作用。

还有一个相关的问题:为什么我需要UNION?如果我在没有UNION的情况下执行它,它似乎会得到一个非常高的三重计数,这没有多大意义,计数是两倍相同。

您可以在我的SPARQL端点上尝试:http://data.alod.ch/sparql/

1 个答案:

答案 0 :(得分:3)

在投影中使用聚合时,必须通过某些变量的不同值对解决方案进行分区或分组。如果您未指定 group by 子句,则分组是隐式的。在这种情况下,您有(至少)两个选项。一种是使用两个子查询,如:

select ?acount ?bcount (?acount + ?bcount as ?totalCount) where {
  { select (count(*) as ?acount) where {
      graph :a { ... } }
  { select (count(*) as ?bcount) where {
      graph :b { ... } }
}

我认为这可能是最简单,最不言自明的选择。正如您所指出的,另一个选择是使用联合:

select (count(?a) as ?acount)
       (count(?b) as ?bcount)
       (?acount + ?bcount as ?totalCount)
where {
  { graph :a { ?a ... } }
  union
  { graph :b { ?b ... } }
}

之类的原因
select (count(?a) as ?acount)
       (count(?b) as ?bcount)
       (?acount + ?bcount as ?totalCount)
where {
  graph :a { ?a ... }
  graph :b { ?b ... }
}

没有工作是你最终得到了?a和?b值的笛卡尔积?。也就是说,假设对于αa有两个值,对于αb有三个值。然后你最终得到表中的六行:

a1, b1  
a1, b2 
a1, b3
a2, b1  
a2, b2 
a2, b3

这些行中的每一行都是唯一的,因此如果您使用隐含的,则您将拥有6个a和6个b,这些不是&#39真的是你想要的。但是,您仍然可以使用 distinct

执行此操作
select (count(distinct ?a) as ?acount)
       (count(distinct ?b) as ?bcount)
       (?acount + ?bcount as ?totalCount)
where {
  #-- ...
}

查询类型

类型1:子查询

SELECT ?BScount ?NEcount (?BScount + ?NEcount as ?totalCount)
WHERE {
  { select (count(*) as ?BScount) WHERE {
      GRAPH bs: { ?sBS a locah:ArchivalResource }
    } }
  { select (count(*) as ?NEcount) WHERE {
      GRAPH ne: { ?sNE a locah:ArchivalResource }
    } }
}

类型2:联盟

SELECT (count(?sBS) as ?BScount)
       (count(?sNE) AS ?NEcount)
       (?BScount + ?NEcount as ?totalCount)
WHERE {
  { GRAPH bs: { ?sBS a locah:ArchivalResource } }
  UNION
  { GRAPH ne: { ?sNE a locah:ArchivalResource } }
}

类型3:笛卡尔积和不同

SELECT (count(distinct ?sBS) as ?BScount)
       (count(distinct ?sNE) AS ?NEcount)
       (?BScount + ?NEcount as ?totalCount)
WHERE {
  { GRAPH bs: { ?sBS a locah:ArchivalResource } }
  { GRAPH ne: { ?sNE a locah:ArchivalResource } }
}