Index

Obtain an Index instance via pinecone.Pinecone.index().

from pinecone import Pinecone

pc = Pinecone(api_key="your-api-key")

# Resolve host automatically by index name
idx = pc.index("my-index")

# — or — connect directly with a host URL
idx = pc.index(host="my-index-abc123.svc.pinecone.io")

Method groups:

class pinecone.index.Index(*, 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, **kwargs)[source]

Bases: object

Synchronous data plane client targeting a specific Pinecone index.

Can be constructed directly with a host URL, or via the Pinecone.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_KEY env 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.

  • pool_threads (int | None) – Tune the thread pool used by the legacy async_req=True execution model on upsert, query, describe_index_stats, and list_paginated. Defaults to 10. The pool is lazy-constructed on first async_req=True call and shut down by close(); multiprocessing.pool is not imported until then. For new code, prefer AsyncIndex or concurrent.futures.ThreadPoolExecutor. This kwarg exists for backcompat with pre-rewrite callers.

  • proxy_headers (Mapping[str, str] | None)

  • kwargs (Any)

Raises:
  • PineconeValueError – If no API key can be resolved or the host is invalid.

  • FileNotFoundError – If ssl_ca_certs names a path that does not exist, raised when the client is constructed, so a mistyped path cannot leave you silently verifying against the default trust store instead. A bundle that exists but cannot be parsed as a certificate raises ssl.SSLError instead.

Examples

from pinecone import Index

idx = Index(host="movie-recs-abc123.svc.pinecone.io", api_key="...")
__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, **kwargs)[source]
Parameters:
Return type:

None

property host: str

The data plane host URL for this index.

property documents: Documents

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, and fetch; use the vector methods on this class (upsert(), query(), etc.) for a vector-based index instead. See Documents for the full set of document operations. The namespace instance is built and cached on first access.

Returns:

Documents namespace instance.

Examples

>>> from pinecone import Pinecone
>>> pc = Pinecone(api_key="your-api-key")
>>> idx = pc.index(name="articles-en")
>>> idx.documents.upsert(
...     namespace="articles-en",
...     documents=[{"_id": "article-101", "title": "Intro to vectors"}],
... )
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_size to 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 Vector instance, a tuple of (id, values) or (id, values, metadata), or a dict with id, values, and optional sparse_values / metadata keys.

  • 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 None sends a single request (current behaviour). Must be a positive integer if provided.

  • show_progress (bool) – When True and tqdm is installed, display a progress bar across batches. Has no effect when batch_size is None or tqdm is not installed. Defaults to True.

  • max_concurrency (int) – Thread pool size for concurrent batch requests (range 1–64, default 4). Only used when batch_size is set.

  • timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.

Returns:

