Advanced Sorting of Plone Search Results

If you have advanced sorting needs, you might find that the ‘sort_on’ attribute provided by the portal_catalog search is very limited.

If you’ve performed a catalog search before, you may be aware the the ‘sort_on’ attribute only allows sorting on a single field with the option to sort ascending or descending.

If you need more advanced options, you can hand your result set off to Python to take care of the complex sorting.

To start with a simple example, lets use the Python sort function, combined with lambda to create a basic sort on a single field:

results = context.portal_catalog.searchResults(portal_type='News Item')
results = list(results) # convert the results to a python list so we can use the sort function
results.sort (lambda x, y : cmp (y['title'], x['title']))

The above sort uses cmp to compare two elements in the results list. Let’s assume that we have a few news items that share the same title. We may then also want to sort by a secondary field, like description:

results.sort (lambda x, y : cmp((y['title'], y['title']), (x['description'], x['description'])))