3 # Copyright 2012 Google Inc. All Rights Reserved.
8 from google
.appengine
.api
import search
11 def get_sort_options(expressions
=None, match_scorer
=None, limit
=1000):
12 """Constructs sort options for 1.6.4 and 1.6.5 API differences.
14 An example of usage (NOTE: Do NOT set limit on SortExpression or MatchScorer):
17 search.SortExpression(expression='author', default_value='',
18 direction=search.SortExpression.DESCENDING)]
19 sort_opts = get_sort_options(expression=expr_list, limit=sort_limit)
21 The returned value is used in constructing the query options:
23 options=search.QueryOptions(limit=doc_limit, sort_options=sort_opts)
25 Another example illustrating sorting on an expression based on a
29 search.SortExpression(expression='_score + 0.001 * rating',
31 direction=search.SortExpression.DESCENDING)]
32 sort_opts = get_sort_options(expression=expr_list,
33 match_scorer=search.MatchScorer(),
38 expression: a list of search.SortExpression. Do not set limit parameter on
40 match_scorer: a search.MatchScorer or search.RescoringMatchScorer. Do not
41 set limit parameter on either scorer
42 limit: the scoring limit
44 Returns: the sort options value, either list of SortOption (1.6.4) or
45 SortOptions (1.6.5), to set the sort_options field in the QueryOptions object.
48 # using 1.6.5 or greater
49 if search
.SortOptions
:
50 logging
.info("search.SortOptions is defined.")
51 return search
.SortOptions(
52 expressions
=expressions
, match_scorer
=match_scorer
, limit
=limit
)
54 # SortOptions not available, so using 1.6.4
55 except AttributeError:
56 logging
.info("search.SortOptions is not defined.")
58 # copy the sort expressions including the limit info
61 search
.SortExpression(
62 expression
=e
.expression
, direction
=e
.direction
,
63 default_value
=e
.default_value
, limit
=limit
)
65 # add the match scorer, if defined, to the expressions list.
66 if isinstance(match_scorer
, search
.MatchScorer
):
67 expr_list
.append(match_scorer
.__class
__(limit
=limit
))
68 logging
.debug("sort expressions: %s", expr_list
)