-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.py
2178 lines (1567 loc) · 77.8 KB
/
index.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
from __future__ import annotations
import json
from asyncio import gather, get_running_loop
from csv import DictReader
from datetime import datetime
from functools import partial
from pathlib import Path
from typing import Any, Generator
from urllib.parse import urlencode
import aiofiles
from httpx import AsyncClient
from meilisearch_python_async._http_requests import HttpRequests
from meilisearch_python_async.errors import InvalidDocumentError, MeiliSearchError
from meilisearch_python_async.models.documents import DocumentsInfo
from meilisearch_python_async.models.index import IndexStats
from meilisearch_python_async.models.search import SearchResults
from meilisearch_python_async.models.settings import Faceting, MeiliSearchSettings, TypoTolerance
from meilisearch_python_async.models.task import TaskInfo
from meilisearch_python_async.task import wait_for_task
class Index:
"""Index class gives access to all indexes routes and child routes.
https://docs.meilisearch.com/reference/api/indexes.html
"""
def __init__(
self,
http_client: AsyncClient,
uid: str,
primary_key: str | None = None,
created_at: str | datetime | None = None,
updated_at: str | datetime | None = None,
):
"""Class initializer.
Args:
http_client: An instance of the AsyncClient. This automatically gets passed by the
Client when creating and Index instance.
uid: The index's unique identifier.
primary_key: The primary key of the documents. Defaults to None.
created_at: The date and time the index was created. Defaults to None.
updated_at: The date and time the index was last updated. Defaults to None.
"""
self.uid = uid
self.primary_key = primary_key
self.created_at: datetime | None = _iso_to_date_time(created_at)
self.updated_at: datetime | None = _iso_to_date_time(updated_at)
self._base_url = "indexes/"
self._base_url_with_uid = f"{self._base_url}{self.uid}"
self._documents_url = f"{self._base_url_with_uid}/documents"
self._stats_url = f"{self._base_url_with_uid}/stats"
self._settings_url = f"{self._base_url_with_uid}/settings"
self.http_client = http_client
self._http_requests = HttpRequests(http_client)
def __str__(self) -> str:
return f"{type(self).__name__}(uid={self.uid}, primary_key={self.primary_key}, created_at={self.created_at}, updated_at={self.updated_at})"
def __repr__(self) -> str:
return f"{type(self).__name__}(uid={self.uid!r}, primary_key={self.primary_key!r}, created_at={self.created_at!r}, updated_at={self.updated_at!r})"
async def delete(self) -> TaskInfo:
"""Deletes the index.
Returns:
The details of the task.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.delete()
"""
url = f"{self._base_url_with_uid}"
response = await self._http_requests.delete(url)
return TaskInfo(**response.json())
async def delete_if_exists(self) -> bool:
"""Delete the index if it already exists.
Returns:
True if the index was deleted or False if not.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.delete_if_exists()
"""
response = await self.delete()
status = await wait_for_task(self.http_client, response.task_uid)
if status.status == "succeeded":
return True
return False
async def update(self, primary_key: str) -> Index:
"""Update the index primary key.
Args:
primary_key: The primary key of the documents.
Returns:
An instance of the Index with the updated information.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> updated_index = await index.update()
"""
payload = {"primaryKey": primary_key}
url = f"{self._base_url_with_uid}"
response = await self._http_requests.patch(url, payload)
await wait_for_task(self.http_client, response.json()["taskUid"], timeout_in_ms=100000)
index_response = await self._http_requests.get(f"{url}")
self.primary_key = index_response.json()["primaryKey"]
return self
async def fetch_info(self) -> Index:
"""Gets the infromation about the index.
Returns:
An instance of the Index containing the retrieved information.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> index_info = await index.fetch_info()
"""
url = f"{self._base_url_with_uid}"
response = await self._http_requests.get(url)
index_dict = response.json()
self.primary_key = index_dict["primaryKey"]
loop = get_running_loop()
self.created_at = await loop.run_in_executor(
None, partial(_iso_to_date_time, index_dict["createdAt"])
)
self.updated_at = await loop.run_in_executor(
None, partial(_iso_to_date_time, index_dict["updatedAt"])
)
return self
async def get_primary_key(self) -> str | None:
"""Get the primary key.
Returns:
The primary key for the documents in the index.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> primary_key = await index.get_primary_key()
"""
info = await self.fetch_info()
return info.primary_key
@classmethod
async def create(
cls, http_client: AsyncClient, uid: str, primary_key: str | None = None
) -> Index:
"""Creates a new index.
In general this method should not be used directly and instead the index should be created
through the `Client`.
Args:
http_client: An instance of the AsyncClient. This automatically gets passed by the
Client when creating and Index instance.
uid: The index's unique identifier.
primary_key: The primary key of the documents. Defaults to None.
Returns:
An instance of Index containing the information of the newly created index.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = await index.create(client, "movies")
"""
if not primary_key:
payload = {"uid": uid}
else:
payload = {"primaryKey": primary_key, "uid": uid}
url = "indexes"
http_request = HttpRequests(http_client)
response = await http_request.post(url, payload)
await wait_for_task(http_client, response.json()["taskUid"], timeout_in_ms=100000)
index_response = await http_request.get(f"{url}/{uid}")
index_dict = index_response.json()
return cls(
http_client=http_client,
uid=index_dict["uid"],
primary_key=index_dict["primaryKey"],
created_at=index_dict["createdAt"],
updated_at=index_dict["updatedAt"],
)
async def get_stats(self) -> IndexStats:
"""Get stats of the index.
Returns:
Stats of the index.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> stats = await index.get_stats()
"""
url = f"{self._stats_url}"
response = await self._http_requests.get(url)
return IndexStats(**response.json())
async def search(
self,
query: str | None = None,
*,
offset: int = 0,
limit: int = 20,
filter: str | list[str | list[str]] | None = None,
facets: list[str] | None = None,
attributes_to_retrieve: list[str] = ["*"],
attributes_to_crop: list[str] | None = None,
crop_length: int = 200,
attributes_to_highlight: list[str] | None = None,
sort: list[str] | None = None,
show_matches_position: bool = False,
highlight_pre_tag: str = "<em>",
highlight_post_tag: str = "</em>",
crop_marker: str = "...",
) -> SearchResults:
"""Search the index.
Args:
query: String containing the word(s) to search
offset: Number of documents to skip. Defaults to 0.
limit: Maximum number of documents returned. Defaults to 20.
filter: Filter queries by an attribute value. Defaults to None.
facets: Facets for which to retrieve the matching count. Defaults to None.
attributes_to_retrieve: Attributes to display in the returned documents.
Defaults to ["*"].
attributes_to_crop: Attributes whose values have to be cropped. Defaults to None.
crop_length: The maximun number of words to display. Defaults to 200.
attributes_to_highlight: Attributes whose values will contain highlighted matching terms.
Defaults to None.
sort: Attributes by which to sort the results. Defaults to None.
show_matches_position: Defines whether an object that contains information about the matches should be
returned or not. Defaults to False.
highlight_pre_tag: The opening tag for highlighting text. Defaults to <em>.
highlight_post_tag: The closing tag for highlighting text. Defaults to </em>
crop_marker: Marker to display when the number of words excedes the `crop_length`.
Defaults to ...
Returns:
Results of the search
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> search_results = await index.search("Tron")
"""
body = {
"q": query,
"offset": offset,
"limit": limit,
"filter": filter,
"facets": facets,
"attributesToRetrieve": attributes_to_retrieve,
"attributesToCrop": attributes_to_crop,
"cropLength": crop_length,
"attributesToHighlight": attributes_to_highlight,
"sort": sort,
"showMatchesPosition": show_matches_position,
"highlightPreTag": highlight_pre_tag,
"highlightPostTag": highlight_post_tag,
"cropMarker": crop_marker,
}
url = f"{self._base_url_with_uid}/search"
response = await self._http_requests.post(url, body=body)
return SearchResults(**response.json())
async def get_document(self, document_id: str) -> dict[str, Any]:
"""Get one document with given document identifier.
Args:
document_id: Unique identifier of the document.
Returns:
The document information
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> document = await index.get_document("1234")
"""
url = f"{self._documents_url}/{document_id}"
response = await self._http_requests.get(url)
return response.json()
async def get_documents(
self, *, offset: int = 0, limit: int = 20, fields: list[str] | None = None
) -> DocumentsInfo:
"""Get a batch documents from the index.
Args:
offset: Number of documents to skip. Defaults to 0.
limit: Maximum number of documents returnedd. Defaults to 20.
fields: Document attributes to show. If this value is None then all
attributes are retrieved. Defaults to None.
Returns:
Documents info.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> documents = await index.get_documents()
"""
parameters: dict[str, Any] = {
"offset": offset,
"limit": limit,
}
if fields:
parameters["fields"] = ",".join(fields)
url = f"{self._documents_url}?{urlencode(parameters)}"
response = await self._http_requests.get(url)
return DocumentsInfo(**response.json())
async def add_documents(
self, documents: list[dict], primary_key: str | None = None
) -> TaskInfo:
"""Add documents to the index.
Args:
documents: List of documents.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
Returns:
The details of the task.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> >>> documents = [
>>> {"id": 1, "title": "Movie 1", "genre": "comedy"},
>>> {"id": 2, "title": "Movie 2", "genre": "drama"},
>>> ]
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.add_documents(documents)
"""
url = f"{self._documents_url}"
if primary_key:
formatted_primary_key = urlencode({"primaryKey": primary_key})
url = f"{url}?{formatted_primary_key}"
response = await self._http_requests.post(url, documents)
return TaskInfo(**response.json())
async def add_documents_in_batches(
self, documents: list[dict], *, batch_size: int = 1000, primary_key: str | None = None
) -> list[TaskInfo]:
"""Adds documents in batches to reduce RAM usage with indexing.
Args:
documents: List of documents.
batch_size: The number of documents that should be included in each batch.
Defaults to 1000.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
Returns:
List of update ids to track the action.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> >>> documents = [
>>> {"id": 1, "title": "Movie 1", "genre": "comedy"},
>>> {"id": 2, "title": "Movie 2", "genre": "drama"},
>>> ]
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.add_documents_in_batches(documents)
"""
batches = [self.add_documents(x, primary_key) for x in _batch(documents, batch_size)]
return await gather(*batches)
async def add_documents_from_directory(
self,
directory_path: Path | str,
*,
primary_key: str | None = None,
document_type: str = "json",
combine_documents: bool = True,
) -> list[TaskInfo]:
"""Load all json files from a directory and add the documents to the index.
Args:
directory_path: Path to the directory that contains the json files.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
document_type: The type of document being added. Accepted types are json, csv, and
ndjson. For csv files the first row of the document should be a header row contining
the field names, and ever for should have a title.
combine_documents: If set to True this will combine the documents from all the files
before indexing them. Defaults to True.
Returns:
The details of the task status.
Raises:
InvalidDocumentError: If the docucment is not a valid format for MeiliSarch.
MeiliSearchError: If the file path is not valid
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from pathlib import Path
>>> from meilisearch_async_client import Client
>>> directory_path = Path("/path/to/directory/containing/files")
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.add_documents_from_directory(directory_path)
"""
directory = Path(directory_path) if isinstance(directory_path, str) else directory_path
if combine_documents:
all_documents = []
for path in directory.iterdir():
if path.suffix == f".{document_type}":
documents = await _load_documents_from_file(path)
all_documents.append(documents)
_raise_on_no_documents(all_documents, document_type, directory_path)
loop = get_running_loop()
combined = await loop.run_in_executor(None, partial(_combine_documents, all_documents))
response = await self.add_documents(combined, primary_key)
return [response]
add_documents = []
for path in directory.iterdir():
if path.suffix == f".{document_type}":
documents = await _load_documents_from_file(path)
add_documents.append(self.add_documents(documents, primary_key))
_raise_on_no_documents(add_documents, document_type, directory_path)
if len(add_documents) > 1:
# Send the first document on its own before starting the gather. Otherwise MeiliSearch
# returns an error because it thinks all entries are trying to create the same index.
first_response = [await add_documents.pop()]
responses = await gather(*add_documents)
responses = [*first_response, *responses]
else:
responses = [await add_documents[0]]
return responses
async def add_documents_from_directory_in_batches(
self,
directory_path: Path | str,
*,
batch_size: int = 1000,
primary_key: str | None = None,
document_type: str = "json",
combine_documents: bool = True,
) -> list[TaskInfo]:
"""Load all json files from a directory and add the documents to the index in batches.
Args:
directory_path: Path to the directory that contains the json files.
batch_size: The number of documents that should be included in each batch.
Defaults to 1000.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
document_type: The type of document being added. Accepted types are json, csv, and
ndjson. For csv files the first row of the document should be a header row contining
the field names, and ever for should have a title.
combine_documents: If set to True this will combine the documents from all the files
before indexing them. Defaults to True.
Returns:
List of update ids to track the action.
Raises:
InvalidDocumentError: If the docucment is not a valid format for MeiliSarch.
MeiliSearchError: If the file path is not valid
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from pathlib import Path
>>> from meilisearch_async_client import Client
>>> directory_path = Path("/path/to/directory/containing/files")
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.add_documents_from_directory_in_batches(directory_path)
"""
directory = Path(directory_path) if isinstance(directory_path, str) else directory_path
if combine_documents:
all_documents = []
for path in directory.iterdir():
if path.suffix == f".{document_type}":
documents = await _load_documents_from_file(path)
all_documents.append(documents)
_raise_on_no_documents(all_documents, document_type, directory_path)
loop = get_running_loop()
combined = await loop.run_in_executor(None, partial(_combine_documents, all_documents))
return await self.add_documents_in_batches(
combined, batch_size=batch_size, primary_key=primary_key
)
responses: list[TaskInfo] = []
add_documents = []
for path in directory.iterdir():
if path.suffix == f".{document_type}":
documents = await _load_documents_from_file(path)
add_documents.append(
self.add_documents_in_batches(
documents, batch_size=batch_size, primary_key=primary_key
)
)
_raise_on_no_documents(add_documents, document_type, directory_path)
if len(add_documents) > 1:
# Send the first document on its own before starting the gather. Otherwise MeiliSearch
# returns an error because it thinks all entries are trying to create the same index.
first_response = await add_documents.pop()
responses_gather = await gather(*add_documents)
responses = [*first_response, *[x for y in responses_gather for x in y]]
else:
responses = await add_documents[0]
return responses
async def add_documents_from_file(
self, file_path: Path | str, primary_key: str | None = None
) -> TaskInfo:
"""Add documents to the index from a json file.
Args:
file_path: Path to the json file.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
Returns:
The details of the task status.
Raises:
InvalidDocumentError: If the docucment is not a valid format for MeiliSarch.
MeiliSearchError: If the file path is not valid
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from pathlib import Path
>>> from meilisearch_async_client import Client
>>> file_path = Path("/path/to/file.json")
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.add_documents_from_file(file_path)
"""
documents = await _load_documents_from_file(file_path)
return await self.add_documents(documents, primary_key=primary_key)
async def add_documents_from_file_in_batches(
self, file_path: Path | str, *, batch_size: int = 1000, primary_key: str | None = None
) -> list[TaskInfo]:
"""Adds documents form a json file in batches to reduce RAM usage with indexing.
Args:
file_path: Path to the json file.
batch_size: The number of documents that should be included in each batch.
Defaults to 1000.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
Returns:
List of update ids to track the action.
Raises:
InvalidDocumentError: If the docucment is not a valid format for MeiliSarch.
MeiliSearchError: If the file path is not valid
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from pathlib import Path
>>> from meilisearch_async_client import Client
>>> file_path = Path("/path/to/file.json")
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.add_documents_from_file_in_batches(file_path)
"""
documents = await _load_documents_from_file(file_path)
return await self.add_documents_in_batches(
documents, batch_size=batch_size, primary_key=primary_key
)
async def add_documents_from_raw_file(
self, file_path: Path | str, primary_key: str | None = None
) -> TaskInfo:
"""Directly send csv or ndjson files to MeiliSearch without pre-processing.
The can reduce RAM usage from MeiliSearch during indexing, but does not include the option
for batching.
Args:
file_path: The path to the file to send to MeiliSearch. Only csv and ndjson files are
allowed.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
Returns:
The details of the task.
Raises:
ValueError: If the file is not a csv or ndjson file.
MeiliSearchError: If the file path is not valid
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from pathlib import Path
>>> from meilisearch_async_client import Client
>>> file_path = Path("/path/to/file.csv")
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.add_documents_from_raw_file(file_path)
"""
upload_path = Path(file_path) if isinstance(file_path, str) else file_path
if not upload_path.exists():
raise MeiliSearchError("No file found at the specified path")
if upload_path.suffix not in (".csv", ".ndjson"):
raise ValueError("Only csv and ndjson files can be sent as binary files")
content_type = "text/csv" if upload_path.suffix == ".csv" else "application/x-ndjson"
url = self._documents_url
if primary_key:
formatted_primary_key = urlencode({"primaryKey": primary_key})
url = f"{url}?{formatted_primary_key}"
async with aiofiles.open(upload_path, "r") as f:
data = await f.read()
response = await self._http_requests.post(url, body=data, content_type=content_type)
return TaskInfo(**response.json())
async def update_documents(
self, documents: list[dict], primary_key: str | None = None
) -> TaskInfo:
"""Update documents in the index.
Args:
documents: List of documents.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
Returns:
The details of the task.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> documents = [
>>> {"id": 1, "title": "Movie 1", "genre": "comedy"},
>>> {"id": 2, "title": "Movie 2", "genre": "drama"},
>>> ]
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.update_documents(documents)
"""
url = f"{self._documents_url}"
if primary_key:
formatted_primary_key = urlencode({"primaryKey": primary_key})
url = f"{url}?{formatted_primary_key}"
response = await self._http_requests.put(url, documents)
return TaskInfo(**response.json())
async def update_documents_in_batches(
self, documents: list[dict], *, batch_size: int = 1000, primary_key: str | None = None
) -> list[TaskInfo]:
"""Update documents in batches to reduce RAM usage with indexing.
Each batch tries to fill the max_payload_size
Args:
documents: List of documents.
batch_size: The number of documents that should be included in each batch.
Defaults to 1000.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
Returns:
List of update ids to track the action.
Raises:
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from meilisearch_async_client import Client
>>> documents = [
>>> {"id": 1, "title": "Movie 1", "genre": "comedy"},
>>> {"id": 2, "title": "Movie 2", "genre": "drama"},
>>> ]
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.update_documents_in_batches(documents)
"""
batches = [self.update_documents(x, primary_key) for x in _batch(documents, batch_size)]
return await gather(*batches)
async def update_documents_from_directory(
self,
directory_path: Path | str,
*,
primary_key: str | None = None,
document_type: str = "json",
combine_documents: bool = True,
) -> list[TaskInfo]:
"""Load all json files from a directory and update the documents.
Args:
directory_path: Path to the directory that contains the json files.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
document_type: The type of document being added. Accepted types are json, csv, and
ndjson. For csv files the first row of the document should be a header row contining
the field names, and ever for should have a title.
combine_documents: If set to True this will combine the documents from all the files
before indexing them. Defaults to True.
Returns:
The details of the task status.
Raises:
InvalidDocumentError: If the docucment is not a valid format for MeiliSarch.
MeiliSearchError: If the file path is not valid
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from pathlib import Path
>>> from meilisearch_async_client import Client
>>> directory_path = Path("/path/to/directory/containing/files")
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.update_documents_from_directory(directory_path)
"""
directory = Path(directory_path) if isinstance(directory_path, str) else directory_path
if combine_documents:
all_documents = []
for path in directory.iterdir():
if path.suffix == f".{document_type}":
documents = await _load_documents_from_file(path)
all_documents.append(documents)
_raise_on_no_documents(all_documents, document_type, directory_path)
loop = get_running_loop()
combined = await loop.run_in_executor(None, partial(_combine_documents, all_documents))
response = await self.update_documents(combined, primary_key)
return [response]
update_documents = []
for path in directory.iterdir():
if path.suffix == f".{document_type}":
documents = await _load_documents_from_file(path)
update_documents.append(self.update_documents(documents, primary_key))
_raise_on_no_documents(update_documents, document_type, directory_path)
if len(update_documents) > 1:
# Send the first document on its own before starting the gather. Otherwise MeiliSearch
# returns an error because it thinks all entries are trying to create the same index.
first_response = [await update_documents.pop()]
responses = await gather(*update_documents)
responses = [*first_response, *responses]
else:
responses = [await update_documents[0]]
return responses
async def update_documents_from_directory_in_batches(
self,
directory_path: Path | str,
*,
batch_size: int = 1000,
primary_key: str | None = None,
document_type: str = "json",
combine_documents: bool = True,
) -> list[TaskInfo]:
"""Load all json files from a directory and update the documents.
Args:
directory_path: Path to the directory that contains the json files.
batch_size: The number of documents that should be included in each batch.
Defaults to 1000.
primary_key: The primary key of the documents. This will be ignored if already set.
Defaults to None.
document_type: The type of document being added. Accepted types are json, csv, and
ndjson. For csv files the first row of the document should be a header row contining
the field names, and ever for should have a title.
combine_documents: If set to True this will combine the documents from all the files
before indexing them. Defaults to True.
Returns:
List of update ids to track the action.
Raises:
InvalidDocumentError: If the docucment is not a valid format for MeiliSarch.
MeiliSearchError: If the file path is not valid
MeilisearchCommunicationError: If there was an error communicating with the server.
MeilisearchApiError: If the MeiliSearch API returned an error.
Examples:
>>> from pathlib import Path
>>> from meilisearch_async_client import Client
>>> directory_path = Path("/path/to/directory/containing/files")
>>> async with Client("http://localhost.com", "masterKey") as client:
>>> index = client.index("movies")
>>> await index.update_documents_from_directory_in_batches(directory_path)
"""
directory = Path(directory_path) if isinstance(directory_path, str) else directory_path
if combine_documents:
all_documents = []
for path in directory.iterdir():
if path.suffix == f".{document_type}":
documents = await _load_documents_from_file(path)
all_documents.append(documents)
_raise_on_no_documents(all_documents, document_type, directory_path)
loop = get_running_loop()