AsyncIndex¶
Obtain an AsyncIndex via pinecone.AsyncPinecone.index().
from pinecone import AsyncPinecone
pc = AsyncPinecone(api_key="your-api-key")
# Resolve host automatically by index name
async with await pc.index("my-index") as idx:
stats = await idx.describe_index_stats()
# — or — connect directly with a host URL
async with AsyncIndex(host="my-index-abc123.svc.pinecone.io", api_key="...") as idx:
stats = await idx.describe_index_stats()
AsyncIndex mirrors Index but every method is an
async def. It is an async context manager; call close() (or use
async with) to release the underlying HTTP connection pool.
Method groups:
Vectors —
upsert(),upsert_records(),query(),query_namespaces(),fetch(),fetch_by_metadata(),update(),delete(),list(),list_paginated()Stats —
describe_index_stats()Documents —
documents, a lazily-instantiatedAsyncDocumentsnamespace for schema-based indexes (index.documents.upsert,.search,.fetch,.delete,.update,.list,.batch_upsert).Integrated Inference —
search(),search_records()Namespaces —
create_namespace(),describe_namespace(),delete_namespace(),list_namespaces(),list_namespaces_paginated()Bulk Import —
start_import(),describe_import(),cancel_import(),list_imports(),list_imports_paginated()Lifecycle —
close()
- class pinecone.async_client.async_index.AsyncIndex(*, host, api_key=None, additional_headers=None, timeout=30.0, proxy_url=None, proxy_headers=None, ssl_ca_certs=None, ssl_verify=True, source_tag=None, connection_pool_maxsize=0, _limiter_registry=None)[source]¶
Bases:
objectAsynchronous data plane client targeting a specific Pinecone index.
Can be constructed directly with a host URL, or via the
AsyncPinecone.index()factory method.- Parameters:
host (str) – The index-specific data plane host URL.
api_key (str | None) – Pinecone API key. Falls back to
PINECONE_API_KEYenv var.additional_headers (Mapping[str, str] | None) – Extra headers included in every request.
timeout (float) – Request timeout in seconds. Defaults to
30.0.proxy_url (str | None) – HTTP proxy URL for outgoing requests.
ssl_ca_certs (str | None) – Path to a CA certificate bundle for SSL verification.
ssl_verify (bool) – Whether to verify SSL certificates. Defaults to
True.source_tag (str | None) – Tag appended to the User-Agent string for request attribution.
connection_pool_maxsize (int) – Maximum number of connections to keep in the pool.
0(default) uses httpx defaults._limiter_registry (_AdaptiveLimiterRegistry | None)
- Raises:
PineconeValueError – If no API key can be resolved or the host is invalid.
FileNotFoundError – If
ssl_ca_certsnames a path that does not exist, so a mistyped path cannot leave you silently verifying against the default trust store instead. The connection pool is built lazily, so this is raised on the first request rather than at construction. A bundle that exists but cannot be parsed as a certificate raisesssl.SSLErrorat the same point.
Examples
from pinecone import AsyncIndex async with AsyncIndex(host="my-index-abc123.svc.pinecone.io", api_key="...") as idx: print(idx.host)
- __init__(*, host, api_key=None, additional_headers=None, timeout=30.0, proxy_url=None, proxy_headers=None, ssl_ca_certs=None, ssl_verify=True, source_tag=None, connection_pool_maxsize=0, _limiter_registry=None)[source]¶
- property documents: AsyncDocuments¶
Entry point for document operations on a schema-based index.
A schema-based index stores JSON records instead of raw vectors. Use this namespace for document operations such as
upsert,search, andfetch; use the vector methods on this class (upsert(),query(), etc.) for a vector-based index instead. SeeAsyncDocumentsfor the full set of document operations. The namespace instance is built and cached on first access.- Returns:
AsyncDocumentsnamespace instance.
Examples
>>> from pinecone import AsyncPinecone >>> pc = AsyncPinecone(api_key="your-api-key") >>> idx = await pc.index(name="articles-en") >>> await idx.documents.upsert( ... namespace="articles-en", ... documents=[{"_id": "article-101", "title": "Intro to vectors"}], ... )
- async upsert_records(*, records, namespace, timeout=None)[source]¶
Upsert records for indexes with integrated inference.
Records are sent as newline-delimited JSON (NDJSON). Embeddings are generated server-side.
- Parameters:
records (list[dict[str, Any]]) – List of record dicts. Each must contain an
_idoridfield. Additional fields are passed through for server-side embedding.namespace (str) – Target namespace (required). Unlike
upsert(), namespace has no default because the records API requires an explicit namespace (must be non-empty).timeout (float | None)
- Returns:
UpsertRecordsResponsewith the count of records submitted.- Raises:
PineconeValueError – If namespace is not a string or is empty/whitespace, records is empty, or a record is missing an identifier field.
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
response = await idx.upsert_records( namespace="articles-en", records=[ { "_id": "article-101", "text": "Vector databases enable similarity search.", }, {"_id": "article-102", "text": "RAG combines search with LLMs."}, ], ) print(response.record_count)
See also
upsert()— for indexes where you provide your own vectors (no server-side embedding).start_import()— for bulk loading millions of vectors from cloud storage.
- async upsert(*, vectors, namespace='', batch_size=None, show_progress=True, max_concurrency=4, timeout=None)[source]¶
Upsert a batch of vectors into a namespace.
If a vector with the same ID already exists in the namespace, it is overwritten.
Each request is capped on both vector count and encoded payload size; wide vectors or large metadata tend to hit the size cap first. Pass
batch_sizeto split a long sequence of vectors into requests that stay under both limits.- Parameters:
vectors (Sequence[Vector | tuple[str, Sequence[float]] | tuple[str, Sequence[float], Mapping[str, Any]] | Mapping[str, Any]]) – Sequence of vectors to upsert. Each element can be a
Vectorinstance, a tuple of(id, values)or(id, values, metadata), or a dict withid,values, and optionalsparse_values/metadatakeys.namespace (str) – Target namespace. Defaults to the default (empty-string) namespace.
batch_size (int | None) – Split vectors into chunks of this size and send one request per chunk. Default
Nonesends a single request (current behaviour). Must be a positive integer if provided.show_progress (bool) – When
Trueandtqdmis installed, display a progress bar across batches. Has no effect whenbatch_sizeisNoneortqdmis not installed. Defaults toTrue.max_concurrency (int) – Asyncio concurrency limit for concurrent batch requests (range 1–64, default 4). Only used when
batch_sizeis set.timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
UpsertResponsewith the count of vectors upserted. Whenbatch_sizetriggers multiple requests,response_infocarries the aggregate LSN from all successful batches (orNoneif no LSN headers were returned).- Raises:
PineconeTypeError – If a vector element is not a recognized format.
PineconeValueError – If a vector element is malformed.
PineconeValueError – If batch_size is not a positive integer.
PineconeValueError – If max_concurrency is outside [1, 64].
ApiError – If one request exceeds the server’s cap on vectors per request or on encoded request size. Lower
batch_sizeand retry.ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Notes
When
batch_sizeis set, batches are submitted concurrently via anasyncio.Semaphoreofmax_concurrencyslots (default 4, range 1–64). Per-batch HTTP retries are handled by the client’s configuredRetryConfig(connection errors and retryable status codes).Partial failures do not raise. When
batch_sizeis set, per-batch errors are captured on the returnedUpsertResponse(seeresponse.has_errors,response.errors,response.failed_items). To retry only the failures, passresponse.failed_itemsback toupsert(...).Examples
from pinecone import Vector response = await idx.upsert( vectors=[ Vector( id="article-101", values=[0.012, -0.087, 0.153], # truncated; use your actual dimension ), ("article-102", [0.045, 0.021, -0.064]), # truncated {"id": "article-103", "values": [0.091, -0.032, 0.178]}, # truncated ], namespace="articles-en", ) print(response.upserted_count) # Upsert 1000 vectors in batches of 100 response = await idx.upsert( vectors=large_vector_list, batch_size=100, show_progress=True, ) print(response.upserted_count)
See also
upsert_records()— for indexes with integrated inference (text in, server-side embedding).start_import()— for bulk loading millions of vectors from cloud storage.
- async upsert_from_dataframe(df, namespace=None, batch_size=500, show_progress=True, timeout=None, *, on_error=None)[source]¶
Not supported for async clients.
AsyncIndexhas no pandas integration. Batch your data yourself and callupsert()in a loop instead, or usestart_import()for bulk loading from cloud storage.The timeout and on_error parameters exist only for signature parity with the sync and gRPC clients; they are unused because this method always raises.
- Raises:
NotImplementedError – Always.
PineconeValueError – If batch_size is not a positive integer.
- Parameters:
- Return type:
- async query(*, top_k, vector=None, id=None, namespace='', filter=None, include_values=False, include_metadata=False, sparse_vector=None, scan_factor=None, max_candidates=None, timeout=None)[source]¶
Query a namespace for the nearest neighbors of a vector.
Note
Use this method for vector-based indexes, where you supply your own vectors. For indexes with integrated inference, use
search(), which embeds text server-side. For schema-based indexes, which store JSON records instead of raw vectors, usedocuments.- Parameters:
top_k (int) – Number of results to return, 1-10000.
id (str | None) – ID of a stored vector to use as the query.
namespace (str) – Namespace to query. Defaults to the default namespace.
filter (dict[str, Any] | None) – Metadata filter expression.
include_values (bool) – Whether to include vector values in results.
include_metadata (bool) – Whether to include metadata in results.
sparse_vector (SparseValues | dict[str, Any] | None) – Sparse query vector with indices and values. Can be combined with vector for a hybrid query on indexes that support both.
scan_factor (float | None) – Recall/latency trade for dedicated read node (DRN) indexes — a multiplier on how much of the index is scanned. Above 1 scans more and favours recall; below 1 scans less and favours latency. Omit to let the server choose.
max_candidates (int | None) – Recall/latency trade for dedicated read node (DRN) indexes — caps how many candidates are reranked before
top_kis taken. Must be at leasttop_k: a smaller value is rejected rather than clamped, since it could not fill the page.timeout (float | None)
- Returns:
QueryResponsewith matches, namespace, and usage info.- Raises:
PineconeValueError – If top_k is not between 1 and 10000, if
idis combined with eithervectororsparse_vector, if none ofvector,id, orsparse_vectoris provided, or ifidis not a legal vector ID.ApiError – If
scan_factorormax_candidatesis out of range, or the index is not a dense DRN index — both knobs are rejected on on-demand indexes and on sparse indexes.ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
response = await idx.query( top_k=10, vector=[0.012, -0.087, 0.153], # truncated; use your actual dimension ) for match in response.matches: print(match.id, match.score)
Query with a metadata filter:
response = await idx.query( top_k=10, vector=[0.012, -0.087, 0.153], filter={"genre": "comedy", "year": {"$gte": 2020}}, namespace="movies-en", )
- async query_namespaces(*, vector=None, namespaces, metric, top_k=None, filter=None, include_values=False, include_metadata=False, sparse_vector=None, scan_factor=None, max_candidates=None, timeout=None)[source]¶
Query multiple namespaces concurrently and return merged top results.
Fans out individual
query()calls across all given namespaces usingasyncio.gather, then merges results via a heap-based aggregator that returns the overall top-k matches ranked by the specified metric.- Parameters:
vector (Sequence[float] | None) – Dense query vector values. Required for dense and hybrid indexes; omit for sparse-only indexes (use sparse_vector instead).
namespaces (Sequence[str]) – Namespaces to query (must be non-empty). Duplicates are removed while preserving order.
metric (str) – Distance metric —
"cosine","euclidean", or"dotproduct".top_k (int | None) – Maximum number of results to return. Defaults to 10.
filter (Mapping[str, Any] | None) – Metadata filter expression applied to every namespace.
include_values (bool) – Whether to include vector values in results.
include_metadata (bool) – Whether to include metadata in results.
sparse_vector (SparseValues | Mapping[str, Any] | None) – Sparse query vector with indices and values. Required for sparse-only indexes when vector is omitted.
scan_factor (float | None) – Recall/latency trade for dedicated read node (DRN) indexes — a multiplier on how much of the index is scanned. Above 1 scans more and favours recall; below 1 scans less and favours latency. Applied to every namespace queried.
max_candidates (int | None) – Recall/latency trade for dedicated read node (DRN) indexes — caps how many candidates are reranked before
top_kis taken, per namespace. Must be at leasttop_k.timeout (float | None)
- Returns:
QueryNamespacesResultswith the merged top-k matches, total usage, and per-namespace usage.- Raises:
PineconeValueError – If namespaces is empty, if both vector and sparse_vector are absent/empty, or if metric is not one of
"cosine","euclidean", or"dotproduct".ApiError – If any individual namespace query fails.
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
# Dense query results = await idx.query_namespaces( vector=[0.012, -0.087, 0.153], # truncated; use your actual dimension namespaces=["articles-en", "articles-fr", "articles-de"], metric="cosine", top_k=10, ) # Sparse-only query (sparse index) results = await idx.query_namespaces( sparse_vector={"indices": [0, 1, 2], "values": [0.1, 0.2, 0.3]}, namespaces=["docs-en", "docs-fr"], metric="dotproduct", top_k=10, ) for match in results.matches: print(match.id, match.score)
- async fetch(*, ids, namespace='', timeout=None)[source]¶
Fetch vectors by their IDs from a namespace.
- Parameters:
ids (list[str]) – List of vector IDs to fetch. Must be non-empty, and every ID must be 1-512 ASCII characters without a NUL.
namespace (str) – Namespace to fetch from. Defaults to the default namespace.
timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
FetchResponsewith a map of vector IDs to Vector objects, namespace, and usage info. IDs that do not exist are omitted from the map rather than raising an error.- Raises:
PineconeValueError – If ids is empty or contains an ID that is not 1-512 ASCII characters without a NUL.
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
response = await idx.fetch(ids=["article-101", "article-102"]) for vid, vec in response.vectors.items(): print(vid, vec.values)
- async fetch_by_metadata(*, filter, namespace='', limit=None, pagination_token=None, timeout=None)[source]¶
Fetch vectors matching a metadata filter expression.
Returns vectors whose metadata satisfies the given filter, with pagination support.
- Parameters:
filter (dict[str, Any]) – Metadata filter expression. Must carry at least one condition.
namespace (str) – Namespace to fetch from. Defaults to the default namespace.
limit (int | None) – Maximum number of vectors to return per page, 1-10000. Omit to let the server choose the page size.
pagination_token (str | None) – Token from a previous response to fetch the next page. When
None, fetches the first page.timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
FetchByMetadataResponsewith matched vectors, namespace, usage, and pagination token for the next page (if any).- Raises:
PineconeValueError – If
filteris empty orlimitfalls outside 1-10000.ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
response = await idx.fetch_by_metadata( filter={"genre": "comedy", "year": {"$gte": 2020}}, namespace="movies-en", ) for vid, vec in response.vectors.items(): print(vid, vec.values) # Paginate through all results token = response.pagination.next if response.pagination else None while token: response = await idx.fetch_by_metadata( filter={"genre": "comedy", "year": {"$gte": 2020}}, namespace="movies-en", pagination_token=token, ) token = response.pagination.next if response.pagination else None
- async delete(*, ids=None, delete_all=False, filter=None, namespace='', timeout=None)[source]¶
Delete vectors from a namespace by ID, filter, or delete-all flag.
Exactly one of
ids,delete_all, orfiltermust be specified. Deleting IDs that do not exist does not raise an error.idsalongsidefilteris rejected here rather than sent: a filter takes precedence overids, so the request would delete everything the filter matches rather than the intersection of the two. Query with the filter first, then delete the returned ids.A by-filter delete selects on metadata alone, so a text-match operator (
$match_phrase,$match_all,$match_any) in the filter is rejected rather than ignored — evaluated there it would match everything and widen the delete to every record the rest of the filter admits. Text matching belongs insearch().A by-filter delete also reads before it writes, so a dedicated index scaled to zero replicas refuses it; add replicas first. Deleting by ID or with
delete_allis unaffected.- Parameters:
ids (list[str] | None) – List of vector IDs to delete. Every ID must be 1-512 ASCII characters without a NUL.
delete_all (bool) – If True, delete all vectors in the namespace.
filter (dict[str, Any] | None) – Metadata filter expression selecting vectors to delete. Must carry at least one condition.
namespace (str) – Namespace to delete from. Defaults to the default namespace.
timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
None — a successful delete returns no payload.
- Raises:
PineconeValueError – If zero or more than one deletion mode is specified, if
filteris empty, or if an ID is not legal.ApiError – If a by-filter delete uses a text-match operator, or the index is a dedicated index scaled to zero replicas.
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
None
Examples
# Delete by IDs await idx.delete(ids=["article-101", "article-102"]) # Delete all vectors in a namespace await idx.delete(delete_all=True, namespace="articles-deprecated") # Delete by metadata filter await idx.delete(filter={"category": {"$eq": "obsolete"}})
- async update(*, id=None, values=None, sparse_values=None, set_metadata=None, namespace='', filter=None, dry_run=False, timeout=None)[source]¶
Update vectors by ID or metadata filter.
Updates a single vector’s dense values, sparse values, or metadata by identifier, or bulk-updates metadata on all vectors matching a filter.
Exactly one of
idorfiltermust be specified. A by-filter update is metadata-only — it spans every record the filter matches, so it cannot carryvaluesorsparse_values, which belong to one record.A by-filter update selects on metadata alone, so a text-match operator (
$match_phrase,$match_all,$match_any) in the filter is rejected rather than ignored — evaluated there it would match everything and widen the patch to every record the rest of the filter admits. Text matching belongs insearch().A by-filter update also reads before it writes, so a dedicated index scaled to zero replicas refuses it; add replicas first. Updating by ID is unaffected.
- Parameters:
id (str | None) – ID of the vector to update. Must be 1-512 ASCII characters without a NUL.
values (list[float] | None) – New dense vector values. Only with
id.sparse_values (SparseValues | dict[str, Any] | None) – New sparse vector with
indicesandvalueskeys. Only withid.set_metadata (dict[str, Any] | None) – Metadata fields to set or overwrite.
namespace (str) – Namespace to target. Defaults to the default namespace.
filter (dict[str, Any] | None) – Metadata filter expression selecting vectors to update. Must carry at least one condition.
dry_run (bool) – If True, return the count of records that would be affected without applying changes. Only applies to filter-based updates.
timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
UpdateResponsewith matched_records count (when available).- Raises:
PineconeValueError – If both or neither of
idandfilterare provided, iffilteris combined withvaluesorsparse_values, or iffilteris empty.ApiError – If a by-filter update uses a text-match operator, or the index is a dedicated index scaled to zero replicas.
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
# Update by ID # truncated; use your actual dimension await idx.update(id="article-101", values=[0.012, -0.087, 0.153]) # Bulk-update metadata by filter await idx.update( filter={"genre": {"$eq": "drama"}}, set_metadata={"year": 2020}, )
- async search(*, namespace, top_k=None, inputs=None, vector=None, id=None, filter=None, fields=None, rerank=None, match_terms=None, query=None, timeout=None)[source]¶
Search records by text, vector, or ID with optional reranking.
Searches a namespace using integrated inference (text inputs embedded server-side), a raw vector, or an existing record ID as the query.
Note
Use this method for indexes with integrated inference. For vector-based indexes, where you supply your own vectors, use
query().- Parameters:
namespace (str) – Namespace to search in (required).
top_k (int) – Number of results to return (must be >= 1).
inputs (SearchInputs | dict[str, Any] | None) – Inputs for server-side embedding (e.g.
{"text": "query text"}). UseSearchInputsfor typed key validation and IDE autocompletion (e.g.SearchInputs(text="query text")).vector (list[float] | dict[str, Any] | None) – Query vector. Pass a
list[float]for a dense-only query (wrapped automatically as{"values": [...]}) or a dict for sparse/hybrid queries with keysvalues,sparse_indices, and/orsparse_values(passed through as-is). SeeSearchQueryVectorfor the typed helper.id (str | None) – ID of an existing record to use as the query.
filter (dict[str, Any] | None) – Metadata filter expression.
fields (list[str] | None) – Field names to include in results. When
None, the server returns all available fields.rerank (RerankConfig | dict[str, Any] | None) – Reranking configuration with
model(required),rank_fields(required), and optionaltop_n,parameters,querykeys. UseRerankConfigfor IDE autocompletion.match_terms (dict[str, Any] | None) – Term-matching constraint for sparse search. Requires keys
"strategy"(currently only"all") and"terms"(list of strings). Valid only on a text query — combined withvectororidit is rejected — and only on a sparse index whose embedding model supports it; the server names the supported model when it refuses.Nonedisables term matching.query (dict[str, Any] | None) – Legacy query body containing
top_kplus one ofinputs,vector, orid. Prefer passing these fields directly.timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
SearchRecordsResponsewith hits and usage statistics.- Raises:
PineconeValueError – If
namespaceis not a string,top_k < 1, orrerankis missing required keys.ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
response = await idx.search( namespace="articles-en", top_k=10, inputs={"text": "benefits of vector databases for search"}, ) for hit in response.result.hits: print(hit.id, hit.score) response = await idx.search( namespace="articles-en", top_k=10, inputs={"text": "benefits of vector databases"}, rerank={ "model": "bge-reranker-v2-m3", "rank_fields": ["text"], "top_n": 5, }, ) for hit in response.result.hits: print(hit.id, hit.score)
Note
Use inline
rerankwhen searching and reranking in a single call. Usepc.inference.rerank()when reranking results from a different source or when you need to rerank without searching.
- async search_records(*, namespace, top_k=None, inputs=None, vector=None, id=None, filter=None, fields=None, rerank=None, match_terms=None, query=None, timeout=None)[source]¶
Alias for
search().Prefer calling
search()directly — this alias exists for backwards compatibility.
- async list_paginated(*, prefix=None, limit=None, pagination_token=None, namespace='', timeout=None)[source]¶
Fetch a single page of vector IDs from a namespace.
- Parameters:
prefix (str | None) – Return only IDs starting with this prefix. At most 512 ASCII characters without a NUL; the empty prefix matches everything.
limit (int | None) – Maximum number of IDs to return in this page, 1-100.
pagination_token (str | None) – Token from a previous response to fetch the next page.
namespace (str) – Namespace to list from. Defaults to the default namespace.
timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
ListResponsewith vector IDs, pagination info, namespace, and usage.- Raises:
PineconeValueError – If
prefixis not legal orlimitfalls outside 1-100.ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
response = await idx.list_paginated(prefix="doc1#", limit=50) for item in response.vectors: print(item.id)
- list(*, prefix=None, limit=None, namespace='', timeout=None)[source]¶
List vector IDs in a namespace, automatically following pagination.
Yields one
ListResponseper page. The generator automatically follows pagination tokens until all pages have been retrieved.- Parameters:
prefix (str | None) – Return only IDs starting with this prefix. At most 512 ASCII characters without a NUL; the empty prefix matches everything.
limit (int | None) – Maximum number of IDs to return per page, 1-100.
namespace (str) – Namespace to list from. Defaults to the default namespace.
timeout (float | None) – Per-request timeout in seconds, applied to each underlying page request. Overrides the client-level default for this call only.
- Yields:
ListResponsefor each page of results.- Raises:
PineconeValueError – If
prefixis not legal orlimitfalls outside 1-100.ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
async for page in idx.list(prefix="doc1#"): for item in page.vectors: print(item.id)
- async describe_index_stats(*, filter=None, timeout=None)[source]¶
Return statistics for this index.
Returns aggregate statistics including total vector count, per-namespace vector counts, dimension, and index fullness.
- Parameters:
filter (dict[str, Any] | None) – Metadata filter expression. Accepted for API compatibility, but a non-empty filter is rejected for every index type, so the call fails instead of returning filtered counts. Leave it unset: the statistics returned always describe the whole index.
timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
DescribeIndexStatsResponsewith namespace summaries, dimension, total vector count, and fullness metrics.- Raises:
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
stats = await idx.describe_index_stats() print(stats.total_vector_count, stats.dimension)
- async create_namespace(*, name, schema=None)[source]¶
Create a named namespace in the index.
- Parameters:
name (str) – Name for the new namespace. Must be ASCII, must not contain the NUL character, and must be 1-512 characters long.
__default__is reserved and cannot be created: it names the namespace requests address when they omit a namespace, so it always exists.schema (dict[str, Any] | None) – Optional metadata-index configuration,
{"fields": {<field>: {"filterable": True}}}. Omitting it does not mean “index everything”: the namespace inherits the index’s own metadata-index configuration, so an index that restricts which fields are indexed passes that restriction on. Supply schema to override the inherited configuration for this namespace, indexing exactly the fields listed.filterableis required on each field and must beTrue— to leave a field unindexed, omit it fromfields.
- Returns:
NamespaceDescriptionwith the namespace name, record count, schema, indexed fields, andsize_bytes.- Raises:
PineconeValueError – If name violates the rules above, or schema is malformed. Raised before any HTTP request is made.
ConflictError – a namespace of that name already exists.
ApiError – If the API returns any other error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
ns = await idx.create_namespace(name="movies-en") print(ns.name, ns.record_count, ns.size_bytes) ns = await idx.create_namespace( name="movies-en", schema={"fields": {"genre": {"filterable": True}}}, )
- async describe_namespace(*, name=None, **kwargs)[source]¶
Describe a namespace by name.
This operation is rate limited per index, independently of the other namespace operations. Prefer
list_namespaces()when describing more than one namespace: it returns the same information for every namespace in a single request and is not subject to that limit.- Parameters:
- Returns:
NamespaceDescriptionwith the namespace name, record count, schema, indexed fields, andsize_bytes.size_bytesis approximate: data written before size tracking reads as 0, and recently deleted data may still be counted; compaction converges the value.- Raises:
PineconeValueError – If name violates the rules above. Raised before any HTTP request is made.
NotFoundError – no namespace of that name exists on the index.
RateLimitError – this operation’s per-index limit was exceeded. Use
list_namespaces()to describe many namespaces.ApiError – If the API returns any other error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
ns = await idx.describe_namespace(name="movies-en") print(ns.name, ns.record_count, ns.size_bytes) default_ns = await idx.describe_namespace(name="__default__")
- async delete_namespace(*, name=None, timeout=None, **kwargs)[source]¶
Delete a namespace by name, removing all its vectors.
Deleting a namespace is irreversible; all data in it is permanently deleted.
- Parameters:
- Returns:
None — a successful delete returns no payload.
- Raises:
PineconeValueError – If name violates the rules above. Raised before any HTTP request is made.
NotFoundError – no namespace of that name exists on the index.
ApiError – If the API returns any other error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
None
Examples
await idx.delete_namespace(name="movies-deprecated")
- async list_namespaces_paginated(*, prefix=None, limit=None, pagination_token=None)[source]¶
Fetch a single page of namespace descriptions.
- Parameters:
prefix (str | None) – Return only namespaces whose names start with this prefix. Must be ASCII, must not contain the NUL character, and must be at most 512 characters. The empty prefix matches every namespace.
limit (int | None) – Maximum number of namespaces to return in this page, 1-100.
pagination_token (str | None) – Token from a previous response to fetch the next page.
- Returns:
ListNamespacesResponsewith namespace descriptions, pagination info, and total count. Each description carriessize_bytes.- Raises:
PineconeValueError – If prefix or limit violates the rules above. Raised before any HTTP request is made.
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
response = await idx.list_namespaces_paginated(prefix="prod-", limit=10) for ns in response.namespaces: print(ns.name, ns.record_count, ns.size_bytes)
- list_namespaces(*, prefix=None, limit=None)[source]¶
List namespaces, automatically following pagination.
Yields one
ListNamespacesResponseper page. The generator automatically follows pagination tokens until all pages have been retrieved.Because it describes every namespace in one request per page, this is the operation to reach for over repeated
describe_namespace()calls, which are rate limited per index.- Parameters:
- Yields:
ListNamespacesResponsefor each page of results. EachNamespaceDescriptioncarriessize_bytes.- Raises:
PineconeValueError – If prefix or limit violates the rules above. Raised on first iteration, before any HTTP request is made.
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
async for page in idx.list_namespaces(prefix="prod-"): for ns in page.namespaces: print(ns.name, ns.record_count, ns.size_bytes)
- async start_import(uri, *, error_mode=None, integration_id=None)[source]¶
Start a bulk import operation from an external data source.
Initiates an asynchronous bulk import of vectors from cloud storage into the index. The import runs server-side; use
describe_import()to poll for progress and completion.Note
The import URI must point to a directory of Parquet files in cloud storage. Each Parquet file must follow the Pinecone-required schema. See Pinecone import docs for the required Parquet schema and supported storage formats.
- Parameters:
uri (str) – Directory prefix holding the Parquet files, not a single file. Three forms are accepted:
s3://for Amazon S3,gs://for Google Cloud Storage, and anhttps://URL naming an Azure Blob Storage container.s3://additionally requires that the index itself be hosted on AWS.error_mode (str | None) – How to handle a record the import cannot read.
"continue"skips it and imports the rest;"abort"ends the whole import at the first such record. Case-insensitive. Defaults to"abort"when omitted, so an unreadable record fails the import unless you opt into skipping.integration_id (str | None) – Optional integration ID for the import.
- Returns:
StartImportResponsewith the ID of the created import operation.- Raises:
PineconeValueError – If
error_modeis supplied but not"continue"or"abort".ApiError – If
uriis empty or longer than the server accepts, uses an unsupported scheme, is ans3://URI on an index not hosted on AWS, or names an S3 directory bucket, which imports do not support.ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
import asyncio # Start an import and poll until complete response = await idx.start_import(uri="s3://my-bucket/vectors/") import_id = response.id import_op = await idx.describe_import(import_id) while import_op.status not in ("Completed", "Failed", "Cancelled"): await asyncio.sleep(10) import_op = await idx.describe_import(import_id) print(f"Status: {import_op.status}, records imported: {import_op.records_imported}")
# Skip unreadable records instead of failing the import response = await idx.start_import( uri="s3://my-bucket/vectors/", error_mode="continue", )
See also
upsert()— for upserting vectors directly in small batches (single request per call).upsert_records()— for indexes with integrated inference (text in, server-side embedding).upsert_from_dataframe()— for loading vectors from a pandas DataFrame with automatic batching.
- async describe_import(id)[source]¶
Describe a bulk import operation by ID.
- Parameters:
id (str | int) – Import operation ID. Integers are converted to strings silently.
- Returns:
ImportModelwith the import operation details.- Raises:
PineconeValueError – If the ID is empty or exceeds 1000 characters.
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
import_op = await idx.describe_import("import-123") print(import_op.status, import_op.percent_complete)
- async cancel_import(id)[source]¶
Cancel a bulk import operation by ID.
- Parameters:
id (str | int) – Import operation ID. Integers are converted to strings silently.
- Returns:
None — a successful cancellation returns no payload.
- Raises:
PineconeValueError – If the ID is empty or exceeds 1000 characters.
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
None
Examples
await idx.cancel_import("import-123")
- list_imports(*, limit=None, pagination_token=None)[source]¶
List bulk import operations, automatically following pagination.
Yields individual
ImportModelobjects, fetching additional pages transparently until all results have been returned.- Parameters:
- Yields:
ImportModelfor each import operation.- Raises:
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
async for imp in idx.list_imports(): print(imp.id, imp.status)
- async list_imports_paginated(*, limit=None, pagination_token=None)[source]¶
Fetch a single page of bulk import operations.
Returns an
ImportListfor one page. The caller is responsible for managing the pagination token.- Parameters:
- Returns:
ImportListwith the import operations for the requested page.- Raises:
ApiError – If the API returns an error response (e.g. authentication failure or server error).
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
Examples
page = await idx.list_imports_paginated(limit=10) for imp in page: print(imp.id, imp.status)
- async close()[source]¶
Close the underlying HTTP client and release its resources.
Call this when you are done making requests through this index, or use the index as an async context manager so it closes automatically.
- Returns:
None.
- Return type:
None
Examples
idx = await pc.index(name="articles-en") async with idx: await idx.upsert(namespace="articles-en", vectors=[...])
- async __aenter__()[source]¶
Enter the async context manager, returning this index.
- Returns:
This
AsyncIndexinstance.- Return type:
Examples
idx = await pc.index(name="articles-en") async with idx: await idx.upsert(namespace="articles-en", vectors=[...])
AsyncDocuments¶
- class pinecone.async_client.documents.AsyncDocuments(*, http)[source]¶
Bases:
objectDocument data-plane operations for a schema-based index (2026-07 API).
Accessed via
documents. Not constructed directly — the parentAsyncIndexbuilds and caches its own instance on first access.Examples
from pinecone import AsyncPinecone pc = AsyncPinecone(api_key="your-api-key") index = await pc.index(name="articles-en") async with index: await index.documents.upsert( namespace="articles-en", documents=[{"_id": "article-101", "title": "Intro to vectors"}], )
- Parameters:
http (AsyncHTTPClient)
- async batch_upsert(*, namespace, documents, batch_size=50, max_concurrency=4, show_progress=True, timeout=None)[source]¶
Upsert a large list of documents in parallel batches.
Splits documents into chunks of batch_size and submits them concurrently behind an
asyncio.Semaphoreof max_concurrency slots. Per-batch HTTP failures are captured in the returnedBatchResultrather than raised, so one failed batch does not abort the rest; retry only the failures by passingresult.failed_itemsback in.- Parameters:
namespace (str) – Target namespace (required, non-empty).
documents (Sequence[Mapping[str, Any] | DocumentRecord]) – Documents to upsert. Each element is a dict with an
_idkey or aDocumentRecord; IDs must be unique across the whole list.batch_size (int) – Maximum documents per request (1-1000, default 50).
max_concurrency (int) – Asyncio concurrency limit for concurrent batch requests (1-64, default 4).
show_progress (bool) – Display a progress bar when
tqdmis installed. Defaults toTrue.timeout (float | None) – Per-request timeout in seconds applied to each batch’s request — not to the whole call.
- Returns:
BatchResultwith aggregated success and failure counts; per-batch errors are inresult.errorsand the affected documents inresult.failed_items.- Raises:
PineconeValueError – If
namespaceis empty,documentsis empty or contains an invalid or duplicate_id,batch_sizeis outside [1, 1000], ormax_concurrencyis outside [1, 64].- Return type:
BatchResult
Examples
documents = [ {"_id": f"article-{i}", "title": f"Article {i}"} for i in range(5000) ] result = await idx.documents.batch_upsert( namespace="articles-en", documents=documents, batch_size=100, max_concurrency=8, ) print(result.successful_item_count, result.failed_item_count)
See also
upsert()— for a single-request upsert of up to 1000 documents.
- async delete(*, namespace, ids=None, filter=None, delete_all=False, timeout=None)[source]¶
Delete documents from a namespace by ID, filter, or delete-all flag.
Exactly one of
ids,filter, ordelete_allmust be provided. Deleting IDs that do not exist does not raise an error.Pinecone applies the delete asynchronously. For a filtered delete,
response.matched_recordsis the point-in-time count of matching documents when the delete was accepted, not a guarantee of the number ultimately deleted.- Parameters:
namespace (str) – Namespace to delete from (required, non-empty).
ids (Sequence[str] | None) – Document IDs to delete (1-1000). Mutually exclusive with
filteranddelete_all.filter (Mapping[str, Any] | None) – Non-empty metadata filter expression selecting the documents to delete. Text-match operators (
$match_phrase,$match_all,$match_any) are not supported here. Mutually exclusive withidsanddelete_all. Not available on an index with dedicated read capacity scaled to 0 replicas — scale up replicas first.delete_all (bool) – If
True, delete all documents in the namespace. Mutually exclusive withidsandfilter.timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
DeleteDocumentsResponse—matched_recordsis populated only for filtered deletes (Nonefor by-ID and delete-all paths, and when the count could not be read in time).- Raises:
PineconeValueError – If
namespaceis empty, zero or more than one ofids/filter/delete_allis provided,filteris an empty dict, oridsexceeds 1000 entries.ApiError – If the API returns an error response; the server’s error text is surfaced intact.
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
DeleteDocumentsResponse
Examples
await idx.documents.delete(namespace="articles-en", ids=["article-101"]) response = await idx.documents.delete( namespace="articles-en", filter={"category": {"$eq": "obsolete"}}, ) print(response.matched_records) await idx.documents.delete(namespace="articles-old", delete_all=True)
- async fetch(*, namespace, ids=None, filter=None, include_fields=None, pagination_token=None, timeout=None)[source]¶
Fetch documents from a namespace by ID or by metadata filter.
Exactly one of
idsorfiltermust be provided. A filtered fetch returns matching documents a page at a time — a page holds up to 10000 documents and the page size is fixed — withresponse.paginationcarrying the token for the next page.- Parameters:
namespace (str) – Namespace to fetch from (required, non-empty).
ids (Sequence[str] | None) – Document IDs to fetch (1-1000). IDs that do not exist are omitted from the result rather than raising. Mutually exclusive with
filter.filter (Mapping[str, Any] | None) – Non-empty metadata filter expression selecting the documents to fetch. Mutually exclusive with
ids.include_fields (Sequence[str] | None) – Document fields to include in the response.
None(default) returns all fields.pagination_token (str | None) – Token from a previous filtered fetch response to retrieve the next page. Only valid together with
filter.timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
FetchDocumentsResponsewithdocuments(a map of document ID to document),namespace,usage, and — for filtered fetches with more results —pagination.- Raises:
PineconeValueError – If
namespaceis empty, both or neither ofidsandfilterare provided,filteris an empty dict,idsexceeds 1000 entries, orpagination_tokenis passed withoutfilter.ApiError – If the API returns an error response; the server’s error text is surfaced intact.
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
FetchDocumentsResponse
Examples
response = await idx.documents.fetch( namespace="articles-en", ids=["article-101", "article-102"], ) for doc_id, doc in response.documents.items(): print(doc_id, doc.title) response = await idx.documents.fetch( namespace="articles-en", filter={"category": {"$eq": "tech"}}, ) while response.pagination is not None: response = await idx.documents.fetch( namespace="articles-en", filter={"category": {"$eq": "tech"}}, pagination_token=response.pagination.next, )
- list(*, namespace, prefix=None, limit=None, pagination_token=None, timeout=None)[source]¶
List the documents in a namespace, following pagination lazily.
Returns an
AsyncPaginatorthat fetches pages on demand and stops when the server returns nopaginationtoken. Documents come back in sorted order by ID, carrying only their_id.- Parameters:
namespace (str) – Namespace to list from (required, non-empty).
prefix (str | None) – Return only documents whose IDs begin with this prefix. At most 512 characters, ASCII only (
\x01-\x7F).Nonelists every document.limit (int | None) – Maximum number of documents the server returns per page, 1-100. This tunes the page size, not the total — the paginator follows every page. To stop early, break out of the
async forloop.pagination_token (str | None) – Token from a previous list response to resume from, rather than starting at the first page.
timeout (float | None) – Per-request timeout in seconds, applied to each page request. Overrides the client-level default.
- Returns:
AsyncPaginatoroverListedDocumentRecordobjects. Supportsasync for,to_list(), andpages().- Raises:
PineconeValueError – If
namespaceis empty,prefixviolates the rules above, orlimitfalls outside 1-100. Raised by this call, before the paginator is returned.ApiError – If the API returns an error response; the server’s error text is surfaced intact.
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If a page request exceeds the configured timeout.
- Return type:
AsyncPaginator[ListedDocumentRecord]
Examples
async for doc in idx.documents.list(namespace="articles-en", prefix="article-1"): print(doc.id) paginator = idx.documents.list(namespace="articles-en", limit=20) async for page in paginator.pages(): print(len(page.items), page.pagination_token)
- async search(*, namespace, score_by, top_k, include_fields=None, filter=None, timeout=None)[source]¶
Search documents in a namespace using one or more scoring methods.
Returns the
top_kmost similar documents ranked by the given scoring methods (dense vector, sparse vector, BM25 text, or Lucene query string similarity).- Parameters:
namespace (str) – Namespace to search (required, non-empty).
score_by (Sequence[TextQuery | QueryStringQuery | DenseVectorQuery | SparseVectorQuery | Mapping[str, Any]]) – Scoring methods to rank documents by (1-100 clauses). Items are typed variants (
TextQuery,QueryStringQuery,DenseVectorQuery,SparseVectorQuery) or plain dicts with atypekey.textandquery_stringclauses may be combined; adense_vectororsparse_vectorclause must appear alone.top_k (int) – Number of top-ranked documents to return (1-10000).
include_fields (Sequence[str] | None) – Document fields to include in the results.
None(default) returns all fields;[]returns only_idand score.filter (Mapping[str, Any] | None) – Metadata filter expression restricting the documents searched, or
None.timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
SearchDocumentsResponsewithmatches(ordered from most to least similar),namespace, andusage.- Raises:
PineconeValueError – If
namespaceis empty,score_byis empty, over 100 clauses, or combines a vector clause with any other clause, ortop_kis outside [1, 10000].ApiError – If the API returns an error response; the server’s error text is surfaced intact.
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
SearchDocumentsResponse
Examples
from pinecone import TextQuery response = await idx.documents.search( namespace="articles-en", top_k=5, score_by=[TextQuery(query="machine learning", fields=["content"])], include_fields=["title", "category"], filter={"category": {"$eq": "tech"}}, ) for doc in response.matches: print(doc._id, doc._score)
- async update(*, namespace, documents=None, filter=None, set_fields=None, remove_fields=None, timeout=None)[source]¶
Apply partial updates to documents in a namespace.
Documents are selected either per ID with
documents, or in bulk withfilterplusset_fieldsand/orremove_fields. The two shapes are mutually exclusive. Fields that are not mentioned are left unchanged, and an update naming a document that does not exist is accepted as a no-op rather than raising.Pinecone applies the update asynchronously — for a filtered update,
response.matched_recordsis the point-in-time count of matching documents when the update was accepted, not a guarantee of the number ultimately patched.- Parameters:
namespace (str) – Namespace to update in (required, non-empty).
documents (Sequence[Mapping[str, Any] | UpdateDocumentRecord] | None) – Per-document patches (1-1000). Each element is a dict with an
_idkey or anUpdateDocumentRecord. Any key other than_idand_remove_fieldssets a new value for that field; the names in_remove_fieldsare removed from the document._idvalues must be unique within the request. Mutually exclusive withfilter,set_fields, andremove_fields.filter (Mapping[str, Any] | None) – Non-empty metadata filter expression selecting the documents to patch. Text-match operators (
$match_phrase,$match_all,$match_any) are not supported here. Mutually exclusive withdocuments. Not available on an index with dedicated read capacity scaled to 0 replicas — scale up replicas first.set_fields (Mapping[str, Any] | None) – Fields to set on every document matching
filter, and the values to set them to. Only valid withfilter.remove_fields (Sequence[str] | None) – Names of the fields to remove from every document matching
filter. Only valid withfilter.timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
UpdateDocumentsResponse—matched_recordsis populated only for filtered updates (Nonefor per-ID updates, and when the count could not be read in time).- Raises:
PineconeValueError – If
namespaceis empty,documentsis combined with any by-filter field, neitherdocumentsnorfilteris given,set_fieldsorremove_fieldsis passed withoutfilter,filteris an empty dict or carries no patch,documentsis empty or exceeds 1000 entries, or a patch is malformed — the message names the offending position.ApiError – If the API returns an error response; the server’s error text is surfaced intact. A field value of
Noneis rejected server-side — use_remove_fields(per-ID) orremove_fields(by-filter) to remove a field.PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
UpdateDocumentsResponse
Examples
await idx.documents.update( namespace="articles-en", documents=[ {"_id": "article-101", "title": "Updated title"}, {"_id": "article-102", "_remove_fields": ["content"]}, ], ) response = await idx.documents.update( namespace="articles-en", filter={"category": {"$eq": "news"}}, set_fields={"category": "archive"}, remove_fields=["content"], ) print(response.matched_records)
- async upsert(*, namespace, documents, timeout=None)[source]¶
Upsert documents into a namespace.
Each document must include an
_idfield (a unique, non-empty ASCII string of at most 512 characters) along with fields defined in the index schema or arbitrary metadata fields. If a document with the same_idalready exists in the namespace, it is overwritten.Pinecone applies the upsert asynchronously, so documents may not be immediately visible to
search()orfetch().- Parameters:
namespace (str) – Target namespace (required, non-empty).
documents (Sequence[Mapping[str, Any] | DocumentRecord]) – The documents to upsert (1-1000 per request). Each element is a dict with an
_idkey or aDocumentRecord. For larger lists, usebatch_upsert().timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.
- Returns:
UpsertDocumentsResponsewith the count of documents accepted for upsert.- Raises:
PineconeValueError – If
namespaceis empty,documentsis empty or over 1000 entries, or any document has a missing, empty, non-string, non-ASCII, over-512-character, or duplicate_id— the message names the offending document’s position.ApiError – If one request exceeds the server’s cap on encoded request size — a document count inside the accepted range can still be too large. Send fewer documents per request, or use
batch_upsert().ApiError – If the API returns an error response; the server’s error text is surfaced intact.
PineconeConnectionError – If a network-level connection fails (DNS, refused, transport error).
PineconeTimeoutError – If the request exceeds the configured timeout.
- Return type:
UpsertDocumentsResponse
Examples
response = await idx.documents.upsert( namespace="articles-en", documents=[ {"_id": "article-101", "title": "Intro to vectors"}, {"_id": "article-102", "title": "Advanced retrieval"}, ], ) print(response.upserted_count)
See also
batch_upsert()— for upserting large document lists in parallel batches.upsert()— for indexes where you provide your own vectors.