在 SPARQL 中计算具有特定类型 属性 的资源

Count resources having a property of a certain type in SPARQL

我在三重存储中有数据,想计算以下内容:

有多少资源 'x' 有对象 属性 'op' 至少有 2 个相似类型 'R' 的不同资源 'r' 作为值?

以下是 turtle 语法中此类数据的示例:

PREFIX ex: <http://example.com>

ex:doc1 
  a ex:Document ;
  ex:mentions p1, p2, p3 .

ex:doc2 
  a ex:Document ;
  ex:mentions p4, p5 .

ex:p1
  a ex:Person ;
  ex:hasRole ex:r1 .

ex:p2
  a ex:Person ;
  ex:hasRole ex:r1 .

ex:p3
  a ex:Person ;
  ex:hasRole ex:r2 .

ex:p4
  a ex:Person ;
  ex:hasRole ex:r1 .

ex:p5
  a ex:Person ;
  ex:hasRole ex:r2 .

ex:r1
  a ex:Role1 . 

ex:r2
  a ex:Role2 .

objective 是统计资源,例如 ex:doc1 有 2 个 ex:mentions 具有相似的角色(r1 类型 ex:Role1)。这里的结果将为 1,撇开 ex:doc2`.

策略是:

  1. 识别具有所需 属性 的资源,即文档 (doc) 具有指向资源 (person) 的对象属性 (mentions),这些资源本身具有相似值的属性 (hasRole) (角色)).

  2. 数一数。

我在第 1 步时遇到困难。 例如,此查询 returns all docs having a p1 with Role1,即使只有一个 p (p1) 具有此 属性.

SELECT distinct ?doc
WHERE
{
    ?doc a ex:Document .
    ?doc ex:mentions ?p1 .
    ?doc ex:mentions ?p2 .
    ?p1 ex:hasRole ?r1 .
    ?p2 ex:hasRole ?r1 .
    ?r1 a ex:Role1 .
}

非常感谢您的帮助。

您的数据不太可用(p1、p2 等资源上没有前缀),但修复后,我可以使用以下查询。你非常接近;诀窍是您需要 filter(?p1 != ?p2) 以确保您获得 ex:mentions 属性 的不同值。然后你可以检查他们是否有一个具有共同类型的角色 ?p1 ex:hasRole/a ?roleType 。 ?p2 ex:hasRole/a ?roleType,或者更简洁地说,?roleType ^(a/ex:hasRole) ?p1, ?p2。然后,在计数时,你只想计算 ?documentdistinct 个值,所以你需要 (count(distinct ?文档) 作为 ?nDocuments):

prefix ex: <http://example.com>

select
  #-- count ?document, but only count *distinct* values
  #-- of ?document.
  (count(distinct ?document) as ?nDocuments)

where {
  #-- get documents that have two distinct 
  #-- values for the ex:mentions property
  ?document a ex:Document ; ex:mentions ?p1, ?p2
  filter(?p1 != ?p2)

  #-- then check that they have a common role type
  ?roleType ^(a/ex:hasRole) ?p1, ?p2
}
--------------
| nDocuments |
==============
| 2          |
--------------