SPARQL date range

2019-07-24 12:44发布

问题:

I'm trying to obtain all records between certain dates. The date field has appears in this format: 2012-01-31. I think it is of type: <http://www.w3.org/2001/XMLSchema#date>

How would I modify the query below to extract records with date greater than 2012-01-31 please?

PREFIX xsd:     <http://www.w3.org/2001/XMLSchema#>
PREFIX rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs:    <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl:     <http://www.w3.org/2002/07/owl#>
PREFIX lrppi:   <http://landregistry.data.gov.uk/def/ppi/>
PREFIX skos:    <http://www.w3.org/2004/02/skos/core#>
PREFIX lrcommon: <http://landregistry.data.gov.uk/def/common/>

SELECT  ?county ?postcode ?amount ?date
WHERE
{    
    ?transx  lrppi:pricePaid ?amount .
    ?transx   lrppi:transactionDate ?date .
    ?transx   lrppi:propertyAddress ?addr.

    ?addr lrcommon:postcode "PL6 8RU"^^xsd:string .
    ?addr lrcommon:postcode ?postcode .

    # Cant get this line to work
    # ?date lrppi:transactionDate ?date . FILTER ( ?date >= "1327968000"^^xsd:date  )

    OPTIONAL {?addr lrcommon:county ?county .}
}
ORDER BY ?postcode

If you want to play with this, you can enter your query here: http://landregistry.data.gov.uk/landregistry/sparql/sparql.html

回答1:

This is what the FILTER clause is designed for.

The Expressions and Testing Values section of the SPARQL specification covers this in detail, pretty much the first example in that section covers filtering on dates.

Edit

If you are new to SPARQL then I would recommend you read a good SPARQL tutorial like SPARQL by Example which is written by one of the specification authors. This will walk you through various parts of SPARQL and should help you get your head around the RDF data model and query language better.

In terms of dates they are represented using XML schema datatypes, for example expressing today as a date would be the following:

"2013-03-22"^^xsd:date

The linked specification covers the lexical form of various datatypes.

So for your example it would be the following:

FILTER ( ?date >= "2012-01-31"^^xsd:date )

If you are starting from a UNIX timestamp and trying to get to an xsd:date see Generating an xsd:dateTime in shell script which may provide a useful starting point.



标签: sparql