Catch exception related to number field handling in older SDK.
[gae-samples.git] / search / python / sortoptions.py
blob71af03e186e777f6bce269bfb79f8c7611256cef
1 #!/usr/bin/python
3 # Copyright 2012 Google Inc. All Rights Reserved.
6 import logging
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):
16 expr_list = [
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
26 MatchScorer score:
28 expr_list = [
29 search.SortExpression(expression='_score + 0.001 * rating',
30 default_value='',
31 direction=search.SortExpression.DESCENDING)]
32 sort_opts = get_sort_options(expression=expr_list,
33 match_scorer=search.MatchScorer(),
34 limit=sort_limit)
37 Args:
38 expression: a list of search.SortExpression. Do not set limit parameter on
39 SortExpression
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.
46 """
47 try:
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.")
57 expr_list = []
58 # copy the sort expressions including the limit info
59 if expressions:
60 expr_list = [
61 search.SortExpression(
62 expression=e.expression, direction=e.direction,
63 default_value=e.default_value, limit=limit)
64 for e in expressions]
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)
69 return expr_list