The Splunk documentation says that the order rule is lexicographic. I am trying to sort the following values:
| makeresults
| eval fruit="apple"
| append [ | makeresults | eval fruit="Banana" ]
| append [ | makeresults | eval fruit="zebra" ]
| append [ | makeresults | eval fruit="10" ]
| append [ | makeresults | eval fruit="2" ]
| append [ | makeresults | eval fruit="20" ]
| append [ | makeresults | eval fruit="30" ]
| append [ | makeresults | eval fruit="3" ]
| append [ | makeresults | eval fruit="1" ]
| append [ | makeresults | eval fruit="25" ]
| append [ | makeresults | eval fruit="38" ]
| table fruit
| sort fruit
The output I am getting is:
1, 2, 3, 10, 20, 25, 30, 38, Banana, apple, zebra
I understand that Banana appears before apple because B<a. But what is up with string numerics?
Shouldn't the order be: 1, 10, 2, 20, 25, 3, 30, 38, Banana, apple, zebra ?
Even the documentation says that between 10, 9, 70, 100 the sorted output should be 10, 100, 70, 90.
https://help.splunk.com/en/splunk-enterprise/search/spl-search-reference/9.2/search-commands/sort
Interestingly, when using tostring() before the sort it still identifies as a number?!
The only way I can make it sort as a string is using | sort str(fruit) as @richgalloway mentioned.
🌟 Did this answer help you? If so, please consider:
Your feedback encourages the volunteers in this community to continue contributing
thanks for response ! @livehybrid @richgalloway
@richgalloway - yes, the documentation does mention that numerics will be sorted as numbers. I am confused because I thought that by putting quotes around the numbers, they would automatically get appended as strings to the fruit field and not as numbers.
So is it right to conclude that even though I added double quotes for numbers while appending them, by default Splunk does not take it as a string? Explicit type conversion is required as an additional step?
As @livehybrid noted, explicit type conversion does not make a difference here. If you need numbers sorted as strings then you must use the str operator.
Interestingly, when using tostring() before the sort it still identifies as a number?!
The only way I can make it sort as a string is using | sort str(fruit) as @richgalloway mentioned.
🌟 Did this answer help you? If so, please consider:
Your feedback encourages the volunteers in this community to continue contributing
When I add
| eval type=typeof(fruit)
to the query the results say the numbers are indeed numbers rather than strings. That would explain the sort.
When I use
| sort str(fruit)
the results are in the expected lexicographical order.
FWIW, the docs do say "Numeric data is sorted as you would expect for numbers and the sort order is specified as ascending or descending."