Search code examples
sortingsparqlontologyprotege

Sort the Inserted data on basis of Time in Ontology Model


I have an ontology Model. I am inserting integer data in one of the class instance through Sparql update. The model is storing the data randomly with out any order. Now when I want to extract this data through Sparql Query I want it in order of the time of insertion. How could i achieve this? Any idea?

P.S: My ontology Model is made in Protege software. My Query for inserting Data is below one.

PREFIX test:<http://www.semanticweb.org/muhammad/ontologies/2017/2/untitled-ontology-14#> 
INSERT { 
  ?KPI_Variables test:hasValue_ROB1 10
} WHERE {
  ?KPI_Variables test:hasValue_ROB1 ?Newvalue 
  FILTER(?KPI_Variables= test:Actual_Production_Time)
}

And For Getting the data I am using the following Query:

PREFIX test:<http://www.semanticweb.org/muhammad/ontologies/2017/2/untitled-ontology-14#> 
SELECT ?KPI_Variables ?Newvalue WHERE {
  ?KPI_Variables test:hasValue_ROB1 ?Newvalue 
  FILTER(?KPI_Variables = test:Actual_Production_Time)
} LIMIT 25

Solution

  • Data in RDF is simply triples. There's no notion of when a triple is added to a graph. If you want that kind of information, you'll need to make it explicit in your data model. SPARQL does include a now function that lets you get a timestamp for when a query is run. That means that you could do something like this:

    prefix  : <urn:ex:>
    
    insert {
      [] :hasSubject ?s ;
         :hasPredicate ?p ;
         :hasObject ?o ;
         :hasTime ?now .
    }
    where {
        #-- Fake a couple of triples
        values (?s ?p ?o) {
            (:a :p :b)
            (:c :q :d)
        }
        #-- Get the current time
        bind (now() as ?now)
    }
    

    Now your graph contains data like:

    @prefix :      <urn:ex:> .
    
    [ :hasObject     :d ;
      :hasPredicate  :q ;
      :hasSubject    :c ;
      :hasTime       "2017-04-28T13:32:11.482+00:00"^^<http://www.w3.org/2001/XMLSchema#dateTime>
    ] .
    
    [ :hasObject     :b ;
      :hasPredicate  :p ;
      :hasSubject    :a ;
      :hasTime       "2017-04-28T13:32:11.482+00:00"^^<http://www.w3.org/2001/XMLSchema#dateTime>
    ] .
    

    Which you can query like:

    prefix  : <urn:ex:>
    
    select ?s ?p ?o ?time {
      [] :hasSubject ?s ;
         :hasPredicate ?p ;
         :hasObject ?o ;
         :hasTime ?time
    }
    order by ?time
    
    s,p,o,time
    urn:ex:c,urn:ex:q,urn:ex:d,2017-04-28T13:32:11.482+00:00
    urn:ex:a,urn:ex:p,urn:ex:b,2017-04-28T13:32:11.482+00:00
    

    Once you've inserted some things at different times, you'd have different time values, so sorting would be meaningful. I'd suggest that you don't just reify the triples like I did (and if you are going to go with a straightfoward reification, you should probably use the standard vocabulary for it), but rather have some meaningful structure that actually has timestamps as part of it.