Use COUNT inside a CONSTRUCT function in SPARQL

968 views Asked by At

I am trying to write a SPIN-Rule that will count the number of incoming references and set this number as a property value. E.g., count number of Issues that occurred on a particular machine. Therefore I need to count the number of incoming references of type rdfs:occuredOn (domain: Issue, range: Machine).

CONSTRUCT {
?machine rdfs:numberOfIssues ?n .
}

WHERE {
?machine a ex:Machine .
?issue a ex:Issue .
?issue ?r ?machine .
(COUNT(?r) AS ?n) //Error
}       

Thank you in advance!

1

There are 1 answers

1
UninformedUser On BEST ANSWER

Only GroupGraphPattern is allowed, i.e., you have to use a sub-SELECT query in the WHERE clause:

CONSTRUCT 
  { 
    ?machine rdfs:numberOfIssues ?n .
  }
WHERE
  { { SELECT  ?machine (COUNT(?r) AS ?n)
      WHERE
        { ?machine  a  owl:Machine .
          ?issue    a  owl:Issue ;
                    ?r        ?machine
        }
      GROUP BY ?machine
    }
  } 

Note, you should never user built-in namespaces/prefixes (such as owl:, rdfs:, rdf:, xsd:, etc.) for your domain ontology!