UpsertResponse with the count of vectors upserted. When batch_size triggers multiple requests, response_info carries the aggregate LSN from all successful batches (or None if 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_size and 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. Pass timeout=<seconds> to override the client-level default for this call only.

Return type:

UpsertResponse

Notes

When batch_size is set, batches are submitted in parallel via a ThreadPoolExecutor of max_concurrency workers (default 4, range 1–64). Per-batch HTTP retries are handled by the client’s configured RetryConfig (connection errors and retryable status codes).

Partial failures do not raise. When batch_size is set, per-batch errors are captured on the returned UpsertResponse (see response.has_errors, response.errors, response.failed_items). To retry only the failures, pass response.failed_items back to upsert(...).

Examples

from pinecone import Index, Vector

idx = Index(host="article-search-abc123.svc.pinecone.io", api_key="...")
response = 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 = idx.upsert(
    vectors=large_vector_list,
    batch_size=100,
    show_progress=True,
)
print(response.upserted_count)

See also

upsert_from_dataframe(df, namespace=None, batch_size=500, show_progress=True, timeout=None, *, on_error=None)[source]

Upsert vectors from a pandas DataFrame.

Convenience method that accepts a DataFrame with columns id, values, and optionally sparse_values and metadata, batches the rows, and upserts them via upsert().

Parameters:
  • df (pd.DataFrame) – A pandas.DataFrame with at least id and values columns. sparse_values and metadata columns are included when present and non-None.

  • namespace (str | None) – Target namespace. Defaults to the default namespace.

  • batch_size (int) – Number of rows per upsert batch. Defaults to 500.

  • show_progress (bool) – If True and tqdm is installed, display a progress bar. If tqdm is not installed, silently falls back to no progress bar.

  • timeout (float | None) – Client-side request timeout in seconds applied to each batch’s upsert request — not to the DataFrame as a whole. None (default) uses the client-level default. Raise it to accommodate large or slow batches.

  • on_error (Literal['raise', 'collect'] | None) – What to do when some batches fail. "collect" (the default) returns an UpsertResponse carrying failed_item_count, errors, and failed_items. "raise" re-raises the lowest-indexed batch failure once every batch has settled, with the partial result attached to the exception’s response attribute.

Returns:

UpsertResponse with the total count of vectors upserted across all batches.

Raises:
Return type:

UpsertResponse

Examples

# Upsert article embeddings from a DataFrame
import pandas as pd
from pinecone import Pinecone

pc = Pinecone(api_key="your-api-key")
index = pc.index("article-search")
df = pd.DataFrame([
    {"id": "article-101", "values": [0.012, -0.087, 0.153]},
    {"id": "article-102", "values": [0.045, 0.021, -0.064]},
])
response = index.upsert_from_dataframe(df)
response.upserted_count  # 2

# Upsert with metadata, a custom namespace, and a smaller batch size
df = pd.DataFrame([
    {
        "id": "article-101",
        "values": [0.012, -0.087, 0.153],
        "metadata": {"topic": "science", "year": 2024},
    },
    {
        "id": "article-102",
        "values": [0.045, 0.021, -0.064],
        "metadata": {"topic": "technology", "year": 2024},
    },
])
response = index.upsert_from_dataframe(
    df,
    namespace="articles-en",
    batch_size=100,
)

See also

  • upsert() — for upserting vectors directly (accepts optional batch_size; no DataFrame dependency).

  • upsert_records() — for indexes with integrated inference (text in, server-side embedding).

  • start_import() — for bulk loading millions of vectors from cloud storage.

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 _id or id field. 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:

UpsertRecordsResponse with 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:

UpsertRecordsResponse

Examples

response = idx.upsert_records(
    namespace="articles-en",
    records=[
        {"_id": "article-101", "text": "Vector databases for 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).

  • upsert_from_dataframe() — for loading vectors from a pandas DataFrame with automatic batching.

  • start_import() — for bulk loading millions of vectors from cloud storage.

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, use documents.

Parameters:
  • top_k (int) – Number of results to return, 1-10000.

  • vector (list[float] | None) – Dense query vector values.

  • 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_k is taken. Must be at least top_k: a smaller value is rejected rather than clamped, since it could not fill the page.

  • timeout (float | None)

Returns:

QueryResponse with matches, namespace, and usage info.

Raises:
  • PineconeValueError – If top_k is not between 1 and 10000, if id is combined with either vector or sparse_vector, if none of vector, id, or sparse_vector is provided, or if id is not a legal vector ID.

  • ApiError – If scan_factor or max_candidates is 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:

QueryResponse

Examples

response = 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 = idx.query(
    top_k=10,
    vector=[0.012, -0.087, 0.153],
    filter={"genre": "comedy", "year": {"$gte": 2020}},
    namespace="movies-en",
)
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 in parallel and return merged top results.

Fans out individual query() calls across all given namespaces using a thread pool, 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_k is taken, per namespace. Must be at least top_k.

  • timeout (float | None)

Returns:

QueryNamespacesResults with 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:

QueryNamespacesResults

Examples

# Dense query
results = 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 = 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)
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:

FetchResponse with 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:

FetchResponse

Examples

response = idx.fetch(ids=["article-101", "article-102"])
for vid, vec in response.vectors.items():
    print(vid, vec.values)
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:

FetchByMetadataResponse with matched vectors, namespace, usage, and pagination token for the next page (if any).

Raises:
Return type:

FetchByMetadataResponse

Examples

response = 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 = 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
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, or filter must be specified. Deleting IDs that do not exist does not raise an error.

ids alongside filter is rejected here rather than sent: a filter takes precedence over ids, 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 in search().

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_all is 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 filter is 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
idx.delete(ids=["article-101", "article-102"])

# Delete all vectors in a namespace
idx.delete(delete_all=True, namespace="articles-deprecated")

# Delete by metadata filter
idx.delete(filter={"category": {"$eq": "obsolete"}})
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 id or filter must be specified. A by-filter update is metadata-only — it spans every record the filter matches, so it cannot carry values or sparse_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 in search().

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 indices and values keys. Only with id.

  • 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:

UpdateResponse with matched_records count (when available).

Raises:
  • PineconeValueError – If both or neither of id and filter are provided, if filter is combined with values or sparse_values, or if filter is 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:

UpdateResponse

Examples

# Update by ID
# truncated; use your actual dimension
idx.update(id="article-101", values=[0.012, -0.087, 0.153])

# Bulk-update metadata by filter
idx.update(
    filter={"genre": {"$eq": "drama"}},
    set_metadata={"year": 2020},
)
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:

DescribeIndexStatsResponse with 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:

DescribeIndexStatsResponse

Examples

stats = idx.describe_index_stats()
print(stats.total_vector_count, stats.dimension)
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"}). Use SearchInputs for 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 keys values, sparse_indices, and/or sparse_values (passed through as-is). See SearchQueryVector for 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 optional top_n, parameters, query keys. Use RerankConfig for 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 with vector or id it is rejected — and only on a sparse index whose embedding model supports it; the server names the supported model when it refuses. None disables term matching.

  • query (dict[str, Any] | None) – Legacy query body containing top_k plus one of inputs, vector, or id. Prefer passing these fields directly.

  • timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.

Returns:

SearchRecordsResponse with hits and usage statistics.

Raises:
  • PineconeValueError – If namespace is not a string, top_k < 1, or rerank is 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:

SearchRecordsResponse

Examples

# Basic search
response = 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)

# Search with reranking
response = 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 rerank when searching and reranking in a single call. Use pc.inference.rerank() when reranking results from a different source or when you need to rerank without searching.

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.

Parameters:
Return type:

SearchRecordsResponse

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. filterable is required on each field and must be True — to leave a field unindexed, omit it from fields.

Returns:

NamespaceDescription with the namespace name, record count, schema, indexed fields, and size_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:

NamespaceDescription

Examples

ns = idx.create_namespace(name="movies-en")
print(ns.name, ns.record_count, ns.size_bytes)

ns = idx.create_namespace(
    name="movies-en",
    schema={"fields": {"genre": {"filterable": True}}},
)
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:
  • name (str) – Name of the namespace to describe. Must be ASCII, must not contain the NUL character, and must be 1-512 characters long. Pass __default__ to describe the namespace that requests address when they omit a namespace.

  • kwargs (str)

Returns:

NamespaceDescription with the namespace name, record count, schema, indexed fields, and size_bytes. size_bytes is approximate: data written before size tracking reads as 0, and recently deleted data may still be counted; compaction converges the value.

Raises:
Return type:

NamespaceDescription

Examples

ns = idx.describe_namespace(name="movies-en")
print(ns.name, ns.record_count, ns.size_bytes)

default_ns = idx.describe_namespace(name="__default__")
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:
  • name (str) – Name of the namespace to delete. Must be ASCII, must not contain the NUL character, and must be 1-512 characters long.

  • timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.

  • kwargs (str)

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

idx.delete_namespace(name="movies-deprecated")
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:

ListNamespacesResponse with namespace descriptions, pagination info, and total count. Each description carries size_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:

ListNamespacesResponse

Examples

response = 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 ListNamespacesResponse per 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:
  • 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 per page, 1-100.

Yields:

ListNamespacesResponse for each page of results. Each NamespaceDescription carries size_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:

Iterator[ListNamespacesResponse]

Examples

for page in idx.list_namespaces(prefix="prod-"):
    for ns in page.namespaces:
        print(ns.name, ns.record_count, ns.size_bytes)
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:

ListResponse with vector IDs, pagination info, namespace, and usage.

Raises:
Return type:

ListResponse

Examples

response = 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 ListResponse per 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:

ListResponse for each page of results.

Raises:
Return type:

Iterator[ListResponse]

Examples

for page in idx.list(prefix="doc1#"):
    for item in page.vectors:
        print(item.id)
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 an https:// 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:

StartImportResponse with the ID of the created import operation.

Raises:
  • PineconeValueError – If error_mode is supplied but not "continue" or "abort".

  • ApiError – If uri is empty or longer than the server accepts, uses an unsupported scheme, is an s3:// 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:

StartImportResponse

Examples

# Start an import and poll until complete
import time
response = idx.start_import(uri="s3://my-bucket/vectors/")
import_id = response.id

# Poll until the import finishes
import_op = idx.describe_import(import_id)
while import_op.status not in ("Completed", "Failed", "Cancelled"):
    time.sleep(10)
    import_op = 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 = 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.

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:

ImportModel with the import operation details.

Raises:
Return type:

ImportModel

Examples

import_op = idx.describe_import("import-123")
print(import_op.status, import_op.percent_complete)
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:
Return type:

None

Examples

idx.cancel_import("import-123")
list_imports(*, limit=None, pagination_token=None)[source]

List bulk import operations, automatically following pagination.

Yields individual ImportModel objects, fetching additional pages transparently until all results have been returned.

Parameters:
  • limit (int | None) – Maximum number of imports per page. Omit to let the server choose the page size.

  • pagination_token (str | None) – Token to resume pagination from a previous call.

Yields:

ImportModel for 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:

Iterator[ImportModel]

Examples

for imp in idx.list_imports():
    print(imp.id, imp.status)
list_imports_paginated(*, limit=None, pagination_token=None)[source]

Fetch a single page of bulk import operations.

Returns an ImportList for one page. The caller is responsible for managing the pagination token.

Parameters:
  • limit (int | None) – Maximum number of imports to return in this page.

  • pagination_token (str | None) – Token from a previous response to fetch the next page.

Returns:

ImportList with 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:

ImportList

Examples

page = idx.list_imports_paginated(limit=10)
for imp in page:
    print(imp.id, imp.status)
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 a context manager so it closes automatically.

Returns:

None.

Return type:

None

Examples

with pc.index(name="articles-en") as idx:
    idx.upsert(namespace="articles-en", vectors=[...])
__enter__()[source]

Enter the context manager, returning this index.

Returns:

This Index instance.

Return type:

Index

Examples

with pc.index(name="articles-en") as idx:
    idx.upsert(namespace="articles-en", vectors=[...])
__exit__(*args)[source]

Exit the context manager, calling close().

Returns:

None.

Parameters:

args (Any)

Return type:

None

Documents

class pinecone.client.documents.Documents(*, http, get_batch_executor)[source]

Bases: object

Document data-plane operations for a schema-based index (2026-07 API).

Accessed via documents. Not constructed directly — the parent Index builds and caches its own instance on first access.

Examples

from pinecone import Pinecone

pc = Pinecone(api_key="your-api-key")
with pc.index(name="articles-en") as index:
    index.documents.upsert(
        namespace="articles-en",
        documents=[{"_id": "article-101", "title": "Intro to vectors"}],
    )
Parameters:
  • http (HTTPClient)

  • get_batch_executor (Callable[[int], ThreadPoolExecutor])

__init__(*, http, get_batch_executor)[source]
Parameters:
  • http (HTTPClient)

  • get_batch_executor (Callable[[int], ThreadPoolExecutor])

Return type:

None

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 via a thread pool. Per-batch HTTP failures are captured in the returned BatchResult rather than raised, so one failed batch does not abort the rest; retry only the failures by passing result.failed_items back 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 _id key or a DocumentRecord; IDs must be unique across the whole list.

  • batch_size (int) – Maximum documents per request (1-1000, default 50).

  • max_concurrency (int) – Thread pool size for concurrent requests (1-64, default 4).

  • show_progress (bool) – Display a progress bar when tqdm is installed. Defaults to True.

  • timeout (float | None) – Per-request timeout in seconds applied to each batch’s request — not to the whole call.

Returns:

BatchResult with aggregated success and failure counts; per-batch errors are in result.errors and the affected documents in result.failed_items.

Raises:

PineconeValueError – If namespace is empty, documents is empty or contains an invalid or duplicate _id, batch_size is outside [1, 1000], or max_concurrency is outside [1, 64].

Return type:

BatchResult

Examples

documents = [
    {"_id": f"article-{i}", "title": f"Article {i}"}
    for i in range(5000)
]
result = 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.

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, or delete_all must be provided. Deleting IDs that do not exist does not raise an error.

Pinecone applies the delete asynchronously. For a filtered delete, response.matched_records is 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 filter and delete_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 with ids and delete_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 with ids and filter.

  • timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.

Returns:

DeleteDocumentsResponsematched_records is populated only for filtered deletes (None for by-ID and delete-all paths, and when the count could not be read in time).

Raises:
  • PineconeValueError – If namespace is empty, zero or more than one of ids/filter/delete_all is provided, filter is an empty dict, or ids exceeds 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

idx.documents.delete(namespace="articles-en", ids=["article-101"])

response = idx.documents.delete(
    namespace="articles-en",
    filter={"category": {"$eq": "obsolete"}},
)
print(response.matched_records)

idx.documents.delete(namespace="articles-old", delete_all=True)
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 ids or filter must 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 — with response.pagination carrying 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:

FetchDocumentsResponse with documents (a map of document ID to document), namespace, usage, and — for filtered fetches with more results — pagination.

Raises:
  • PineconeValueError – If namespace is empty, both or neither of ids and filter are provided, filter is an empty dict, ids exceeds 1000 entries, or pagination_token is passed without filter.

  • 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 = 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 = idx.documents.fetch(
    namespace="articles-en",
    filter={"category": {"$eq": "tech"}},
)
while response.pagination is not None:
    response = 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 a Paginator that fetches pages on demand and stops when the server returns no pagination token. 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). None lists 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, use itertools.islice() or break out of the loop.

  • 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:

Paginator over ListedDocumentRecord objects. Supports for loops, to_list(), and pages().

Raises:
  • PineconeValueError – If namespace is empty, prefix violates the rules above, or limit falls 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:

Paginator[ListedDocumentRecord]

Examples

for doc in idx.documents.list(namespace="articles-en", prefix="article-1"):
    print(doc.id)

for page in idx.documents.list(namespace="articles-en", limit=20).pages():
    print(len(page.items), page.pagination_token)
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_k most 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 a type key. text and query_string clauses may be combined; a dense_vector or sparse_vector clause 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 _id and 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:

SearchDocumentsResponse with matches (ordered from most to least similar), namespace, and usage.

Raises:
  • PineconeValueError – If namespace is empty, score_by is empty, over 100 clauses, or combines a vector clause with any other clause, or top_k is 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 = 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)

