SPARQL Type Conversion?
Asked Answered
B

2

11

I have the following SPARQL query:

PREFIX ssn: <http://purl.oclc.org/NET/ssnx/ssn#> 
PREFIX dtp: <http://dtp-126.sncs.abdn.ac.uk#> 
PREFIX dbp: <http://dbpedia.org/resource/> 
SELECT ?value ?time WHERE {         
    dtp:CD7514 ssn:madeObservation ?observation .       
    ?observation ssn:observedProperty ?property .   
    ?property ssn:hasValue <http://dbpedia.org/resource/Temperature> .          
    ?observation ssn:observationResult ?observationValue .      
    ?observationValue ssn:hasValue ?value .         
    ?observationValue ssn:observationSamplingTime ?time 
    FILTER(?time > 1291908000)
}

Which, in a nutshell, is selecting all temperature sensor observations from a sensor, dtp:CD7514, and filtering out values less than the given timestamp.

However, adding the filter constraint returns 0 results (when there are observations that match this time region!)

Is it possible that ?time is a varchar/text/String data type and therefore the comparison can't be done? If so, is it possible to do the conversion within SPARQL?

Bifarious answered 14/12, 2010 at 12:58 Comment(1)
What's in your data graph - what's the datatype of ?time literals? The SSN ontology does not prescribe a specific format for the representation of time instants.Quintillion
B
2

The solution to this was merely to add quotes around the timestamp.

Bifarious answered 14/12, 2010 at 14:14 Comment(1)
Yeah, that makes them string literals and not xsd:integers. String literals have well defined lexicographical sort order.Quintillion
R
32

That's only going to work if the time value you're matching has the same number of digits, as it will do a strong compare. A better fix would be:

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
...
FILTER(xsd:integer(?time) > 1291908000)

That will cast the value in ?time to an integer, and then do a numeric compare on it.

Reprove answered 7/2, 2011 at 15:54 Comment(1)
Interesting that in 2022, this answer is still the top Google result for "SPARQL cast to int" and similar search phrases. I wonder how many people learned the correct SPARQL syntax for int casts through this SO answer :)Goldschmidt
B
2

The solution to this was merely to add quotes around the timestamp.

Bifarious answered 14/12, 2010 at 14:14 Comment(1)
Yeah, that makes them string literals and not xsd:integers. String literals have well defined lexicographical sort order.Quintillion

© 2022 - 2024 — McMap. All rights reserved.