-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathindex.py
More file actions
771 lines (659 loc) · 28.5 KB
/
Copy pathindex.py
File metadata and controls
771 lines (659 loc) · 28.5 KB
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
from pinecone.utils.tqdm import tqdm
import warnings
import logging
import json
from typing import Union, List, Optional, Dict, Any, Literal, Iterator, TYPE_CHECKING
from pinecone.config import ConfigBuilder
from pinecone.openapi_support import ApiClient
from pinecone.core.openapi.db_data.api.vector_operations_api import VectorOperationsApi
from pinecone.core.openapi.db_data import API_VERSION
from pinecone.core.openapi.db_data.models import (
QueryResponse,
IndexDescription as DescribeIndexStatsResponse,
UpsertResponse,
ListResponse,
SearchRecordsResponse,
ListNamespacesResponse,
NamespaceDescription,
)
from .dataclasses import (
Vector,
SparseValues,
FetchResponse,
FetchByMetadataResponse,
Pagination,
SearchQuery,
SearchRerank,
)
from .interfaces import IndexInterface
from .request_factory import IndexRequestFactory
from .types import (
SparseVectorTypedDict,
VectorTypedDict,
VectorMetadataTypedDict,
VectorTuple,
VectorTupleWithMetadata,
FilterTypedDict,
SearchRerankTypedDict,
SearchQueryTypedDict,
)
from ..utils import (
setup_openapi_client,
parse_non_empty_args,
validate_and_convert_errors,
filter_dict,
PluginAware,
require_kwargs,
)
from .query_results_aggregator import QueryResultsAggregator, QueryNamespacesResults
from pinecone.openapi_support import OPENAPI_ENDPOINT_PARAMS
from multiprocessing.pool import ApplyResult
from multiprocessing import cpu_count
from concurrent.futures import as_completed
if TYPE_CHECKING:
from pinecone.config import Config, OpenApiConfiguration
from .resources.sync.bulk_import import BulkImportResource
from .resources.sync.namespace import NamespaceResource
from pinecone.core.openapi.db_data.models import (
StartImportResponse,
ListImportsResponse,
ImportModel,
)
from .resources.sync.bulk_import import ImportErrorMode
logger = logging.getLogger(__name__)
""" :meta private: """
def parse_query_response(response: QueryResponse):
""":meta private:"""
response._data_store.pop("results", None)
return response
class Index(PluginAware, IndexInterface):
"""
A client for interacting with a Pinecone index via REST API.
For improved performance, use the Pinecone GRPC index client.
"""
_bulk_import_resource: Optional["BulkImportResource"]
""" :meta private: """
_namespace_resource: Optional["NamespaceResource"]
""" :meta private: """
def __init__(
self,
api_key: str,
host: str,
pool_threads: Optional[int] = None,
additional_headers: Optional[Dict[str, str]] = None,
openapi_config=None,
**kwargs,
):
if additional_headers is None:
additional_headers = {}
self._config = ConfigBuilder.build(
api_key=api_key, host=host, additional_headers=additional_headers, **kwargs
)
""" :meta private: """
self._openapi_config = ConfigBuilder.build_openapi_config(self._config, openapi_config)
""" :meta private: """
if pool_threads is None:
self._pool_threads = 5 * cpu_count()
""" :meta private: """
else:
self._pool_threads = pool_threads
""" :meta private: """
if kwargs.get("connection_pool_maxsize", None):
self._openapi_config.connection_pool_maxsize = kwargs.get("connection_pool_maxsize")
self._vector_api = setup_openapi_client(
api_client_klass=ApiClient,
api_klass=VectorOperationsApi,
config=self._config,
openapi_config=self._openapi_config,
pool_threads=self._pool_threads,
api_version=API_VERSION,
)
self._api_client = self._vector_api.api_client
self._bulk_import_resource = None
""" :meta private: """
self._namespace_resource = None
""" :meta private: """
# Initialize PluginAware parent class
super().__init__()
@property
def config(self) -> "Config":
""":meta private:"""
return self._config
@property
def openapi_config(self) -> "OpenApiConfiguration":
""":meta private:"""
warnings.warn(
"The `openapi_config` property has been renamed to `_openapi_config`. It is considered private and should not be used directly. This warning will become an error in a future version of the Pinecone Python SDK.",
DeprecationWarning,
stacklevel=2,
)
return self._openapi_config
@property
def pool_threads(self) -> int:
""":meta private:"""
warnings.warn(
"The `pool_threads` property has been renamed to `_pool_threads`. It is considered private and should not be used directly. This warning will become an error in a future version of the Pinecone Python SDK.",
DeprecationWarning,
stacklevel=2,
)
return self._pool_threads
@property
def bulk_import(self) -> "BulkImportResource":
""":meta private:"""
if self._bulk_import_resource is None:
from .resources.sync.bulk_import import BulkImportResource
self._bulk_import_resource = BulkImportResource(api_client=self._api_client)
return self._bulk_import_resource
@property
def namespace(self) -> "NamespaceResource":
""":meta private:"""
if self._namespace_resource is None:
from .resources.sync.namespace import NamespaceResource
self._namespace_resource = NamespaceResource(
api_client=self._api_client,
config=self._config,
openapi_config=self._openapi_config,
pool_threads=self._pool_threads,
)
return self._namespace_resource
def _openapi_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
return filter_dict(kwargs, OPENAPI_ENDPOINT_PARAMS)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self._vector_api.api_client.close()
def close(self):
self._vector_api.api_client.close()
@validate_and_convert_errors
def upsert(
self,
vectors: Union[
List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict]
],
namespace: Optional[str] = None,
batch_size: Optional[int] = None,
show_progress: bool = True,
**kwargs,
) -> UpsertResponse:
_check_type = kwargs.pop("_check_type", True)
if kwargs.get("async_req", False) and batch_size is not None:
raise ValueError(
"async_req is not supported when batch_size is provided."
"To upsert in parallel, please follow: "
"https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel"
)
if batch_size is None:
return self._upsert_batch(vectors, namespace, _check_type, **kwargs)
if not isinstance(batch_size, int) or batch_size <= 0:
raise ValueError("batch_size must be a positive integer")
pbar = tqdm(total=len(vectors), disable=not show_progress, desc="Upserted vectors")
total_upserted = 0
for i in range(0, len(vectors), batch_size):
batch_result = self._upsert_batch(
vectors[i : i + batch_size], namespace, _check_type, **kwargs
)
pbar.update(batch_result.upserted_count)
# we can't use here pbar.n for the case show_progress=False
total_upserted += batch_result.upserted_count
return UpsertResponse(upserted_count=total_upserted)
def _upsert_batch(
self,
vectors: Union[
List[Vector], List[VectorTuple], List[VectorTupleWithMetadata], List[VectorTypedDict]
],
namespace: Optional[str],
_check_type: bool,
**kwargs,
) -> UpsertResponse:
return self._vector_api.upsert_vectors(
IndexRequestFactory.upsert_request(vectors, namespace, _check_type, **kwargs),
**self._openapi_kwargs(kwargs),
)
@staticmethod
def _iter_dataframe(df, batch_size):
for i in range(0, len(df), batch_size):
batch = df.iloc[i : i + batch_size].to_dict(orient="records")
yield batch
@validate_and_convert_errors
def upsert_from_dataframe(
self, df, namespace: Optional[str] = None, batch_size: int = 500, show_progress: bool = True
) -> UpsertResponse:
try:
import pandas as pd
except ImportError:
raise RuntimeError(
"The `pandas` package is not installed. Please install pandas to use `upsert_from_dataframe()`"
)
if not isinstance(df, pd.DataFrame):
raise ValueError(f"Only pandas dataframes are supported. Found: {type(df)}")
pbar = tqdm(total=len(df), disable=not show_progress, desc="sending upsert requests")
results = []
for chunk in self._iter_dataframe(df, batch_size=batch_size):
res = self.upsert(vectors=chunk, namespace=namespace)
pbar.update(len(chunk))
results.append(res)
upserted_count = 0
for res in results:
upserted_count += res.upserted_count
return UpsertResponse(upserted_count=upserted_count)
@validate_and_convert_errors
def upsert_records(self, namespace: str, records: List[Dict[str, Any]]):
"""Upsert records to a namespace.
Upsert records to a namespace. A record is a dictionary that contains either an ``id`` or ``_id``
field along with other fields that will be stored as metadata. The ``id`` or ``_id`` field is used
as the unique identifier for the record. At least one field in the record should correspond to
a field mapping in the index's embed configuration.
When records are upserted, Pinecone converts mapped fields into embeddings and upserts them into
the specified namespace of the index.
Args:
namespace (str): The namespace of the index to upsert records to.
records (List[Dict[str, Any]]): The records to upsert into the index.
Each record should contain either an ``id`` or ``_id`` field.
Examples:
.. code-block:: python
>>> from pinecone import Pinecone, CloudProvider, AwsRegion, EmbedModel, IndexEmbed
>>> pc = Pinecone(api_key="<<PINECONE_API_KEY>>")
>>> index_model = pc.create_index_for_model(
... name="my-model-index",
... cloud=CloudProvider.AWS,
... region=AwsRegion.US_WEST_2,
... embed=IndexEmbed(
... model=EmbedModel.Multilingual_E5_Large,
... field_map={"text": "my_text_field"}
... )
... )
>>> idx = pc.Index(host=index_model.host)
>>> idx.upsert_records(
... namespace="my-namespace",
... records=[
... {"_id": "test1", "my_text_field": "Apple is a popular fruit."},
... {"_id": "test2", "my_text_field": "The tech company Apple is innovative."},
... ],
... )
"""
args = IndexRequestFactory.upsert_records_args(namespace=namespace, records=records)
self._vector_api.upsert_records_namespace(**args)
@validate_and_convert_errors
def search(
self,
namespace: str,
query: Union[SearchQueryTypedDict, SearchQuery],
rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None,
fields: Optional[List[str]] = ["*"], # Default to returning all fields
) -> SearchRecordsResponse:
request = IndexRequestFactory.search_request(query=query, rerank=rerank, fields=fields)
return self._vector_api.search_records_namespace(namespace, request)
@validate_and_convert_errors
def search_records(
self,
namespace: str,
query: Union[SearchQueryTypedDict, SearchQuery],
rerank: Optional[Union[SearchRerankTypedDict, SearchRerank]] = None,
fields: Optional[List[str]] = ["*"], # Default to returning all fields
) -> SearchRecordsResponse:
return self.search(namespace, query=query, rerank=rerank, fields=fields)
@validate_and_convert_errors
def delete(
self,
ids: Optional[List[str]] = None,
delete_all: Optional[bool] = None,
namespace: Optional[str] = None,
filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None,
**kwargs,
) -> Dict[str, Any]:
return self._vector_api.delete_vectors(
IndexRequestFactory.delete_request(
ids=ids, delete_all=delete_all, namespace=namespace, filter=filter, **kwargs
),
**self._openapi_kwargs(kwargs),
)
@validate_and_convert_errors
def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> FetchResponse:
args_dict = parse_non_empty_args([("namespace", namespace)])
result = self._vector_api.fetch_vectors(ids=ids, **args_dict, **kwargs)
return FetchResponse(
namespace=result.namespace,
vectors={k: Vector.from_dict(v) for k, v in result.vectors.items()},
usage=result.usage,
)
@validate_and_convert_errors
def fetch_by_metadata(
self,
filter: FilterTypedDict,
namespace: Optional[str] = None,
limit: Optional[int] = None,
pagination_token: Optional[str] = None,
**kwargs,
) -> FetchByMetadataResponse:
"""Fetch vectors by metadata filter.
Look up and return vectors by metadata filter from a single namespace.
The returned vectors include the vector data and/or metadata.
Examples:
.. code-block:: python
>>> index.fetch_by_metadata(
... filter={'genre': {'$in': ['comedy', 'drama']}, 'year': {'$eq': 2019}},
... namespace='my_namespace',
... limit=50
... )
>>> index.fetch_by_metadata(
... filter={'status': 'active'},
... pagination_token='token123'
... )
Args:
filter (Dict[str, Union[str, float, int, bool, List, dict]]):
Metadata filter expression to select vectors.
See `metadata filtering <https://www.pinecone.io/docs/metadata-filtering/>_`
namespace (str): The namespace to fetch vectors from.
If not specified, the default namespace is used. [optional]
limit (int): Max number of vectors to return. Defaults to 100. [optional]
pagination_token (str): Pagination token to continue a previous listing operation. [optional]
Returns:
FetchByMetadataResponse: Object containing the fetched vectors, namespace, usage, and pagination token.
"""
request = IndexRequestFactory.fetch_by_metadata_request(
filter=filter,
namespace=namespace,
limit=limit,
pagination_token=pagination_token,
**kwargs,
)
result = self._vector_api.fetch_vectors_by_metadata(request, **self._openapi_kwargs(kwargs))
pagination = None
if result.pagination and result.pagination.next:
pagination = Pagination(next=result.pagination.next)
return FetchByMetadataResponse(
namespace=result.namespace or "",
vectors={k: Vector.from_dict(v) for k, v in result.vectors.items()},
usage=result.usage,
pagination=pagination,
)
@validate_and_convert_errors
def query(
self,
*args,
top_k: int,
vector: Optional[List[float]] = None,
id: Optional[str] = None,
namespace: Optional[str] = None,
filter: Optional[FilterTypedDict] = None,
include_values: Optional[bool] = None,
include_metadata: Optional[bool] = None,
sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None,
**kwargs,
) -> Union[QueryResponse, ApplyResult]:
response = self._query(
*args,
top_k=top_k,
vector=vector,
id=id,
namespace=namespace,
filter=filter,
include_values=include_values,
include_metadata=include_metadata,
sparse_vector=sparse_vector,
**kwargs,
)
if kwargs.get("async_req", False) or kwargs.get("async_threadpool_executor", False):
return response
else:
return parse_query_response(response)
def _query(
self,
*args,
top_k: int,
vector: Optional[List[float]] = None,
id: Optional[str] = None,
namespace: Optional[str] = None,
filter: Optional[FilterTypedDict] = None,
include_values: Optional[bool] = None,
include_metadata: Optional[bool] = None,
sparse_vector: Optional[Union[SparseValues, SparseVectorTypedDict]] = None,
**kwargs,
) -> QueryResponse:
if len(args) > 0:
raise ValueError(
"The argument order for `query()` has changed; please use keyword arguments instead of positional arguments. Example: index.query(vector=[0.1, 0.2, 0.3], top_k=10, namespace='my_namespace')"
)
if top_k < 1:
raise ValueError("top_k must be a positive integer")
request = IndexRequestFactory.query_request(
top_k=top_k,
vector=vector,
id=id,
namespace=namespace,
filter=filter,
include_values=include_values,
include_metadata=include_metadata,
sparse_vector=sparse_vector,
**kwargs,
)
return self._vector_api.query_vectors(request, **self._openapi_kwargs(kwargs))
@validate_and_convert_errors
def query_namespaces(
self,
vector: Optional[List[float]],
namespaces: List[str],
metric: Literal["cosine", "euclidean", "dotproduct"],
top_k: Optional[int] = None,
filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None,
include_values: Optional[bool] = None,
include_metadata: Optional[bool] = None,
sparse_vector: Optional[
Union[SparseValues, Dict[str, Union[List[float], List[int]]]]
] = None,
**kwargs,
) -> QueryNamespacesResults:
if namespaces is None or len(namespaces) == 0:
raise ValueError("At least one namespace must be specified")
if sparse_vector is None and vector is not None and len(vector) == 0:
# If querying with a vector, it must not be empty
raise ValueError("Query vector must not be empty")
overall_topk = top_k if top_k is not None else 10
aggregator = QueryResultsAggregator(top_k=overall_topk, metric=metric)
target_namespaces = set(namespaces) # dedup namespaces
async_futures = [
self.query(
vector=vector,
namespace=ns,
top_k=overall_topk,
filter=filter,
include_values=include_values,
include_metadata=include_metadata,
sparse_vector=sparse_vector,
async_threadpool_executor=True,
_preload_content=False,
**kwargs,
)
for ns in target_namespaces
]
for result in as_completed(async_futures):
raw_result = result.result()
response = json.loads(raw_result.data.decode("utf-8"))
aggregator.add_results(response)
final_results = aggregator.get_results()
return final_results
@validate_and_convert_errors
def update(
self,
id: str,
values: Optional[List[float]] = None,
set_metadata: Optional[VectorMetadataTypedDict] = None,
namespace: Optional[str] = None,
sparse_values: Optional[Union[SparseValues, SparseVectorTypedDict]] = None,
**kwargs,
) -> Dict[str, Any]:
return self._vector_api.update_vector(
IndexRequestFactory.update_request(
id=id,
values=values,
set_metadata=set_metadata,
namespace=namespace,
sparse_values=sparse_values,
**kwargs,
),
**self._openapi_kwargs(kwargs),
)
@validate_and_convert_errors
def describe_index_stats(
self, filter: Optional[FilterTypedDict] = None, **kwargs
) -> DescribeIndexStatsResponse:
return self._vector_api.describe_index_stats(
IndexRequestFactory.describe_index_stats_request(filter, **kwargs),
**self._openapi_kwargs(kwargs),
)
@validate_and_convert_errors
def list_paginated(
self,
prefix: Optional[str] = None,
limit: Optional[int] = None,
pagination_token: Optional[str] = None,
namespace: Optional[str] = None,
**kwargs,
) -> ListResponse:
args_dict = IndexRequestFactory.list_paginated_args(
prefix=prefix,
limit=limit,
pagination_token=pagination_token,
namespace=namespace,
**kwargs,
)
return self._vector_api.list_vectors(**args_dict, **kwargs)
@validate_and_convert_errors
def list(self, **kwargs):
done = False
while not done:
results = self.list_paginated(**kwargs)
if len(results.vectors) > 0:
yield [v.id for v in results.vectors]
if results.pagination:
kwargs.update({"pagination_token": results.pagination.next})
else:
done = True
@validate_and_convert_errors
def start_import(
self,
uri: str,
integration_id: Optional[str] = None,
error_mode: Optional[
Union["ImportErrorMode", Literal["CONTINUE", "ABORT"], str]
] = "CONTINUE",
) -> "StartImportResponse":
"""
Args:
uri (str): The URI of the data to import. The URI must start with the scheme of a supported storage provider.
integration_id (Optional[str], optional): If your bucket requires authentication to access, you need to pass the id of your storage integration using this property. Defaults to None.
error_mode: Defaults to "CONTINUE". If set to "CONTINUE", the import operation will continue even if some
records fail to import. Pass "ABORT" to stop the import operation if any records fail to import.
Returns:
`StartImportResponse`: Contains the id of the import operation.
Import data from a storage provider into an index. The uri must start with the scheme of a supported
storage provider. For buckets that are not publicly readable, you will also need to separately configure
a storage integration and pass the integration id.
Examples:
>>> from pinecone import Pinecone
>>> index = Pinecone().Index('my-index')
>>> index.start_import(uri="s3://bucket-name/path/to/data.parquet")
{ id: "1" }
"""
return self.bulk_import.start(uri=uri, integration_id=integration_id, error_mode=error_mode)
@validate_and_convert_errors
def list_imports(self, **kwargs) -> Iterator["ImportModel"]:
"""
Args:
limit (Optional[int]): The maximum number of operations to fetch in each network call. If unspecified, the server will use a default value. [optional]
pagination_token (Optional[str]): When there are multiple pages of results, a pagination token is returned in the response. The token can be used
to fetch the next page of results. [optional]
Returns:
Returns a generator that yields each import operation. It automatically handles pagination tokens on your behalf so you can
easily iterate over all results. The `list_imports` method accepts all of the same arguments as list_imports_paginated
.. code-block:: python
for op in index.list_imports():
print(op)
You can convert the generator into a list by wrapping the generator in a call to the built-in `list` function:
.. code-block:: python
operations = list(index.list_imports())
You should be cautious with this approach because it will fetch all operations at once, which could be a large number
of network calls and a lot of memory to hold the results.
"""
for i in self.bulk_import.list(**kwargs):
yield i
@validate_and_convert_errors
def list_imports_paginated(
self, limit: Optional[int] = None, pagination_token: Optional[str] = None, **kwargs
) -> "ListImportsResponse":
"""
Args:
limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional]
pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned
in the response if additional results are available. [optional]
Returns: ListImportsResponse object which contains the list of operations as ImportModel objects, pagination information,
and usage showing the number of read_units consumed.
The list_imports_paginated() operation returns information about import operations.
It returns operations in a paginated form, with a pagination token to fetch the next page of results.
Consider using the `list_imports` method to avoid having to handle pagination tokens manually.
Examples:
.. code-block:: python
>>> results = index.list_imports_paginated(limit=5)
>>> results.pagination.next
eyJza2lwX3Bhc3QiOiI5OTMiLCJwcmVmaXgiOiI5OSJ9
>>> results.data[0]
{
"id": "6",
"uri": "s3://dev-bulk-import-datasets-pub/10-records-dim-10/",
"status": "Completed",
"percent_complete": 100.0,
"records_imported": 10,
"created_at": "2024-09-06T14:52:02.567776+00:00",
"finished_at": "2024-09-06T14:52:28.130717+00:00"
}
>>> next_results = index.list_imports_paginated(limit=5, pagination_token=results.pagination.next)
"""
return self.bulk_import.list_paginated(
limit=limit, pagination_token=pagination_token, **kwargs
)
@validate_and_convert_errors
def describe_import(self, id: str) -> "ImportModel":
"""
Args:
id (str): The id of the import operation. This value is returned when
starting an import, and can be looked up using list_imports.
Returns:
`ImportModel`: An object containing operation id, status, and other details.
describe_import is used to get detailed information about a specific import operation.
"""
return self.bulk_import.describe(id=id)
@validate_and_convert_errors
def cancel_import(self, id: str):
"""Cancel an import operation.
Args:
id (str): The id of the import operation to cancel.
"""
return self.bulk_import.cancel(id=id)
@validate_and_convert_errors
@require_kwargs
def create_namespace(
self, name: str, schema: Optional[Dict[str, Any]] = None, **kwargs
) -> "NamespaceDescription":
return self.namespace.create(name=name, schema=schema, **kwargs)
@validate_and_convert_errors
@require_kwargs
def describe_namespace(self, namespace: str, **kwargs) -> "NamespaceDescription":
return self.namespace.describe(namespace=namespace, **kwargs)
@validate_and_convert_errors
@require_kwargs
def delete_namespace(self, namespace: str, **kwargs) -> Dict[str, Any]:
return self.namespace.delete(namespace=namespace, **kwargs)
@validate_and_convert_errors
@require_kwargs
def list_namespaces(
self, limit: Optional[int] = None, **kwargs
) -> Iterator[ListNamespacesResponse]:
return self.namespace.list(limit=limit, **kwargs)
@validate_and_convert_errors
@require_kwargs
def list_namespaces_paginated(
self, limit: Optional[int] = None, pagination_token: Optional[str] = None, **kwargs
) -> ListNamespacesResponse:
return self.namespace.list_paginated(
limit=limit, pagination_token=pagination_token, **kwargs
)