Order SPARQL query results by length of a string?
Asked Answered
U

1

8

I'm trying to autocomplete what the user writes in an input, with terms in DBpedia, similar to this jsFiddle example. Try writing dog in the input of that jsFiddle, and you will see the 'Dog' term in the suggestions.

I have the following code, and the problem is that the 10-term list I got as a result does not contains the "Dog" alternative. So, if I could order the list by the length of the (string representation of) ?concept, then I could get that term. Is this possible?

SELECT DISTINCT ?concept
WHERE {
  ?concept a skos:Concept . 
  FILTER regex(str(?concept), "dog", "i")
}
ORDER BY ASC(?concept) LIMIT 10
Unlay answered 12/2, 2016 at 17:40 Comment(0)
U
13

So, if I could order the list by the lenght of the ?concept it is possible to get the term. But I can't find the right statement to do it. Is it possible?

It sounds like you're looking for strlen.

order by strlen(str(?concept))

E.g.,

select distinct ?concept where {
  ?concept a skos:Concept . 
  filter regex(str(?concept), "dog", "i")
}
order by strlen(str(?concept))
limit 10

SPARQL results

That said, if you're just checking string membership, you don't need all the power of regular expressions, and it might be more efficient to use contains and lcase to check whether the lowercased ?concept contains "dog" with a filter like:

filter contains(lcase(str(?concept)), "dog")

The table of contents in the SPARQL spec has a big list of functions that you can browse. In particular, you'd want to look at the subsections of 17.4 Function Definitions.

Unguinous answered 12/2, 2016 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.