This repository has been archived by the owner on Feb 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
/
__init__.py
2183 lines (1615 loc) · 65.8 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import logging
from datetime import datetime
from operator import itemgetter
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk_index
from elasticutils._version import __version__ # noqa
log = logging.getLogger('elasticutils')
# Note: Don't change these--they're not part of the API.
DEFAULT_URLS = ['localhost']
DEFAULT_DOCTYPES = None
DEFAULT_INDEXES = None
DEFAULT_TIMEOUT = 5
#: Maps ElasticUtils field actions to their Elasticsearch query names.
QUERY_ACTION_MAP = {
None: 'term', # Default to term
'in': 'in',
'term': 'term',
'terms': 'terms',
'startswith': 'prefix', # Backwards compatability
'prefix': 'prefix',
'text': 'text',
'text_phrase': 'text_phrase',
'match': 'match', # ES 0.19.9 renamed text to match
'match_phrase': 'match_phrase',
'wildcard': 'wildcard',
'fuzzy': 'fuzzy'}
#: List of text/match actions.
TEXTMATCH_ACTIONS = ['text', 'text_phrase', 'match', 'match_phrase']
#: List of range actions.
RANGE_ACTIONS = ['gt', 'gte', 'lt', 'lte']
class ElasticUtilsError(Exception):
"""Base class for ElasticUtils errors."""
pass
class InvalidFieldActionError(ElasticUtilsError):
"""Raise this when the field action doesn't exist"""
pass
class InvalidFlagsError(ElasticUtilsError):
"""Raise when multiple flags are passed into a query"""
pass
class InvalidFacetType(ElasticUtilsError):
"""Raise when _type is unrecognized."""
pass
class BadSearch(ElasticUtilsError):
"""Raise when there is something wrong with the search."""
pass
def _build_key(urls, timeout, **settings):
# Order the settings by key and then turn it into a string with
# repr. There are a lot of edge cases here, but the worst that
# happens is that the key is different and so you get a new
# Elasticsearch. We'll probably have to tweak this.
settings = sorted(settings.items(), key=lambda item: item[0])
settings = repr([(k, v) for k, v in settings])
# elasticsearch allows urls to be a string, so we make sure to
# account for that when converting whatever it is into a tuple.
if isinstance(urls, basestring):
urls = (urls,)
else:
urls = tuple(urls)
# Generate a tuple of all the bits and return that as the key
# because that's hashable.
key = (urls, timeout, settings)
return key
_cached_elasticsearch = {}
def get_es(urls=None, timeout=DEFAULT_TIMEOUT, force_new=False, **settings):
"""Create an elasticsearch `Elasticsearch` object and return it.
This will aggressively re-use `Elasticsearch` objects with the
following rules:
1. if you pass the same argument values to `get_es()`, then it
will return the same `Elasticsearch` object
2. if you pass different argument values to `get_es()`, then it
will return different `Elasticsearch` object
3. it caches each `Elasticsearch` object that gets created
4. if you pass in `force_new=True`, then you are guaranteed to get
a fresh `Elasticsearch` object AND that object will not be
cached
:arg urls: list of uris; Elasticsearch hosts to connect to,
defaults to ``['http://localhost:9200']``
:arg timeout: int; the timeout in seconds, defaults to 5
:arg force_new: Forces get_es() to generate a new Elasticsearch
object rather than pulling it from cache.
:arg settings: other settings to pass into Elasticsearch
constructor; See
`<http://elasticsearch.readthedocs.org/>`_ for more details.
Examples::
# Returns cached Elasticsearch object
es = get_es()
# Returns a new Elasticsearch object
es = get_es(force_new=True)
es = get_es(urls=['localhost'])
es = get_es(urls=['localhost:9200'], timeout=10,
max_retries=3)
"""
# Cheap way of de-None-ifying things
urls = urls or DEFAULT_URLS
# v0.7: Check for 'hosts' instead of 'urls'. Take this out in v1.0.
if 'hosts' in settings:
raise DeprecationWarning('"hosts" is deprecated in favor of "urls".')
if not force_new:
key = _build_key(urls, timeout, **settings)
if key in _cached_elasticsearch:
return _cached_elasticsearch[key]
es = Elasticsearch(urls, timeout=timeout, **settings)
if not force_new:
# We don't need to rebuild the key here since we built it in
# the previous if block, so it's in the namespace. Having said
# that, this is a little ew.
_cached_elasticsearch[key] = es
return es
def split_field_action(s):
"""Takes a string and splits it into field and action
Example::
>>> split_field_action('foo__bar')
'foo', 'bar'
>>> split_field_action('foo')
'foo', None
"""
if '__' in s:
return s.rsplit('__', 1)
return s, None
def _process_facets(facets, flags):
rv = {}
for fieldname in facets:
facet_type = {'terms': {'field': fieldname}}
if flags.get('global_'):
facet_type['global'] = flags['global_']
if flags.get('size'):
facet_type['terms']['size'] = flags['size']
elif flags.get('filtered'):
# Note: This is an indicator that the facet_filter should
# get filled in later when we know all the filters.
facet_type['facet_filter'] = None
rv[fieldname] = facet_type
return rv
def _facet_counts(items):
"""Returns facet counts as dict.
Given the `items()` on the raw dictionary from Elasticsearch this processes
it and returns the counts keyed on the facet name provided in the original
query.
"""
facets = {}
for key, val in items:
if val['_type'] == 'terms':
facets[key] = [v for v in val['terms']]
elif val['_type'] == 'range':
facets[key] = [v for v in val['ranges']]
elif val['_type'] == 'histogram':
facets[key] = [v for v in val['entries']]
elif val['_type'] == 'date_histogram':
facets[key] = [v for v in val['entries']]
elif val['_type'] in ('filter', 'query', 'statistical'):
facets[key] = val
else:
raise InvalidFacetType(
'Facet _type "%s". key "%s" val "%r"' %
(val['_type'], key, val))
return facets
class F(object):
"""
Filter objects.
Makes it easier to create filters cumulatively using ``&`` (and),
``|`` (or) and ``~`` (not) operations.
For example::
f = F()
f &= F(price='Free')
f |= F(style='Mexican')
creates a filter "price = 'Free' or style = 'Mexican'".
"""
def __init__(self, **filters):
"""Creates an F"""
filters = filters.items()
if len(filters) > 1:
self.filters = [{'and': filters}]
else:
self.filters = filters
def __repr__(self):
return '<F {0}>'.format(self.filters)
def _combine(self, other, conn='and'):
"""
OR and AND will create a new F, with the filters from both F
objects combined with the connector `conn`.
"""
f = F()
self_filters = copy.deepcopy(self.filters)
other_filters = copy.deepcopy(other.filters)
if not self.filters:
f.filters = other_filters
elif not other.filters:
f.filters = self_filters
elif conn in self.filters[0]:
f.filters = self_filters
f.filters[0][conn].extend(other_filters)
elif conn in other.filters[0]:
f.filters = other_filters
f.filters[0][conn].extend(self_filters)
else:
f.filters = [{conn: self_filters + other_filters}]
return f
def __or__(self, other):
return self._combine(other, 'or')
def __and__(self, other):
return self._combine(other, 'and')
def __invert__(self):
f = F()
self_filters = copy.deepcopy(self.filters)
if len(self_filters) == 0:
f.filters = []
elif (len(self_filters) == 1
and isinstance(self_filters[0], dict)
and self_filters[0].get('not', {}).get('filter', {})):
f.filters = self_filters[0]['not']['filter']
else:
f.filters = [{'not': {'filter': self_filters}}]
return f
class Q(object):
"""
Query objects.
Makes it easier to create queries cumulatively.
If there's more than one query part, they're combined under a
BooleanQuery. By default, they're combined in the `must` clause.
You can combine two Q classes using the ``+`` operator. For
example::
q = Q()
q += Q(title__text='shoes')
q += Q(summary__text='shoes')
creates a BooleanQuery with two `must` clauses.
Example 2::
q = Q()
q += Q(title__text='shoes', should=True)
q += Q(summary__text='shoes')
q += Q(description__text='shoes', must=True)
creates a BooleanQuery with one `should` clause (title) and two
`must` clauses (summary and description).
"""
def __init__(self, **queries):
"""Creates a Q"""
self.should_q = []
self.must_q = []
self.must_not_q = []
should_flag = queries.pop('should', False)
must_flag = queries.pop('must', False)
must_not_flag = queries.pop('must_not', False)
# This (ab)uses the fact that booleans are integers.
if should_flag + must_flag + must_not_flag > 1:
raise InvalidFlagsError(
'Either should, must or must_not can be True, but not '
'more than one.')
if should_flag:
self.should_q.extend(queries.items())
elif must_not_flag:
self.must_not_q.extend(queries.items())
else:
self.must_q.extend(queries.items())
def __repr__(self):
return '<Q should={0} must={1} must_not={2}>'.format(
self.should_q, self.must_q, self.must_not_q)
def __add__(self, other):
q = Q()
# Note: LHS takes precedence over RHS
q.should_q = list(self.should_q)
q.must_q = list(self.must_q)
q.must_not_q = list(self.must_not_q)
q.should_q.extend(other.should_q)
q.must_q.extend(other.must_q)
q.must_not_q.extend(other.must_not_q)
return q
def __eq__(self, other):
return (sorted(self.should_q) == sorted(other.should_q)
and sorted(self.must_q) == sorted(other.must_q)
and sorted(self.must_not_q) == sorted(other.must_not_q))
def _boosted_value(name, action, key, value, boost):
"""Boost a value if we should in _process_queries"""
if boost is not None:
# Note: Most queries use 'value' for the key name except
# Text/Match queries which use 'query'. So we have to do some
# switcheroo for that.
value_key = 'query' if action in TEXTMATCH_ACTIONS else 'value'
return {name: {'boost': boost, value_key: value}}
return {name: value}
class PythonMixin(object):
"""Mixin that provides ES results fixing"""
def to_python(self, obj):
"""Converts strings in a data structure to Python types
It converts datetime-ish things to Python datetimes.
Override if you want something different.
:arg obj: Python datastructure
:returns: Python datastructure with strings converted to
Python types
.. Note::
This does the conversion in-place!
"""
if isinstance(obj, basestring):
if len(obj) == 26:
try:
return datetime.strptime(obj, '%Y-%m-%dT%H:%M:%S.%f')
except (TypeError, ValueError):
pass
elif len(obj) == 19:
try:
return datetime.strptime(obj, '%Y-%m-%dT%H:%M:%S')
except (TypeError, ValueError):
pass
elif len(obj) == 10:
try:
return datetime.strptime(obj, '%Y-%m-%d')
except (TypeError, ValueError):
pass
elif isinstance(obj, dict):
for key, val in obj.items():
obj[key] = self.to_python(val)
elif isinstance(obj, list):
return [self.to_python(item) for item in obj]
return obj
class S(PythonMixin):
"""Represents a lazy Elasticsearch Search API request.
The API for `S` takes inspiration from Django's QuerySet.
`S` can be either typed or untyped. An untyped `S` returns dict
results by default.
An `S` is lazy in the sense that it doesn't do an Elasticsearch
search request until it's forced to evaluate by either iterating
over it, calling ``.count``, doing ``len(s)``, or calling
``.facet_count``.
**Adding support for other queries**
You can add support for queries that S doesn't have support for by
subclassing S with a method called ``process_query_ACTION``. This
method takes a key, value and an action.
For example::
claass FunkyS(S):
def process_query_funkyquery(self, key, val, action):
return {'funkyquery': {'field': key, 'value': val}}
Then you can use that just like other actions::
s = FunkyS().query(Q(foo__funkyquery='bar'))
s = FunkyS().query(foo__funkyquery='bar')
Many Elasticsearch queries take other arguments. This is a good
way of using different arguments. For example, if you wanted
to write a handler for fuzzy for dates, you could do::
claass FunkyS(S):
def process_query_fuzzy(self, key, val, action):
# val here is a (value, min_similarity) tuple
return {
'funkyquery': {
key: {
'value': val[0],
'min_similarity': val[1]
}
}
}
Used::
s = FunkyS().query(created__fuzzy=(created_dte, '1d'))
**Adding support for other filters**
You can add support for filters that S doesn't have support for by
subclassing S with a method called ``process_filter_ACTION``.
This method takes a key, value and an action.
For example::
claass FunkyS(S):
def process_filter_funkyfilter(self, key, val, action):
return {'funkyfilter': {'field': key, 'value': val}}
Then you can use that just like other actions::
s = FunkyS().filter(F(foo__funkyfilter='bar'))
s = FunkyS().filter(foo__funkyfilter='bar')
"""
def __init__(self, type_=None):
"""Create and return an S.
:arg type_: class; the model that this S is based on
"""
self.type = type_
self.steps = []
self.start = 0
self.stop = None
self.as_list = self.as_dict = False
self.field_boosts = {}
self._results_cache = None
def __repr__(self):
try:
return '<S {0}>'.format(repr(self._build_query()))
except RuntimeError:
# This happens when you're debugging _build_query and try
# to repr the instance you're calling it on. Then that
# calls _build_query and ...
return repr(self.steps)
def _clone(self, next_step=None):
new = self.__class__(self.type)
new.steps = list(self.steps)
if next_step:
new.steps.append(next_step)
new.start = self.start
new.stop = self.stop
new.field_boosts = self.field_boosts.copy()
return new
def es(self, **settings):
"""Return a new S with specified Elasticsearch settings.
This allows you to configure the Elasticsearch object that gets
used to execute the search.
:arg settings: the settings you'd use to build the
Elasticsearch---same as what you'd pass to
:py:func:`get_es`.
"""
return self._clone(next_step=('es', settings))
def indexes(self, *indexes):
"""
Return a new S instance that will search specified indexes.
"""
return self._clone(next_step=('indexes', indexes))
def doctypes(self, *doctypes):
"""
Return a new S instance that will search specified doctypes.
.. Note::
Elasticsearch calls these "mapping types". It's the name
associated with a mapping.
"""
return self._clone(next_step=('doctypes', doctypes))
def explain(self, value=True):
"""
Return a new S instance with explain set.
"""
return self._clone(next_step=('explain', value))
def values_list(self, *fields):
"""
Return a new S instance that returns ListSearchResults.
:arg fields: the list of fields to have in the results.
With no arguments, returns a list of tuples of all the
data for that document.
With arguments, returns a list of tuples where the fields
in the tuple are in the order specified.
For example:
>>> list(S().values_list())
[(1, 'fred', 40), (2, 'brian', 30), (3, 'james', 45)]
>>> list(S().values_list('id', 'name'))
[(1, 'fred'), (2, 'brian'), (3, 'james')]
>>> list(S().values_list('name', 'id'))
[('fred', 1), ('brian', 2), ('james', 3)]
.. Note::
If you don't specify fields, the data comes back in an
arbitrary order. It's probably best to specify fields or
use ``values_dict``.
"""
return self._clone(next_step=('values_list', fields))
def values_dict(self, *fields):
"""
Return a new S instance that returns DictSearchResults.
:arg fields: the list of fields to have in the results.
With no arguments, this returns a list of dicts with all
the fields.
With arguments, it returns a list of dicts with the
specified fields.
For example:
>>> list(S().values_dict())
[{'id': 1, 'name': 'fred', 'age': 40}, ...]
>>> list(S().values_dict('id', 'name'))
[{'id': 1, 'name': 'fred'}, ...]
"""
return self._clone(next_step=('values_dict', fields))
def order_by(self, *fields):
"""
Return a new S instance with results ordered as specified
You can change the order search results by specified fields::
q = (S().query(title='trucks')
.order_by('title')
This orders search results by the `title` field in ascending
order.
If you want to sort by descending order, prepend a ``-``::
q = (S().query(title='trucks')
.order_by('-title')
You can also sort by the computed field ``_score`` or pass a dict as
a sort field in order to use more advanced sort options. Read the
Elasticsearch documentation for details.
.. Note::
Calling this again will overwrite previous ``.order_by()``
calls.
"""
return self._clone(next_step=('order_by', fields))
def query(self, *queries, **kw):
"""
Return a new S instance with query args combined with existing
set in a must boolean query.
:arg queries: instances of Q
:arg kw: queries in the form of ``field__action=value``
There are three special flags you can use:
* ``must=True``: Specifies that the queries and kw queries
**must match** in order for a document to be in the result.
If you don't specify a special flag, this is the default.
* ``should=True``: Specifies that the queries and kw queries
**should match** in order for a document to be in the result.
* ``must_not=True``: Specifies the queries and kw queries
**must not match** in order for a document to be in the result.
These flags work by putting those queries in the appropriate
clause of an Elasticsearch boolean query.
Examples:
>>> s = S().query(foo='bar')
>>> s = S().query(Q(foo='bar'))
>>> s = S().query(foo='bar', bat__text='baz')
>>> s = S().query(foo='bar', should=True)
>>> s = S().query(foo='bar', should=True).query(baz='bat', must=True)
Notes:
1. Don't specify multiple special flags, but if you did, `should`
takes precedence.
2. If you don't specify any, it defaults to `must`.
3. You can specify special flags in the
:py:class:`elasticutils.Q`, too. If you're building your
query incrementally, using :py:class:`elasticutils.Q` helps
a lot.
See the documentation on :py:class:`elasticutils.Q` for more
details on composing queries with Q.
See the documentation on :py:class:`elasticutils.S` for more
details on adding support for more query types.
"""
q = Q()
for query in queries:
q += query
if 'or_' in kw:
# Backwards compatibile with pre-0.7 version.
or_query = kw.pop('or_')
# or_query here is a dict of key/val pairs. or_ indicates
# they're in a should clause, so we generate the
# equivalent Q and then add it in.
or_query['should'] = True
q += Q(**or_query)
q += Q(**kw)
return self._clone(next_step=('query', q))
def query_raw(self, query):
"""
Return a new S instance with a query_raw.
:arg query: Python dict specifying the complete query to send
to Elasticsearch
Example::
S().query_raw({'match': {'title': 'example'}})
.. Note::
If there's a query_raw in your S, then that's your
query. All ``.query()``, ``.demote()``, ``.boost()`` and
anything else that affects the query clause is ignored.
"""
return self._clone(next_step=('query_raw', query))
def filter(self, *filters, **kw):
"""
Return a new S instance with filter args combined with
existing set with AND.
:arg filters: this will be instances of F
:arg kw: this will be in the form of ``field__action=value``
Examples:
>>> s = S().filter(foo='bar')
>>> s = S().filter(F(foo='bar'))
>>> s = S().filter(foo='bar', bat='baz')
>>> s = S().filter(foo='bar').filter(bat='baz')
By default, everything is combined using AND. If you provide
multiple filters in a single filter call, those are ANDed
together. If you provide multiple filters in multiple filter
calls, those are ANDed together.
If you want something different, use the F class which supports
``&`` (and), ``|`` (or) and ``~`` (not) operators. Then call
filter once with the resulting F instance.
See the documentation on :py:class:`elasticutils.F` for more
details on composing filters with F.
See the documentation on :py:class:`elasticutils.S` for more
details on adding support for new filter types.
"""
return self._clone(next_step=('filter', list(filters) + kw.items()))
def filter_raw(self, filter_):
"""
Return a new S instance with a filter_raw.
:arg filter_: Python dict specifying the complete filter to send
to Elasticsearch
Example::
S().filter_raw({'term': {'title': 'example'}})
.. Note::
If there's a filter_raw in your S, then that's your
filter. All ``.filter()`` and anything else that affects the
filter clause is ignored.
"""
return self._clone(next_step=('filter_raw', filter_))
def boost(self, **kw):
"""
Return a new S instance with field boosts.
ElasticUtils allows you to specify query-time field boosts
with ``.boost()``. It takes a set of arguments where the keys
are either field names or field name + ``__`` + field action.
Examples::
q = (S().query(title='taco trucks',
description__text='awesome')
.boost(title=4.0, description__text=2.0))
If the key is a field name, then the boost will apply to all
query bits that have that field name. For example::
q = (S().query(title='trucks',
title__prefix='trucks',
title__fuzzy='trucks')
.boost(title=4.0))
applies a 4.0 boost to all three query bits because all three
query bits are for the title field name.
If the key is a field name and field action, then the boost
will apply only to that field name and field action. For
example::
q = (S().query(title='trucks',
title__prefix='trucks',
title__fuzzy='trucks')
.boost(title__prefix=4.0))
will only apply the 4.0 boost to title__prefix.
Boosts are relative to one another and all boosts default to
1.0.
For example, if you had::
qs = (S().boost(title=4.0, summary=2.0)
.query(title__text=value,
summary__text=value,
content__text=value,
should=True))
``title__text`` would be boosted twice as much as
``summary__text`` and ``summary__text`` twice as much as
``content__text``.
"""
new = self._clone()
new.field_boosts.update(kw)
return new
def demote(self, amount_, *queries, **kw):
"""
Returns a new S instance with boosting query and demotion.
You can demote documents that match query criteria::
q = (S().query(title='trucks')
.demote(0.5, description__text='gross'))
q = (S().query(title='trucks')
.demote(0.5, Q(description__text='gross')))
This is implemented using the boosting query in
Elasticsearch. Anything you specify with ``.query()`` goes
into the positive section. The negative query and negative
boost portions are specified as the first and second arguments
to ``.demote()``.
.. Note::
Calling this again will overwrite previous ``.demote()``
calls.
"""
q = Q()
for query in queries:
q += query
q += Q(**kw)
return self._clone(next_step=('demote', (amount_, q)))
def facet(self, *args, **kw):
"""
Return a new S instance with facet args combined with existing
set.
:arg args: The list of facets to return.
Additional keyword options:
* ``size`` -- Maximum number of terms to return for each facet.
"""
return self._clone(next_step=('facet', (args, kw)))
def facet_raw(self, **kw):
"""
Return a new S instance with raw facet args combined with
existing set.
"""
return self._clone(next_step=('facet_raw', kw.items()))
def highlight(self, *fields, **kwargs):
"""Set highlight/excerpting with specified options.
:arg fields: The list of fields to highlight. If the field is
None, then the highlight is cleared.
Additional keyword options:
* ``pre_tags`` -- List of tags before highlighted portion
* ``post_tags`` -- List of tags after highlighted portion
Results will have a ``_highlight`` property which contains
the highlighted field excerpts.
For example::
q = (S().query(title__text='crash', content__text='crash')
.highlight('title', 'content'))
for result in q:
print result._highlight['title']
print result._highlight['content']
If you pass in ``None``, it will clear the highlight.
For example, this search won't highlight anything::
q = (S().query(title__text='crash')
.highlight('title') # highlights 'title' field
.highlight(None)) # clears highlight
.. Note::
Calling this again will overwrite previous ``.highlight()``
calls.
.. Note::
Make sure the fields you're highlighting are indexed
correctly. Read the Elasticsearch documentation for
details.
"""
return self._clone(next_step=('highlight', (fields, kwargs)))
def search_type(self, search_type):
"""Set Elasticsearch search type for distributed search behaviour.
:arg search_type: The search type to set.
The search type affects how much results are fetched from each shard,
and how are they then merged back. This can affect the accuracy of the
results and the execution speed.
For the list of possible values and additional documentation,
consult the Elasticsearch reference:
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-search-type.html
If called multiple times, the last search type will be in effect.
"""
return self._clone(next_step=('search_type', search_type))
def suggest(self, name, term, **kwargs):
"""
Set suggestion options.
:arg name: The name to use for the suggestions.
:arg term: The term to suggest similar looking terms for.
Additional keyword options:
* ``field`` -- The field to base suggestions upon, defaults to _all
Results will have a ``_suggestions`` property containing the
suggestions for all terms.
.. Note::
Calling this multiple times will add multiple suggest clauses to
the query.
"""
return self._clone(next_step=('suggest', (name, term, kwargs)))
def extra(self, **kw):
"""
Return a new S instance with extra args combined with existing
set.
"""
new = self._clone()
actions = ['values_list', 'values_dict', 'order_by', 'query',
'filter', 'facet']
for key, vals in kw.items():
assert key in actions
if hasattr(vals, 'items'):
new.steps.append((key, vals.items()))
else:
new.steps.append((key, vals))
return new
def __getitem__(self, k):
new = self._clone()
# TODO: validate numbers and ranges