-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathcollection.py
3652 lines (3186 loc) · 138 KB
/
collection.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
__all__ = ["StandardCollection", "VertexCollection", "EdgeCollection"]
from numbers import Number
from typing import List, Optional, Sequence, Tuple, Union
from warnings import warn
from arango.api import ApiGroup
from arango.connection import Connection
from arango.cursor import Cursor
from arango.exceptions import (
ArangoServerError,
CollectionChecksumError,
CollectionCompactError,
CollectionConfigureError,
CollectionInformationError,
CollectionLoadError,
CollectionPropertiesError,
CollectionRecalculateCountError,
CollectionRenameError,
CollectionResponsibleShardError,
CollectionRevisionError,
CollectionShardsError,
CollectionStatisticsError,
CollectionTruncateError,
CollectionUnloadError,
DocumentCountError,
DocumentDeleteError,
DocumentGetError,
DocumentIDsError,
DocumentInError,
DocumentInsertError,
DocumentKeysError,
DocumentParseError,
DocumentReplaceError,
DocumentRevisionError,
DocumentUpdateError,
EdgeListError,
IndexCreateError,
IndexDeleteError,
IndexGetError,
IndexListError,
IndexLoadError,
IndexMissingError,
)
from arango.executor import ApiExecutor
from arango.formatter import format_collection, format_edge, format_index, format_vertex
from arango.request import Request
from arango.response import Response
from arango.result import Result
from arango.typings import Fields, Headers, Json, Jsons, Params
from arango.utils import (
build_filter_conditions,
build_sort_expression,
get_batches,
get_doc_id,
is_none_or_bool,
is_none_or_int,
is_none_or_str,
validate_sort_parameters,
)
class Collection(ApiGroup):
"""Base class for collection API wrappers.
:param connection: HTTP connection.
:param executor: API executor.
:param name: Collection name.
"""
types = {2: "document", 3: "edge"}
statuses = {
1: "new",
2: "unloaded",
3: "loaded",
4: "unloading",
5: "deleted",
6: "loading",
}
def __init__(
self, connection: Connection, executor: ApiExecutor, name: str
) -> None:
super().__init__(connection, executor)
self._name = name
self._id_prefix = name + "/"
def __iter__(self) -> Result[Cursor]:
return self.all()
def __len__(self) -> Result[int]:
return self.count()
def __contains__(self, document: Union[str, Json]) -> Result[bool]:
return self.has(document, check_rev=False)
def _get_status_text(self, code: int) -> str: # pragma: no cover
"""Return the collection status text.
:param code: Collection status code.
:type code: int
:return: Collection status text or None if code is None.
:rtype: str
"""
return None if code is None else self.statuses[code]
def _validate_id(self, doc_id: str) -> str:
"""Check the collection name in the document ID.
:param doc_id: Document ID.
:type doc_id: str
:return: Verified document ID.
:rtype: str
:raise arango.exceptions.DocumentParseError: On bad collection name.
"""
if not doc_id.startswith(self._id_prefix):
raise DocumentParseError(f'bad collection name in document ID "{doc_id}"')
return doc_id
def _extract_id(self, body: Json) -> str:
"""Extract the document ID from document body.
:param body: Document body.
:type body: dict
:return: Document ID.
:rtype: str
:raise arango.exceptions.DocumentParseError: On missing ID and key.
"""
try:
if "_id" in body:
return self._validate_id(body["_id"])
else:
key: str = body["_key"]
return self._id_prefix + key
except KeyError:
raise DocumentParseError('field "_key" or "_id" required')
def _prep_from_body(self, document: Json, check_rev: bool) -> Tuple[str, Headers]:
"""Prepare document ID and request headers.
:param document: Document body.
:type document: dict
:param check_rev: Whether to check the revision.
:type check_rev: bool
:return: Document ID and request headers.
:rtype: (str, dict)
"""
doc_id = self._extract_id(document)
if not check_rev or "_rev" not in document:
return doc_id, {}
return doc_id, {"If-Match": document["_rev"]}
def _prep_from_doc(
self, document: Union[str, Json], rev: Optional[str], check_rev: bool
) -> Tuple[str, Union[str, Json], Json]:
"""Prepare document ID, body and request headers.
:param document: Document ID, key or body.
:type document: str | dict
:param rev: Document revision or None.
:type rev: str | None
:param check_rev: Whether to check the revision.
:type check_rev: bool
:return: Document ID, body and request headers.
:rtype: (str, str | body, dict)
"""
if isinstance(document, dict):
doc_id = self._extract_id(document)
rev = rev or document.get("_rev")
if not check_rev or rev is None:
return doc_id, doc_id, {}
else:
return doc_id, doc_id, {"If-Match": rev}
else:
if "/" in document:
doc_id = self._validate_id(document)
else:
doc_id = self._id_prefix + document
if not check_rev or rev is None:
return doc_id, doc_id, {}
else:
return doc_id, doc_id, {"If-Match": rev}
def _ensure_key_in_body(self, body: Json) -> Json:
"""Return the document body with "_key" field populated.
:param body: Document body.
:type body: dict
:return: Document body with "_key" field.
:rtype: dict
:raise arango.exceptions.DocumentParseError: On missing ID and key.
"""
if "_key" in body:
return body
elif "_id" in body:
doc_id = self._validate_id(body["_id"])
body = body.copy()
body["_key"] = doc_id[len(self._id_prefix) :]
return body
raise DocumentParseError('field "_key" or "_id" required')
def _ensure_key_from_id(self, body: Json) -> Json:
"""Return the body with "_key" field if it has "_id" field.
:param body: Document body.
:type body: dict
:return: Document body with "_key" field if it has "_id" field.
:rtype: dict
"""
if "_id" in body and "_key" not in body:
doc_id = self._validate_id(body["_id"])
body = body.copy()
body["_key"] = doc_id[len(self._id_prefix) :]
return body
@property
def name(self) -> str:
"""Return collection name.
:return: Collection name.
:rtype: str
"""
return self._name
def recalculate_count(self) -> Result[bool]:
"""Recalculate the document count.
:return: True if recalculation was successful.
:rtype: bool
:raise arango.exceptions.CollectionRecalculateCountError: If operation fails.
"""
request = Request(
method="put",
endpoint=f"/_api/collection/{self.name}/recalculateCount",
)
def response_handler(resp: Response) -> bool:
if resp.is_success:
return True
raise CollectionRecalculateCountError(resp, request)
return self._execute(request, response_handler)
def responsible_shard(self, document: Json) -> Result[str]: # pragma: no cover
"""Return the ID of the shard responsible for given **document**.
If the document does not exist, return the shard that would be
responsible.
:return: Shard ID
:rtype: str
"""
request = Request(
method="put",
endpoint=f"/_api/collection/{self.name}/responsibleShard",
data=document,
read=self.name,
)
def response_handler(resp: Response) -> str:
if resp.is_success:
return str(resp.body["shardId"])
raise CollectionResponsibleShardError(resp, request)
return self._execute(request, response_handler)
def rename(self, new_name: str) -> Result[bool]:
"""Rename the collection.
Renames may not be reflected immediately in async execution, batch
execution or transactions. It is recommended to initialize new API
wrappers after a rename.
:param new_name: New collection name.
:type new_name: str
:return: True if collection was renamed successfully.
:rtype: bool
:raise arango.exceptions.CollectionRenameError: If rename fails.
"""
request = Request(
method="put",
endpoint=f"/_api/collection/{self.name}/rename",
data={"name": new_name},
)
def response_handler(resp: Response) -> bool:
if not resp.is_success:
raise CollectionRenameError(resp, request)
self._name = new_name
self._id_prefix = new_name + "/"
return True
return self._execute(request, response_handler)
def properties(self) -> Result[Json]:
"""Return collection properties.
:return: Collection properties.
:rtype: dict
:raise arango.exceptions.CollectionPropertiesError: If retrieval fails.
"""
request = Request(
method="get",
endpoint=f"/_api/collection/{self.name}/properties",
read=self.name,
)
def response_handler(resp: Response) -> Json:
if resp.is_success:
return format_collection(resp.body)
raise CollectionPropertiesError(resp, request)
return self._execute(request, response_handler)
def shards(self, details: bool = False) -> Result[Json]:
"""Return collection shards and properties.
Available only in a cluster setup.
:param details: Include responsible servers for each shard.
:type details: bool
:return: Collection shards and properties.
:rtype: dict
:raise arango.exceptions.CollectionShardsError: If retrieval fails.
"""
request = Request(
method="get",
endpoint=f"/_api/collection/{self.name}/shards",
params={"details": details},
read=self.name,
)
def response_handler(resp: Response) -> Json:
if resp.is_success:
return format_collection(resp.body)
raise CollectionShardsError(resp, request)
return self._execute(request, response_handler)
def info(self) -> Result[Json]:
"""Return the collection information.
:return: Information about the collection.
:rtype: dict
:raise arango.exceptions.CollectionInformationError: If retrieval fails.
"""
request = Request(
method="get",
endpoint=f"/_api/collection/{self.name}",
read=self.name,
)
def response_handler(resp: Response) -> Json:
if resp.is_success:
return format_collection(resp.body)
raise CollectionInformationError(resp, request)
return self._execute(request, response_handler)
def configure(
self,
sync: Optional[bool] = None,
schema: Optional[Json] = None,
replication_factor: Optional[int] = None,
write_concern: Optional[int] = None,
computed_values: Optional[Jsons] = None,
) -> Result[Json]:
"""Configure collection properties.
:param sync: Block until operations are synchronized to disk.
:type sync: bool | None
:param schema: document schema for validation of objects.
:type schema: dict
:param replication_factor: Number of copies of each shard on different
servers in a cluster. Allowed values are 1 (only one copy is kept
and no synchronous replication), and n (n-1 replicas are kept and
any two copies are replicated across servers synchronously, meaning
every write to the master is copied to all slaves before operation
is reported successful).
:type replication_factor: int
:param write_concern: Write concern for the collection. Determines how
many copies of each shard are required to be in sync on different
DBServers. If there are less than these many copies in the cluster
a shard will refuse to write. Writes to shards with enough
up-to-date copies will succeed at the same time. The value of this
parameter cannot be larger than that of **replication_factor**.
Default value is 1. Used for clusters only.
:type write_concern: int
:return: New collection properties.
:param computed_values: Define expressions on the collection level that
run on inserts, modifications, or both.
:type computed_values: dict | None
:rtype: dict
:raise arango.exceptions.CollectionConfigureError: If operation fails.
"""
data: Json = {}
if sync is not None:
data["waitForSync"] = sync
if schema is not None:
data["schema"] = schema
if replication_factor is not None:
data["replicationFactor"] = replication_factor
if write_concern is not None:
data["writeConcern"] = write_concern
if computed_values is not None:
data["computedValues"] = computed_values
request = Request(
method="put",
endpoint=f"/_api/collection/{self.name}/properties",
data=data,
)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise CollectionConfigureError(resp, request)
return format_collection(resp.body)
return self._execute(request, response_handler)
def statistics(self) -> Result[Json]:
"""Return collection statistics.
:return: Collection statistics.
:rtype: dict
:raise arango.exceptions.CollectionStatisticsError: If retrieval fails.
"""
request = Request(
method="get",
endpoint=f"/_api/collection/{self.name}/figures",
read=self.name,
)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise CollectionStatisticsError(resp, request)
stats: Json = resp.body.get("figures", resp.body)
if "documentReferences" in stats: # pragma: no cover
stats["document_refs"] = stats.pop("documentReferences")
if "lastTick" in stats: # pragma: no cover
stats["last_tick"] = stats.pop("lastTick")
if "waitingFor" in stats: # pragma: no cover
stats["waiting_for"] = stats.pop("waitingFor")
if "documentsSize" in stats: # pragma: no cover
stats["documents_size"] = stats.pop("documentsSize")
if "cacheInUse" in stats: # pragma: no cover
stats["cache_in_use"] = stats.pop("cacheInUse")
if "cacheSize" in stats: # pragma: no cover
stats["cache_size"] = stats.pop("cacheSize")
if "cacheUsage" in stats: # pragma: no cover
stats["cache_usage"] = stats.pop("cacheUsage")
if "uncollectedLogfileEntries" in stats: # pragma: no cover
stats["uncollected_logfile_entries"] = stats.pop(
"uncollectedLogfileEntries"
)
return stats
return self._execute(request, response_handler)
def revision(self) -> Result[str]:
"""Return collection revision.
:return: Collection revision.
:rtype: str
:raise arango.exceptions.CollectionRevisionError: If retrieval fails.
"""
request = Request(
method="get",
endpoint=f"/_api/collection/{self.name}/revision",
read=self.name,
)
def response_handler(resp: Response) -> str:
if resp.is_success:
return str(resp.body["revision"])
raise CollectionRevisionError(resp, request)
return self._execute(request, response_handler)
def checksum(self, with_rev: bool = False, with_data: bool = False) -> Result[str]:
"""Return collection checksum.
:param with_rev: Include document revisions in checksum calculation.
:type with_rev: bool
:param with_data: Include document data in checksum calculation.
:type with_data: bool
:return: Collection checksum.
:rtype: str
:raise arango.exceptions.CollectionChecksumError: If retrieval fails.
"""
request = Request(
method="get",
endpoint=f"/_api/collection/{self.name}/checksum",
params={"withRevision": with_rev, "withData": with_data},
)
def response_handler(resp: Response) -> str:
if resp.is_success:
return str(resp.body["checksum"])
raise CollectionChecksumError(resp, request)
return self._execute(request, response_handler)
def compact(self) -> Result[Json]:
"""Compact a collection.
Compacts the data of a collection in order to reclaim disk space.
The operation will compact the document and index data by rewriting the
underlying .sst files and only keeping the relevant entries.
Under normal circumstances, running a compact operation is not necessary, as
the collection data will eventually get compacted anyway. However, in some
situations, e.g. after running lots of update/replace or remove operations,
the disk data for a collection may contain a lot of outdated data for which the
space shall be reclaimed. In this case the compaction operation can be used.
:return: Collection compact.
:rtype: dict
:raise arango.exceptions.CollectionCompactError: If retrieval fails.
"""
request = Request(
method="put",
endpoint=f"/_api/collection/{self.name}/compact",
)
def response_handler(resp: Response) -> Json:
if resp.is_success:
return format_collection(resp.body)
raise CollectionCompactError(resp, request)
return self._execute(request, response_handler)
def load(self) -> Result[bool]:
"""Load the collection into memory.
:return: True if collection was loaded successfully.
:rtype: bool
:raise arango.exceptions.CollectionLoadError: If operation fails.
"""
request = Request(method="put", endpoint=f"/_api/collection/{self.name}/load")
def response_handler(resp: Response) -> bool:
if not resp.is_success:
raise CollectionLoadError(resp, request)
return True
return self._execute(request, response_handler)
def unload(self) -> Result[bool]:
"""Unload the collection from memory.
:return: True if collection was unloaded successfully.
:rtype: bool
:raise arango.exceptions.CollectionUnloadError: If operation fails.
"""
request = Request(method="put", endpoint=f"/_api/collection/{self.name}/unload")
def response_handler(resp: Response) -> bool:
if not resp.is_success:
raise CollectionUnloadError(resp, request)
return True
return self._execute(request, response_handler)
def truncate(
self,
sync: Optional[bool] = None,
compact: Optional[bool] = None,
) -> Result[bool]:
"""Delete all documents in the collection.
:param sync: Block until deletion operation is synchronized to disk.
:type sync: bool | None
:param compact: Whether to compact the collection after truncation.
:type compact: bool | None
:return: True if collection was truncated successfully.
:rtype: bool
:raise arango.exceptions.CollectionTruncateError: If operation fails.
"""
params: Json = {}
if sync is not None:
params["waitForSync"] = sync
if compact is not None:
params["compact"] = compact
request = Request(
method="put",
endpoint=f"/_api/collection/{self.name}/truncate",
params=params,
)
def response_handler(resp: Response) -> bool:
if not resp.is_success:
raise CollectionTruncateError(resp, request)
return True
return self._execute(request, response_handler)
def count(self) -> Result[int]:
"""Return the total document count.
:return: Total document count.
:rtype: int
:raise arango.exceptions.DocumentCountError: If retrieval fails.
"""
request = Request(method="get", endpoint=f"/_api/collection/{self.name}/count")
def response_handler(resp: Response) -> int:
if resp.is_success:
result: int = resp.body["count"]
return result
raise DocumentCountError(resp, request)
return self._execute(request, response_handler)
def has(
self,
document: Union[str, Json],
rev: Optional[str] = None,
check_rev: bool = True,
allow_dirty_read: bool = False,
) -> Result[bool]:
"""Check if a document exists in the collection.
:param document: Document ID, key or body. Document body must contain
the "_id" or "_key" field.
:type document: str | dict
:param rev: Expected document revision. Overrides value of "_rev" field
in **document** if present.
:type rev: str | None
:param check_rev: If set to True, revision of **document** (if given)
is compared against the revision of target document.
:type check_rev: bool
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool
:return: True if document exists, False otherwise.
:rtype: bool
:raise arango.exceptions.DocumentInError: If check fails.
:raise arango.exceptions.DocumentRevisionError: If revisions mismatch.
"""
handle, body, headers = self._prep_from_doc(document, rev, check_rev)
if allow_dirty_read:
headers["x-arango-allow-dirty-read"] = "true"
request = Request(
method="head",
endpoint=f"/_api/document/{handle}",
headers=headers,
read=self.name,
)
def response_handler(resp: Response) -> bool:
if resp.status_code == 412:
raise DocumentRevisionError(resp, request)
if resp.status_code == 404:
return False
if not resp.is_success:
raise DocumentInError(resp, request)
return True
return self._execute(request, response_handler)
def ids(self, allow_dirty_read: bool = False) -> Result[Cursor]:
"""Return the IDs of all documents in the collection.
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool
:return: Document ID cursor.
:rtype: arango.cursor.Cursor
:raise arango.exceptions.DocumentIDsError: If retrieval fails.
"""
query = "FOR doc IN @@collection RETURN doc._id"
bind_vars = {"@collection": self.name}
request = Request(
method="post",
endpoint="/_api/cursor",
data={"query": query, "bindVars": bind_vars},
read=self.name,
headers={"x-arango-allow-dirty-read": "true"} if allow_dirty_read else None,
)
def response_handler(resp: Response) -> Cursor:
if not resp.is_success:
raise DocumentIDsError(resp, request)
return Cursor(self._conn, resp.body)
return self._execute(request, response_handler)
def keys(self, allow_dirty_read: bool = False) -> Result[Cursor]:
"""Return the keys of all documents in the collection.
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool
:return: Document key cursor.
:rtype: arango.cursor.Cursor
:raise arango.exceptions.DocumentKeysError: If retrieval fails.
"""
query = "FOR doc IN @@collection RETURN doc._key"
bind_vars = {"@collection": self.name}
request = Request(
method="post",
endpoint="/_api/cursor",
data={"query": query, "bindVars": bind_vars},
read=self.name,
headers={"x-arango-allow-dirty-read": "true"} if allow_dirty_read else None,
)
def response_handler(resp: Response) -> Cursor:
if not resp.is_success:
raise DocumentKeysError(resp, request)
return Cursor(self._conn, resp.body)
return self._execute(request, response_handler)
def all(
self,
skip: Optional[int] = None,
limit: Optional[int] = None,
allow_dirty_read: bool = False,
) -> Result[Cursor]:
"""Return all documents in the collection.
:param skip: Number of documents to skip.
:type skip: int | None
:param limit: Max number of documents returned.
:type limit: int | None
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool
:return: Document cursor.
:rtype: arango.cursor.Cursor
:raise arango.exceptions.DocumentGetError: If retrieval fails.
"""
assert is_none_or_int(skip), "skip must be a non-negative int"
assert is_none_or_int(limit), "limit must be a non-negative int"
skip_val = skip if skip is not None else 0
limit_val = limit if limit is not None else "null"
query = f"""
FOR doc IN @@collection
LIMIT {skip_val}, {limit_val}
RETURN doc
"""
bind_vars = {"@collection": self.name}
request = Request(
method="post",
endpoint="/_api/cursor",
data={"query": query, "bindVars": bind_vars, "count": True},
read=self.name,
headers={"x-arango-allow-dirty-read": "true"} if allow_dirty_read else None,
)
def response_handler(resp: Response) -> Cursor:
if not resp.is_success:
raise DocumentGetError(resp, request)
return Cursor(self._conn, resp.body)
return self._execute(request, response_handler)
def find(
self,
filters: Json,
skip: Optional[int] = None,
limit: Optional[int] = None,
allow_dirty_read: bool = False,
sort: Optional[Jsons] = None,
) -> Result[Cursor]:
"""Return all documents that match the given filters.
:param filters: Document filters.
:type filters: dict
:param skip: Number of documents to skip.
:type skip: int | None
:param limit: Max number of documents returned.
:type limit: int | None
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool
:param sort: Document sort parameters
:type sort: Jsons | None
:return: Document cursor.
:rtype: arango.cursor.Cursor
:raise arango.exceptions.DocumentGetError: If retrieval fails.
:raise arango.exceptions.SortValidationError: If sort parameters are invalid.
"""
assert isinstance(filters, dict), "filters must be a dict"
assert is_none_or_int(skip), "skip must be a non-negative int"
assert is_none_or_int(limit), "limit must be a non-negative int"
if sort:
validate_sort_parameters(sort)
skip_val = skip if skip is not None else 0
limit_val = limit if limit is not None else "null"
query = f"""
FOR doc IN @@collection
{build_filter_conditions(filters)}
LIMIT {skip_val}, {limit_val}
{build_sort_expression(sort)}
RETURN doc
"""
bind_vars = {"@collection": self.name}
request = Request(
method="post",
endpoint="/_api/cursor",
data={"query": query, "bindVars": bind_vars, "count": True},
read=self.name,
headers={"x-arango-allow-dirty-read": "true"} if allow_dirty_read else None,
)
def response_handler(resp: Response) -> Cursor:
if not resp.is_success:
raise DocumentGetError(resp, request)
return Cursor(self._conn, resp.body)
return self._execute(request, response_handler)
def find_near(
self,
latitude: Number,
longitude: Number,
limit: Optional[int] = None,
allow_dirty_read: bool = False,
) -> Result[Cursor]:
"""Return documents near a given coordinate.
Documents returned are sorted according to distance, with the nearest
document being the first. If there are documents of equal distance,
they are randomly chosen from the set until the limit is reached. A geo
index must be defined in the collection to use this method.
:param latitude: Latitude.
:type latitude: int | float
:param longitude: Longitude.
:type longitude: int | float
:param limit: Max number of documents returned.
:type limit: int | None
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool
:returns: Document cursor.
:rtype: arango.cursor.Cursor
:raises arango.exceptions.DocumentGetError: If retrieval fails.
"""
assert isinstance(latitude, Number), "latitude must be a number"
assert isinstance(longitude, Number), "longitude must be a number"
assert is_none_or_int(limit), "limit must be a non-negative int"
query = """
FOR doc IN NEAR(@collection, @latitude, @longitude{})
RETURN doc
""".format(
"" if limit is None else ", @limit "
)
bind_vars = {
"collection": self._name,
"latitude": latitude,
"longitude": longitude,
}
if limit is not None:
bind_vars["limit"] = limit
request = Request(
method="post",
endpoint="/_api/cursor",
data={"query": query, "bindVars": bind_vars, "count": True},
read=self.name,
headers={"x-arango-allow-dirty-read": "true"} if allow_dirty_read else None,
)
def response_handler(resp: Response) -> Cursor:
if not resp.is_success:
raise DocumentGetError(resp, request)
return Cursor(self._conn, resp.body)
return self._execute(request, response_handler)
def find_in_range(
self,
field: str,
lower: int,
upper: int,
skip: Optional[int] = None,
limit: Optional[int] = None,
allow_dirty_read: bool = False,
) -> Result[Cursor]:
"""Return documents within a given range in a random order.
A skiplist index must be defined in the collection to use this method.
:param field: Document field name.
:type field: str
:param lower: Lower bound (inclusive).
:type lower: int
:param upper: Upper bound (exclusive).
:type upper: int
:param skip: Number of documents to skip.
:type skip: int | None
:param limit: Max number of documents returned.
:type limit: int | None
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool
:returns: Document cursor.
:rtype: arango.cursor.Cursor
:raises arango.exceptions.DocumentGetError: If retrieval fails.
"""
assert is_none_or_int(skip), "skip must be a non-negative int"
assert is_none_or_int(limit), "limit must be a non-negative int"
bind_vars = {
"@collection": self._name,
"field": field,
"lower": lower,
"upper": upper,
"skip": 0 if skip is None else skip,
"limit": 2147483647 if limit is None else limit, # 2 ^ 31 - 1
}
query = """
FOR doc IN @@collection
FILTER doc.@field >= @lower && doc.@field < @upper
LIMIT @skip, @limit
RETURN doc
"""
request = Request(
method="post",
endpoint="/_api/cursor",
data={"query": query, "bindVars": bind_vars, "count": True},
read=self.name,
headers={"x-arango-allow-dirty-read": "true"} if allow_dirty_read else None,
)
def response_handler(resp: Response) -> Cursor:
if not resp.is_success:
raise DocumentGetError(resp, request)
return Cursor(self._conn, resp.body)
return self._execute(request, response_handler)
def find_in_radius(
self,
latitude: Number,
longitude: Number,
radius: Number,
distance_field: Optional[str] = None,
allow_dirty_read: bool = False,
) -> Result[Cursor]:
"""Return documents within a given radius around a coordinate.
A geo index must be defined in the collection to use this method.
:param latitude: Latitude.
:type latitude: int | float
:param longitude: Longitude.
:type longitude: int | float
:param radius: Max radius.
:type radius: int | float
:param distance_field: Document field used to indicate the distance to
the given coordinate. This parameter is ignored in transactions.
:type distance_field: str
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool
:returns: Document cursor.
:rtype: arango.cursor.Cursor
:raises arango.exceptions.DocumentGetError: If retrieval fails.
"""
assert isinstance(latitude, Number), "latitude must be a number"
assert isinstance(longitude, Number), "longitude must be a number"
assert isinstance(radius, Number), "radius must be a number"
assert is_none_or_str(distance_field), "distance_field must be a str"
query = """
FOR doc IN WITHIN(@@collection, @latitude, @longitude, @radius{})
RETURN doc
""".format(
"" if distance_field is None else ", @distance"
)
bind_vars = {
"@collection": self._name,
"latitude": latitude,
"longitude": longitude,
"radius": radius,
}
if distance_field is not None:
bind_vars["distance"] = distance_field
request = Request(
method="post",
endpoint="/_api/cursor",
data={"query": query, "bindVars": bind_vars, "count": True},
read=self.name,