Sorting SPARQL results by date

cupakob picture cupakob · Jul 20, 2009 · Viewed 17.7k times · Source

Is there a way to sort the results by creation date?

Example query which must be sortet:

SELECT * WHERE {?s ?p ?o} limit 200

Answer

Phil M picture Phil M · Jul 20, 2009

You can use an order by clause just like you can in SQL. Note that per the SPARQL specification, the ORDER BY only applies to SELECT queries. You will need to create a binding for the property you want to use for ordering.

SELECT ?s ?p ?o
WHERE {?s ?p ?o .
       ?s <creationDatePredicate> ?date . }
ORDER BY DESC(?date)
LIMIT 200

Update: If you're not already storing the creation date, you will need to store the metadata yourself. As to how do to do that, you have a few options:

  1. Store a triple in your default graph which has the creation date for each subject. If you're storing more than one graph, this will become unwieldy very quickly and probably is not what you want.

  2. Store each graph as a named graph in your RDF triple store. You can then store metadata about each graph in the default graph or in one "shared" named graph for creation times.

  3. Store your data in the named graph and use a named graph to store the creation time metadata.

An example of option #2's SPARQL query would be:

SELECT ?s ?p ?o
WHERE {
        GRAPH ?g { ?s ?p ?o . }
        ?g <creationDatePredicate> ?date . }
ORDER BY DESC(?date)
LIMIT 200