See also

  • search() — record search for integrated-inference indexes.

  • query() — nearest-neighbor search over vectors you provide.

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 with filter plus set_fields and/or remove_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_records is 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 _id key or an UpdateDocumentRecord. Any key other than _id and _remove_fields sets a new value for that field; the names in _remove_fields are removed from the document. _id values must be unique within the request. Mutually exclusive with filter, set_fields, and remove_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 with documents. 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 with filter.

  • remove_fields (Sequence[str] | None) – Names of the fields to remove from every document matching filter. Only valid with filter.

  • timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.

Returns:

UpdateDocumentsResponsematched_records is populated only for filtered updates (None for per-ID updates, and when the count could not be read in time).

Raises:
  • PineconeValueError – If namespace is empty, documents is combined with any by-filter field, neither documents nor filter is given, set_fields or remove_fields is passed without filter, filter is an empty dict or carries no patch, documents is 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 None is rejected server-side — use _remove_fields (per-ID) or remove_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

idx.documents.update(
    namespace="articles-en",
    documents=[
        {"_id": "article-101", "title": "Updated title"},
        {"_id": "article-102", "_remove_fields": ["content"]},
    ],
)

response = idx.documents.update(
    namespace="articles-en",
    filter={"category": {"$eq": "news"}},
    set_fields={"category": "archive"},
    remove_fields=["content"],
)
print(response.matched_records)
upsert(*, namespace, documents, timeout=None)[source]

Upsert documents into a namespace.

Each document must include an _id field (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 _id already exists in the namespace, it is overwritten.

Pinecone applies the upsert asynchronously, so documents may not be immediately visible to search() or fetch().

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 _id key or a DocumentRecord. For larger lists, use batch_upsert().

  • timeout (float | None) – Per-request timeout in seconds. Overrides the client-level default for this call only.

Returns:

UpsertDocumentsResponse with the count of documents accepted for upsert.

Raises:
  • PineconeValueError – If namespace is empty, documents is 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 = 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.