forked from aparo/pyes
/
es.py
1860 lines (1562 loc) · 66.3 KB
/
es.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import with_statement
try:
# For Python >= 2.6
import json
except ImportError:
# For Python < 2.6 or people using a newer version of simplejson
import simplejson as json
import random
from datetime import date, datetime
from urllib import urlencode
from urlparse import urlunsplit
import base64
import time
from decimal import Decimal
from urllib import quote
import threading
import copy
from urlparse import urlparse
try:
from .connection import connect as thrift_connect
from .pyesthrift.ttypes import Method, RestRequest
thrift_enable = True
except ImportError:
from .fakettypes import Method, RestRequest
thrift_enable = False
from .connection_http import connect as http_connect
from . import logger
from .mappings import Mapper
from .convert_errors import raise_if_error
from .exceptions import (ElasticSearchException, IndexAlreadyExistsException,
IndexMissingException, InvalidQuery,
ReduceSearchPhaseException, VersionConflictEngineException,
BulkOperationException)
__all__ = ['ES', 'file_to_attachment', 'decode_json']
#
# models
#
class DotDict(dict):
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
return self.get(attr, None)
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __deepcopy__(self, memo):
return DotDict([(copy.deepcopy(k, memo), copy.deepcopy(v, memo)) for k, v in self.items()])
class ElasticSearchModel(DotDict):
def __init__(self, *args, **kwargs):
self._meta = DotDict()
self.__initialised = True
if len(args) == 2 and isinstance(args[0], ES):
item = args[1]
self.update(item.pop("_source", DotDict()))
self.update(item.pop("fields", {}))
self._meta = DotDict([(k.lstrip("_"), v) for k, v in item.items()])
self._meta.parent = self._meta.pop("_parent", None)
self._meta.connection = args[0]
else:
self.update(dict(*args, **kwargs))
def __setattr__(self, key, value):
if not self.__dict__.has_key(
'_ElasticSearchModel__initialised'): # this test allows attributes to be set in the __init__ method
return dict.__setattr__(self, key, value)
elif self.__dict__.has_key(key): # any normal attributes are handled normally
dict.__setattr__(self, key, value)
else:
self.__setitem__(key, value)
def get_meta(self):
return self._meta
def delete(self, bulk=False):
"""
Delete the object
"""
meta = self._meta
conn = meta['connection']
conn.delete(meta.index, meta.type, meta.id, bulk=bulk)
def save(self, bulk=False, id=None, parent=None, force=False):
"""
Save the object and returns id
"""
meta = self._meta
conn = meta['connection']
id = id or meta.get("id", None)
parent = parent or meta.get('parent', None)
version = meta.get('version', None)
if force:
version = None
res = conn.index(self,
meta.index, meta.type, id, parent=parent, bulk=bulk, version=version, force_insert=force)
if not bulk:
self._meta.id = res._id
self._meta.version = res._version
return res._id
return id
def reload(self):
meta = self._meta
conn = meta['connection']
res = conn.get(meta.index, meta.type, meta["id"])
self.update(res)
def get_id(self):
""" Force the object saveing to get an id"""
_id = self._meta.get("id", None)
if _id is None:
_id = self.save()
return _id
def get_bulk(self, create=False):
"""Return bulk code"""
result = []
op_type = "index"
if create:
op_type = "create"
meta = self._meta
cmd = {op_type: {"_index": meta.index, "_type": meta.type}}
if meta.parent:
cmd[op_type]['_parent'] = meta.parent
if meta.version:
cmd[op_type]['_version'] = meta.version
if meta.id:
cmd[op_type]['_id'] = meta.id
result.append(json.dumps(cmd, cls=self._meta.connection.encoder))
result.append("\n")
result.append(json.dumps(self, cls=self._meta.connection.encoder))
result.append("\n")
return ''.join(result)
def file_to_attachment(filename, filehandler=None):
"""
Convert a file to attachment
"""
if filehandler:
return {'_name': filename,
'content': base64.b64encode(filehandler.read())
}
with open(filename, 'rb') as _file:
return {'_name': filename,
'content': base64.b64encode(_file.read())
}
def _is_bulk_item_ok(item):
if "index" in item:
return "ok" in item["index"]
elif "delete" in item:
return "ok" in item["delete"]
else:
# unknown response type; be conservative
return False
def _raise_exception_if_bulk_item_failed(bulk_result):
errors = [item for item in bulk_result["items"] if not _is_bulk_item_ok(item)]
if len(errors) > 0:
raise BulkOperationException(errors, bulk_result)
return None
class ESJsonEncoder(json.JSONEncoder):
def default(self, value):
"""Convert rogue and mysterious data types.
Conversion notes:
- ``datetime.date`` and ``datetime.datetime`` objects are
converted into datetime strings.
"""
if isinstance(value, datetime):
return value.isoformat()
elif isinstance(value, date):
dt = datetime(value.year, value.month, value.day, 0, 0, 0)
return dt.isoformat()
elif isinstance(value, Decimal):
return float(str(value))
else:
# use no special encoding and hope for the best
return value
class ESJsonDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
kwargs['object_hook'] = self.dict_to_object
json.JSONDecoder.__init__(self, *args, **kwargs)
def string_to_datetime(self, obj):
"""Decode a datetime string to a datetime object
"""
if isinstance(obj, basestring) and len(obj) == 19:
try:
return datetime(*time.strptime("%Y-%m-%dT%H:%M:%S")[:6])
except:
pass
return obj
def dict_to_object(self, d):
"""
Decode datetime value from string to datetime
"""
for k, v in d.items():
if isinstance(v, basestring) and len(v) == 19:
try:
d[k] = datetime(*time.strptime(v, "%Y-%m-%dT%H:%M:%S")[:6])
except ValueError:
pass
elif isinstance(v, list):
d[k] = [self.string_to_datetime(elem) for elem in v]
return DotDict(d)
class BaseBulker(object):
"""
Base class to implement a bulker strategy
"""
def __init__(self, conn, bulk_size=400, raise_on_bulk_item_failure=False):
self.conn = conn
self._bulk_size = bulk_size
# protects bulk_data
self.bulk_lock = threading.RLock()
with self.bulk_lock:
self.bulk_data = []
self.raise_on_bulk_item_failure = raise_on_bulk_item_failure
def get_bulk_size(self):
"""
Get the current bulk_size
:return a int: the size of the bulk holder
"""
return self._bulk_size
def set_bulk_size(self, bulk_size):
"""
Set the bulk size
:param bulk_size the bulker size
"""
self._bulk_size = bulk_size
self.flush_bulk()
bulk_size = property(get_bulk_size, set_bulk_size)
def add(self, content):
raise NotImplementedError
def flush_bulk(self, forced=False):
raise NotImplementedError
class ListBulker(BaseBulker):
"""
A bulker that store data in a list
"""
def __init__(self, conn, bulk_size=400, raise_on_bulk_item_failure=False):
super(ListBulker, self).__init__(conn=conn, bulk_size=bulk_size,
raise_on_bulk_item_failure=raise_on_bulk_item_failure)
with self.bulk_lock:
self.bulk_data = []
def add(self, content):
with self.bulk_lock:
self.bulk_data.append(content)
def flush_bulk(self, forced=False):
with self.bulk_lock:
if forced or len(self.bulk_data) >= self.bulk_size:
batch = self.bulk_data
self.bulk_data = []
else:
return None
if len(batch) > 0:
bulk_result = self.conn._send_request("POST",
"/_bulk",
"\n".join(batch) + "\n")
if self.raise_on_bulk_item_failure:
_raise_exception_if_bulk_item_failed(bulk_result)
return bulk_result
class ES(object):
"""
ES connection object.
"""
#static to easy overwrite
encoder = ESJsonEncoder
decoder = ESJsonDecoder
def __init__(self, server="localhost:9200", timeout=30.0, bulk_size=400,
encoder=None, decoder=None,
max_retries=3,
default_indices=None,
default_types=None,
dump_curl=False,
model=ElasticSearchModel,
basic_auth=None,
raise_on_bulk_item_failure=False,
document_object_field=None,
bulker_class=ListBulker):
"""
Init a es object.
Servers can be defined in different forms:
- host:port with protocol guess (i.e. 127.0.0.1:9200 protocol -> http
127.0.0.1:9500 protocol -> thrift )
- type://host:port (i.e. http://127.0.0.1:9200 https://127.0.0.1:9200 thrift://127.0.0.1:9500)
- (type, host, port) (i.e. tuple ("http", "127.0.0.1", "9200") ("https", "127.0.0.1", "9200")
("thrift", "127.0.0.1", "9500")). This is the prefered form.
:param server: the server name, it can be a list of servers.
:param timeout: timeout for a call
:param bulk_size: size of bulk operation
:param encoder: tojson encoder
:param max_retries: number of max retries for server if a server is down
:param basic_auth: Dictionary with 'username' and 'password' keys for HTTP Basic Auth.
:param model: used to objectify the dictinary. If None, the raw dict is returned.
:param dump_curl: If truthy, this will dump every query to a curl file. If
this is set to a string value, it names the file that output is sent
to. Otherwise, it should be set to an object with a write() method,
which output will be written to.
:param raise_on_bulk_item_failure: raises an exception if an item in a
bulk operation fails
:param document_object_field: a class to use as base document field in mapper
"""
self.timeout = timeout
self.default_indices = default_indices or ["_all"]
self.max_retries = max_retries
self.cluster = None
self.debug_dump = False
self.cluster_name = "undefined"
self.basic_auth = basic_auth
self.connection = None
self._mappings = None
self.document_object_field = document_object_field
if model is None:
model = lambda connection, model: model
self.model = model
if dump_curl:
if isinstance(dump_curl, basestring):
self.dump_curl = open(dump_curl, "wb")
elif hasattr(dump_curl, 'write'):
self.dump_curl = dump_curl
else:
raise TypeError("dump_curl parameter must be supplied with a "
"string or an object with a write() method")
else:
self.dump_curl = None
#used in bulk
self._bulk_size = bulk_size #size of the bulk
self.bulker = bulker_class(self, bulk_size=bulk_size, raise_on_bulk_item_failure=raise_on_bulk_item_failure)
self.bulker_class = bulker_class
self._raise_on_bulk_item_failure = raise_on_bulk_item_failure
self.info = {} #info about the current server
if encoder:
self.encoder = encoder
if decoder:
self.decoder = decoder
if isinstance(server, (str, unicode)):
self.servers = [server]
elif isinstance(server, tuple):
self.servers = [server]
else:
self.servers = server
self.default_types = default_types or []
#check the servers variable
self._check_servers()
#init connections
self._init_connection()
def __del__(self):
"""
Destructor
"""
# Don't bother getting the lock
if self.bulker:
# It's not safe to rely on the destructor to flush the queue:
# the Python documentation explicitly states "It is not guaranteed
# that __del__() methods are called for objects that still exist "
# when the interpreter exits."
logger.error("pyes object %s is being destroyed, but bulk "
"operations have not been flushed. Call force_bulk()!",
self)
# Do our best to save the client anyway...
self.bulker.force_bulk()
def _check_servers(self):
"""Check the servers variable and convert in a valid tuple form"""
new_servers = []
def check_format(server):
if server.scheme not in ["thrift", "http", "https"]:
raise RuntimeError("Unable to recognize protocol: \"%s\"" % _type)
if server.scheme == "thrift":
if not thrift_enable:
raise RuntimeError("If you want to use thrift, please install thrift. \"pip install thrift\"")
if server.port is None:
raise RuntimeError("If you want to use thrift, please provide a port number")
new_servers.append(server)
for server in self.servers:
if isinstance(server, (tuple, list)):
if len(list(server)) != 3:
raise RuntimeError("Invalid server definition: \"%s\"" % server)
_type, host, port = server
server = urlparse('%s://%s:%s' % (_type, host, port))
check_format(server)
elif isinstance(server, basestring):
if server.startswith(("thrift:", "http:", "https:")):
server = urlparse(server)
check_format(server)
continue
else:
tokens = [t for t in server.split(":") if t.strip()]
if len(tokens) == 2:
host = tokens[0]
try:
port = int(tokens[1])
except ValueError:
raise RuntimeError("Invalid port: \"%s\"" % port)
if 9200 <= port <= 9299:
_type = "http"
elif 9500 <= port <= 9599:
_type = "thrift"
else:
raise RuntimeError("Unable to recognize port-type: \"%s\"" % port)
server = urlparse('%s://%s:%s' % (_type, host, port))
check_format(server)
self.servers = new_servers
def _init_connection(self):
"""
Create initial connection pool
"""
#detect connectiontype
if not self.servers:
raise RuntimeError("No server defined")
server = random.choice(self.servers)
if server.scheme in ["http", "https"]:
self.connection = http_connect(
filter(lambda server: server.scheme in ["http", "https"], self.servers),
timeout=self.timeout
,
basic_auth=self.basic_auth
,
max_retries=self.max_retries)
return
elif server.scheme == "thrift":
self.connection = thrift_connect(
filter(lambda server: server.scheme == "thrift", self.servers),
timeout=self.timeout
,
max_retries=self.max_retries)
def _discovery(self):
"""
Find other servers asking nodes to given server
"""
data = self.cluster_nodes()
self.cluster_name = data["cluster_name"]
for _, nodedata in data["nodes"].items():
server = nodedata['http_address'].replace("]", "").replace("inet[", "http:/")
if server not in self.servers:
self.servers.append(server)
self._init_connection()
return self.servers
def _get_bulk_size(self):
"""
Get the current bulk_size
:return a int: the size of the bulk holder
"""
return self._bulk_size
def _set_bulk_size(self, bulk_size):
"""
Set the bulk size
:param bulk_size the bulker size
"""
self._bulk_size = bulk_size
self.bulker.bulk_size = bulk_size
bulk_size = property(_get_bulk_size, _set_bulk_size)
def _get_raise_on_bulk_item_failure(self):
"""
Get the raise_on_bulk_item_failure status
:return a bool: the status of raise_on_bulk_item_failure
"""
return self._bulk_size
def _set_raise_on_bulk_item_failure(self, raise_on_bulk_item_failure):
"""
Set the raise_on_bulk_item_failure parameter
:param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure
"""
self._raise_on_bulk_item_failure = raise_on_bulk_item_failure
self.bulker.raise_on_bulk_item_failure = raise_on_bulk_item_failure
raise_on_bulk_item_failure = property(_get_raise_on_bulk_item_failure, _set_raise_on_bulk_item_failure)
def _send_request(self, method, path, body=None, params=None, headers=None, raw=False):
if params is None:
params = {}
if headers is None:
headers = {}
# prepare the request
if not path.startswith("/"):
path = "/" + path
if not self.connection:
self._init_connection()
if body:
if not isinstance(body, dict) and hasattr(body, "as_dict"):
body = body.as_dict()
if isinstance(body, dict):
body = json.dumps(body, cls=self.encoder)
else:
body = ""
request = RestRequest(method=Method._NAMES_TO_VALUES[method.upper()],
uri=path, parameters=params, headers=headers, body=body)
if self.dump_curl is not None:
self._dump_curl_request(request)
# execute the request
response = self.connection.execute(request)
if method == "HEAD":
if response.status != 200:
return False
return True
# handle the response
try:
decoded = json.loads(response.body, cls=self.decoder)
except ValueError:
try:
decoded = json.loads(response.body, cls=ESJsonDecoder)
except ValueError:
# The only known place where we get back a body which can't be
# parsed as JSON is when no handler is found for a request URI.
# In this case, the body is actually a good message to return
# in the exception.
raise ElasticSearchException(response.body, response.status, response.body)
if response.status != 200:
raise_if_error(response.status, decoded)
if not raw and isinstance(decoded, dict):
decoded = DotDict(decoded)
return decoded
def _make_path(self, path_components):
"""
Smush together the path components. Empty components will be ignored.
"""
path_components = [quote(str(component), "") for component in path_components if component]
path = '/'.join(path_components)
if not path.startswith('/'):
path = '/' + path
return path
def _query_call(self, query_type, query, indices=None, doc_types=None, **query_params):
"""
This can be used for search and count calls.
These are identical api calls, except for the type of query.
"""
querystring_args = query_params
indices = self._validate_indices(indices)
if doc_types is None:
doc_types = self.default_types
if isinstance(doc_types, basestring):
doc_types = [doc_types]
body = query
path = self._make_path([','.join(indices), ','.join(doc_types), query_type])
return self._send_request('GET', path, body, params=querystring_args)
def _validate_indices(self, indices=None):
"""Return a valid list of indices.
`indices` may be a string or a list of strings.
If `indices` is not supplied, returns the default_indices.
"""
indices = indices or self.default_indices
if isinstance(indices, basestring):
indices = [indices]
return indices
def _dump_curl_request(self, request):
print >> self.dump_curl, "# [%s]" % datetime.now().isoformat()
params = {'pretty': 'true'}
params.update(request.parameters)
method = Method._VALUES_TO_NAMES[request.method]
server = self.servers[0]
if isinstance(server, tuple):
if len(server) == 2:
server = "%s:%s" % (server[0], server[1])
elif len(server) == 3:
server = "%s:%s" % (server[1], server[2])
url = urlunsplit(('http', server, request.uri, urlencode(params), ''))
curl_cmd = "curl -X%s '%s'" % (method, url)
if request.body:
curl_cmd += " -d '%s'" % request.body
print >> self.dump_curl, curl_cmd
def _get_default_indices(self):
return self._default_indices
def _set_default_indices(self, default_indices):
if default_indices is not None:
default_indices = self._validate_indices(default_indices)
self._default_indices = default_indices
default_indices = property(_get_default_indices, _set_default_indices)
del _get_default_indices, _set_default_indices
@property
def mappings(self):
if self._mappings is None:
self._mappings = Mapper(self.get_mapping(indices=["_all"]), connection=self,
document_object_field=self.document_object_field)
return self._mappings
#---- Admin commands
def status(self, indices=None):
"""
Retrieve the status of one or more indices
"""
indices = self._validate_indices(indices)
path = self._make_path([','.join(indices), '_status'])
return self._send_request('GET', path)
def aliases(self, indices=None):
"""
Retrieve the aliases of one or more indices
"""
if not indices:
indices = ["_all"]
path = self._make_path([','.join(indices), '_aliases'])
return self._send_request('GET', path)
def create_bulker(self):
"""
Create a bulker object and return it to allow to manage custom bulk policies
"""
return self.bulker_class(self, bulk_size=self.bulk_size,
raise_on_bulk_item_failure=self.raise_on_bulk_item_failure)
def create_index(self, index, settings=None):
"""
Creates an index with optional settings.
Settings must be a dictionary which will be converted to JSON.
Elasticsearch also accepts yaml, but we are only passing JSON.
"""
return self._send_request('PUT', index, settings)
def create_index_if_missing(self, index, settings=None):
"""Creates an index if it doesn't already exist.
If supplied, settings must be a dictionary.
"""
try:
return self.create_index(index, settings)
except IndexAlreadyExistsException, e:
return e.result
def delete_index(self, index):
"""Deletes an index.
"""
return self._send_request('DELETE', index)
def exists_index(self, index):
"""
Check if an index exists.
"""
return self._send_request('HEAD', index)
def delete_index_if_exists(self, index):
"""Deletes an index if it exists.
"""
if self.exists_index(index):
return self.delete_index(index)
def get_indices(self, include_aliases=False):
"""Get a dict holding an entry for each index which exists.
If include_alises is True, the dict will also contain entries for
aliases.
The key for each entry in the dict is the index or alias name. The
value is a dict holding the following properties:
- num_docs: Number of documents in the index or alias.
- alias_for: Only present for an alias: holds a list of indices which
this is an alias for.
"""
state = self.cluster_state()
status = self.status()
result = {}
indices_status = status['indices']
indices_metadata = state['metadata']['indices']
for index in sorted(indices_status.keys()):
info = indices_status[index]
metadata = indices_metadata[index]
num_docs = info['docs']['num_docs']
result[index] = dict(num_docs=num_docs)
if not include_aliases:
continue
for alias in metadata.get('aliases', []):
try:
alias_obj = result[alias]
except KeyError:
alias_obj = {}
result[alias] = alias_obj
alias_obj['num_docs'] = alias_obj.get('num_docs', 0) + num_docs
try:
alias_obj['alias_for'].append(index)
except KeyError:
alias_obj['alias_for'] = [index]
return result
def get_closed_indices(self):
"""
Get all closed indices.
"""
state = self.cluster_state()
status = self.status()
indices_metadata = set(state['metadata']['indices'].keys())
indices_status = set(status['indices'].keys())
return indices_metadata.difference(indices_status)
def get_alias(self, alias):
"""Get the index or indices pointed to by a given alias.
Raises IndexMissingException if the alias does not exist.
Otherwise, returns a list of index names.
"""
status = self.status([alias])
return status['indices'].keys()
def change_aliases(self, commands):
"""Change the aliases stored.
`commands` is a list of 3-tuples; (command, index, alias), where
`command` is one of "add" or "remove", and `index` and `alias` are the
index and alias to add or remove.
"""
body = {
'actions': [
{command: dict(index=index, alias=alias)}
for (command, index, alias) in commands
]
}
return self._send_request('POST', "_aliases", body)
def add_alias(self, alias, indices=None):
"""Add an alias to point to a set of indices.
"""
indices = self._validate_indices(indices)
return self.change_aliases(['add', index, alias]
for index in indices)
def delete_alias(self, alias, indices=None):
"""Delete an alias.
The specified index or indices are deleted from the alias, if they are
in it to start with. This won't report an error even if the indices
aren't present in the alias.
"""
indices = self._validate_indices(indices)
return self.change_aliases(['remove', index, alias]
for index in indices)
def set_alias(self, alias, indices=None):
"""Set an alias.
This handles removing the old list of indices pointed to by the alias.
Warning: there is a race condition in the implementation of this
function - if another client modifies the indices which this alias
points to during this call, the old value of the alias may not be
correctly set.
"""
indices = self._validate_indices(indices)
try:
old_indices = self.get_alias(alias)
except IndexMissingException:
old_indices = []
commands = [['remove', index, alias] for index in old_indices]
commands.extend([['add', index, alias] for index in indices])
if len(commands) > 0:
return self.change_aliases(commands)
def close_index(self, index):
"""
Close an index.
"""
return self._send_request('POST', "/%s/_close" % index)
def open_index(self, index):
"""
Open an index.
"""
return self._send_request('POST', "/%s/_open" % index)
def flush(self, indices=None, refresh=None):
"""
Flushes one or more indices (clear memory)
"""
self.force_bulk()
indices = self._validate_indices(indices)
path = self._make_path([','.join(indices), '_flush'])
args = {}
if refresh is not None:
args['refresh'] = refresh
return self._send_request('POST', path, params=args)
def refresh(self, indices=None, timesleep=None):
"""
Refresh one or more indices
timesleep: seconds to wait
"""
self.force_bulk()
indices = self._validate_indices(indices)
path = self._make_path([','.join(indices), '_refresh'])
result = self._send_request('POST', path)
if timesleep:
time.sleep(timesleep)
self.cluster_health(wait_for_status='green')
return result
def optimize(self, indices=None,
wait_for_merge=False,
max_num_segments=None,
only_expunge_deletes=False,
refresh=True,
flush=True):
"""Optimize one or more indices.
`indices` is the list of indices to optimise. If not supplied, or
"_all", all indices are optimised.
`wait_for_merge` (boolean): If True, the operation will not return
until the merge has been completed. Defaults to False.
`max_num_segments` (integer): The number of segments to optimize to. To
fully optimize the index, set it to 1. Defaults to half the number
configured by the merge policy (which in turn defaults to 10).
`only_expunge_deletes` (boolean): Should the optimize process only
expunge segments with deletes in it. In Lucene, a document is not
deleted from a segment, just marked as deleted. During a merge process
of segments, a new segment is created that does have those deletes.
This flag allow to only merge segments that have deletes. Defaults to
false.
`refresh` (boolean): Should a refresh be performed after the optimize.
Defaults to true.
`flush` (boolean): Should a flush be performed after the optimize.
Defaults to true.
"""
indices = self._validate_indices(indices)
path = self._make_path([','.join(indices), '_optimize'])
params = dict(
wait_for_merge=wait_for_merge,
only_expunge_deletes=only_expunge_deletes,
refresh=refresh,
flush=flush,
)
if max_num_segments is not None:
params['max_num_segments'] = max_num_segments
result = self._send_request('POST', path, params=params)
return result
def analyze(self, text, index=None, analyzer=None, tokenizer=None, filters=None, field=None):
"""
Performs the analysis process on a text and return the tokens breakdown of the text
"""
if filters is None:
filters = []
argsets = 0
args = {}
if analyzer:
args['analyzer'] = analyzer
argsets += 1
if tokenizer or filters:
if tokenizer:
args['tokenizer'] = tokenizer
if filters:
args['filters'] = ','.join(filters)
argsets += 1
if field:
args['field'] = field
argsets += 1
if argsets > 1:
raise ValueError('Argument conflict: Speficy either analyzer, tokenizer/filters or field')
if field and index is None:
raise ValueError('field can only be specified with an index')
path = self._make_path([index, '_analyze'])
return self._send_request('POST', path, text, args)
def gateway_snapshot(self, indices=None):
"""
Gateway snapshot one or more indices
:param indices: a list of indices or None for default configured.
"""
indices = self._validate_indices(indices)
path = self._make_path([','.join(indices), '_gateway', 'snapshot'])
return self._send_request('POST', path)
def put_mapping(self, doc_type=None, mapping=None, indices=None):
"""
Register specific mapping definition for a specific type against one or more indices.
"""
indices = self._validate_indices(indices)
if mapping is None:
mapping = {}
if hasattr(mapping, "to_json"):
mapping = mapping.to_json()
if hasattr(mapping, "as_dict"):
mapping = mapping.as_dict()
if doc_type:
path = self._make_path([','.join(indices), doc_type, "_mapping"])
if doc_type not in mapping:
mapping = {doc_type: mapping}
else:
path = self._make_path([','.join(indices), "_mapping"])
return self._send_request('PUT', path, mapping)