This object does the work of sorting search results.
For simple sorting (where all fields go in the same direction), you can just use the sortedby and reverse arguments to whoosh.searching.Searcher.search():
# Sort by ascending group
r = searcher.search(myquery, sortedby="group")
# Sort by ascending path and the ascending price price
r = searcher.search(myquery, sortedby=("path", "price"))
# Sort by descending path
r = searcher.search(myquery, sortedby="path", reverse=True)
These are the equivalent of using the sorter directly:
# Sort by ascending path and the ascending price price
sorter = searcher.sorter()
sorter.add_field("path")
sorter.add_field("price")
r = sorter.sort_query(myquery)
For complex sorting (where some fields are ascending and some fields are descending), you must instantiate a sorter object from the searcher and specify the fields to sort by:
# Sort by ascending group and then descending price
sorter = searcher.sorter()
sorter.add_field("group")
sorter.add_field("price", reverse=True)
r = sorter.sort_query(myquery)
Alternatively, you can set up the sort criteria using a keyword argument:
# Sort by ascending group and then descending price
crits = [("group", False), ("price", True)]
sorter = searcher.sorter(criteria=crits)
r = sorter.sort_query(myquery)
Note that complex sorting can be much slower on large indexes than a sort in which all fields are sorted in the same direction. Also, when you do this type of sort on a multi-segment index, the sort cannot reuse field caches and must recreate a field cache-like structure across the entire index, which can effectively double memory usage for cached fields.
You can re-use a configured sorter with different queries. However, the sorter object always returns results from the searcher it was created with. If the index changes and you refresh the searcher, you need to recreate the sorter object to see the updates.
Parameters: |
|
---|
Adds a field to the sorting criteria. Results are sorted by the fields in the order you add them. For example, if you do:
sorter.add_field("group")
sorter.add_field("price")
...the results are sorted by group, and for results with the same value of group, are then sorted by price.
Parameters: |
|
---|
Returns True if this is a “simple” sort (all the fields are sorted in the same direction).
Returns a whoosh.searching.Results object for the given query, sorted according to the fields set up using the Sorter.add_field() method.
The parameters have the same meaning as for the whoosh.searching.Searcher.search() method.