Search code examples
sparqllinked-data

Use a numeric value as string value in SPARQL


Is possible to use somehow a numeric value as a string value in a SPARQL query? For instance, consider the following RDF data, query, and desired result:

Knowledge base

@prefix gr:  <http://purl.org/goodrelations/v1#>.
@prefix xsd: <http://www.w3.org/2001/XMLSchema#>.

:o a gr:QuantitativeValueFloat;
     gr:hasMinValueFloat "1,0"^^xsd:float
     gr:hasMaxValueFloat "10,0"^^xsd:float

Query

PREFIX gr: <http://purl.org/goodrelations/v1#>    
SELECT ?o ?v
WHERE {
  ?o a gr:QuantitativeValueFloat;
       gr:hasMinValueFloat ?vMin;
       gr:hasMaxValueFloat ?vMax.
  CONCAT((?vMin, ?vMax) as ?v)
}

Ideal Result

-----------------
| o  | v        | 
=================
| :o | 1,0-10,0 | 
-----------------

Solution

  • In RDF, all literals have a lexical form that can be obtained with the str function. SPARQL also includes some shorthand for certain kinds of literals. E.g., you can write 1 instead of "1"^^xsd:integer, but they're the same thing, and you can get "1" by doing either str(1) or str("1"^^xsd:integer). That means that you can do what you're trying to do with str and concat:

    select ?xy where {
      values ?x { 1   }  #-- short for "1"^^xsd:integer
      values ?y { 2.5 }  #-- short for "2.5"^^xsd:decimal
    
      bind(concat(str(?x),"--",str(?y)) as ?xy)
    }
    

    ------------
    | xy       |
    ============
    | "1--2.5" |
    ------------
    

    This should work, even if the lexical form of the literals isn't legal for that datatype, as in you data where you have "10,0"^^xd:float, which should be "10.0"^^xsd:float, with a dot (.) rather than a comma (,). (I realize that there are different conventions for the separator, but SPARQL uses the dot.)