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

十年热恋 提交于 2019-12-19 18:22:25

问题


Lets say I have a predicate like 'age' where the values of all age triples are integer literals. What SPARQL query would return the subject with the highest age in the data?


回答1:


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 semantics of order by in SPARQL here

With the next version of SPARQL , 1.1, that is already supported in some systems you can use function aggregates and do ..

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

This is not supported in all triple stores currently.




回答2:


In addition to Manuel's queries you may need to use xsd:integer to force values to be cast to integer if your data has some invalid/dodgy 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 into his second SPARQL 1.1 query as well.



来源:https://stackoverflow.com/questions/4827691/how-do-i-make-a-sparql-query-to-find-the-highest-value-for-a-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!