Search code examples
sparqlrdfshacl

How to use sh:rule and sh:count correctly


Here is my data.ttl:

@prefix : <http://example.com/ns#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

:Bob  a  :Student ;
        :name "Bob" ;
        :tookTest :Test1, :Test2, :Test3, :Test4, :Test5 .

:Test1 a :Test ;   
          :grade "A" .

:Test2 a :Test ;
           :grade "A" .

:Test3  a :Test ;
          :grade "A" .

:Test4 a :Test ;
          :grade "C" .

:Test5 a :Test ;
          :grade "D" .

the shacl.ttl is:

@prefix : <http://example.com/ns#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix sh: <http://www.w3.org/ns/shacl#> .

:Test a rdfs:Class,  sh:NodeShape .
:Student    a rdfs:Class, sh:NodeShape ;
                sh:rule [
        a sh:TripleRule ;
        sh:subject sh:this ;
        sh:predicate :rating ;
        sh:object [sh:count [sh:path :Test] ];  
                     ] .

and I use shacl inferance engine (https://github.com/TopQuadrant/shacl):

shaclinfer.bat -datafile D:\data.ttl -shapesfile D:\shacl.ttl>D:\report.txt

I get a result report as:

<http://example.com/ns#Bob>
        <http://example.com/ns#rating>  0 .

I actually want to implement the following rule:

if Bob get more than 2 "A", then--> :Bob :rating "Outstanding" .

How do I write this sh:condition statement correctly? In this case sh:count should calculate the number of Test which grade="A",Do I have to use sparql CONSTRUCT statements? Thanks for any help!


Solution

  • @prefix : <http://example.com/ns#> .
    @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
    @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
    @prefix sh: <http://www.w3.org/ns/shacl#> .
    
    :Test a rdfs:Class,  sh:NodeShape .
    :Student    a  rdfs:Class, sh:NodeShape ;
                sh:rule [
                        a sh:TripleRule ;
                        sh:subject sh:this ;
                        sh:predicate :rating ;
                        sh:object "Outstanding";  
                        sh:condition :Student ;
                        sh:condition [
                                sh:qualifiedValueShape [
                                         sh:path (:tookTest :grade ) ;
                                         sh:hasValue "A" ; ] ; 
                                sh:qualifiedMinCount 2 ; ];    
                        ] .
    

    The shacl.ttl looks close to correct, but it get error by engine of https://github.com/TopQuadrant/shacl, the error message as follows:

    Exception in thread "main" org.apache.jena.query.QueryParseException: Line 2, column 1: Unresolved prefixed name: :tookTest
    

    Would anyone please test this with any of the other SHACL inference engines?