sparqlrdfblazegraphknowledge-graph

Is it possible to perform an INSERT operation with the GROUP BY clause in SPARQL/Update?


Suppose I have a graph containing students from three different grades.

Sample graph:

<http://some/graph#John_Doe> rdf:type <http://some/graph/ontology#Student>
<http://some/graph#John_Doe> <http://some/graph#hasGrade> <http://some/graph#Grade_3>
<http://some/graph#Grade_3> rdf:type <http://some/graph/ontology#Grade>

I want to create an attribute for every instance of class Grade called gradeStrength to store the number of students in that grade.

With the above example it would look like:

<http://some/graph#Grade_3> <http://some/graph#gradeStrength> 1^^xsd:integer

Currently I do it using two separate queries as follows -

  1. Run a SELECT + GROUP BY query on the graph to get count per grade
  2. Iterate over the result rows of 1. to create a string of triples
  3. Run a INSERT DATA update query on the graph

How can I achieve this by using a single SPARQL/Update query using the INSERT and GROUP BY constructs? I tried writing such a query and it fails in Blazegraph.


Solution

  • Use

    INSERT {
      ?grade <http://some/graph#gradeStrength> ?gradeStrength
    } 
    WHERE 
    { 
      { 
        SELECT ?grade (COUNT(?student) AS ?gradeStrength)  
        { 
          ?student  <http://some/graph#hasGrade> ?grade . 
        } 
        GROUP BY ?grade   
      } 
    }
    

    Answer made from comment by @UninformedUser. Tested on Blazegraph by uploading sample triples from the question.