How to make a SPARQL query to find the highest value for a property?

Suppose I have a predicate of type "age", where the values ​​of all age triples are integer literals. Which SPARQL query will return the topic with the highest age in the data?

+4
source share
3 answers

You just need to do order by desc with the age predicate and then limit to just get the first one.

 PREFIX ns: <http://namespace.org/ontology/> SELECT ?s ?age WHERE { ?s ns:age ?age } ORDER BY DESC(?age) LIMIT 1 

See the order by semantics in SPARQL here

In the next version of SPARQL, 1.1, which is already supported on some systems, you can use function aggregates and do.

 SELECT max(?age) as ?maxage WHERE { ?s ns:age ?age } 

This is currently not supported in all three stores.

+6
source

In addition to Manuel queries, you may need to use xsd:integer to force the values ​​to be non-integer if your data has some invalid / ugly values:

 PREFIX ns: <http://namespace.org/ontology/> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> SELECT ?s ?age WHERE { ?s ns:age ?age } ORDER BY DESC(xsd:integer(?age)) LIMIT 1 

Depending on your data, you may need to add this to your second SPARQL 1.1 query.

+5
source

msalvadores' okay, however there is a small typo in the SPARQL 1.1 query, it should be:

 SELECT (MAX(?age) AS ?maxage) WHERE { ?s ns:age ?age } 

(missing brackets around AS)

+3
source

Source: https://habr.com/ru/post/1337457/


All Articles