TagBrowse Sorts Characters not numbers

I have a script that was working great sorting tags until I added one with a label over 99.

I am using system.tag.browsTags to sort through some tags and generate a few JSON objects.

It looks to sort by character and not number. Can you change the sort outside of ASC or DESC?

I could break the sort into the first 99, then do another sort for larger values. Hoping to find a quicker solution. Thanks!!

Code:

tagPath = self.session.custom.TagPath
tagList = system.tag.browseTags(parentPath=tagPath,udtParentType='Sensor',sort='ASC') 
return tagList

Sort causes 100 to follow 10. Sensor10, Sensor100, etc.

You should be consistent with your tag naming.

[Ignition_monterey_in_edge]Indiana/Monterey/LoehmerDairy/Sensor06

This should be padded correctly for the number of tags you are using:

[Ignition_monterey_in_edge]Indiana/Monterey/LoehmerDairy/Sensor006

If you use this consistency in naming, it will sort correctly. The sorting always runs left to right, character by character, so Sensor10 and Sensor100 are identical up to character 8, then 100 has an extra character and will be placed after Sensor10 but before Sensor11

3 Likes

Here's a general purpose "human" sort operation (instead of lexicographic) you can put in your project library:

from com.inductiveautomation.ignition.common.util import Comparators

__comparator = Comparators.alphaNumeric()

def alphaSort(iterable, key, reverse=False):
	return sorted(
		tags, 
		cmp=lambda n1, n2: __comparator.compare(n1, n2), 
		key=key,
		reverse=reverse,
	)

You'll have to pass a key function like the sorted builtin function expects, e.g:

tags = system.tag.browseTags("")

for t in tags:
	print t.name
	

print

for t in alphaSort(tags, lambda t: t.name):
	print t.name
1 Like

If you've installed my Integration Toolkit (and why would you not?), you can use my naturalOrder() expression function with my orderBy() expresion function, or the script versions.

5 Likes

Initially we were only using 01 to 99. Of course the number began to grow. The system is deployed and collecting historical data. Adjusting the tag name structure at this time wouldn't be ideal.

Thanks for the insight on the sorting.

Awesome. Will give this a try. Thanks!

Natural order is what I need. Will check out the toolkit. :star_struck: