Skip to main content
This page shows you how to upsert records into a namespace in an index. Namespaces let you partition records within an index and are essential for implementing multitenancy when you need to isolate the data of each customer/user. If a record ID already exists, upserting overwrites the entire record. To change only part of a record, update the record.
Upserts consume write units (WUs). See Understanding cost for how upsert cost is calculated.
To control costs when ingesting large datasets (10,000,000+ records), use import instead of upsert.

Upsert dense vectors

Upserting text is supported only for indexes with integrated embedding.
To upsert source text into an index of dense vectors with integrated embedding, use the upsert_records operation. Pinecone converts the text to dense vectors automatically using the hosted dense embedding model associated with the index.
  • Specify the namespace to upsert into. If the namespace doesn’t exist, it is created. To use the default namespace, set the namespace to "__default__".
  • Format your input data as records, each with the following:
    • An _id field with a unique record identifier for the index namespace. id can be used as an alias for _id.
    • A field with the source text to convert to a vector. This field must match the field_map specified in the index.
    • Additional fields are stored as record metadata and can be returned in search results or used to filter search results.
For example, the following code converts the sentences in the chunk_text fields to dense vectors and then upserts them into example-namespace in an example index. The additional category field is stored as metadata.
from pinecone import Pinecone

pc = Pinecone(api_key="YOUR_API_KEY")

# To get the unique host for an index, 
# see https://docs.pinecone.io/guides/manage-data/target-an-index
index = pc.Index(host="INDEX_HOST")

# Upsert records into a namespace
# `chunk_text` fields are converted to dense vectors
# `category` fields are stored as metadata
index.upsert_records(
    "example-namespace",
    [
        {
            "_id": "rec1",
            "chunk_text": "Apples are a great source of dietary fiber, which supports digestion and helps maintain a healthy gut.",
            "category": "digestive system", 
        },
        {
            "_id": "rec2",
            "chunk_text": "Apples originated in Central Asia and have been cultivated for thousands of years, with over 7,500 varieties available today.",
            "category": "cultivation",
        },
        {
            "_id": "rec3",
            "chunk_text": "Rich in vitamin C and other antioxidants, apples contribute to immune health and may reduce the risk of chronic diseases.",
            "category": "immune system",
        },
        {
            "_id": "rec4",
            "chunk_text": "The high fiber content in apples can also help regulate blood sugar levels, making them a favorable snack for people with diabetes.",
            "category": "endocrine system",
        },
    ]
) 
import { Pinecone } from '@pinecone-database/pinecone'

const pc = new Pinecone({ apiKey: "YOUR_API_KEY" })

// To get the unique host for an index, 
// see https://docs.pinecone.io/guides/manage-data/target-an-index
const namespace = pc.index("INDEX_NAME", "INDEX_HOST").namespace("example-namespace");

// Upsert records into a namespace
// `chunk_text` fields are converted to dense vectors
// `category` is stored as metadata
await namespace.upsertRecords([
        {
            "_id": "rec1",
            "chunk_text": "Apples are a great source of dietary fiber, which supports digestion and helps maintain a healthy gut.",
            "category": "digestive system", 
        },
        {
            "_id": "rec2",
            "chunk_text": "Apples originated in Central Asia and have been cultivated for thousands of years, with over 7,500 varieties available today.",
            "category": "cultivation",
        },
        {
            "_id": "rec3",
            "chunk_text": "Rich in vitamin C and other antioxidants, apples contribute to immune health and may reduce the risk of chronic diseases.",
            "category": "immune system",
        },
        {
            "_id": "rec4",
            "chunk_text": "The high fiber content in apples can also help regulate blood sugar levels, making them a favorable snack for people with diabetes.",
            "category": "endocrine system",
        }
]);
import io.pinecone.clients.Index;
import io.pinecone.configs.PineconeConfig;
import io.pinecone.configs.PineconeConnection;
import org.openapitools.db_data.client.ApiException;

import java.util.*;

public class UpsertText {
    public static void main(String[] args) throws ApiException {
        PineconeConfig config = new PineconeConfig("YOUR_API_KEY");
        config.setHost("INDEX_HOST");
        PineconeConnection connection = new PineconeConnection(config);

        Index index = new Index(config, connection, "integrated-dense-java");
        ArrayList<Map<String, String>> upsertRecords = new ArrayList<>();

        HashMap<String, String> record1 = new HashMap<>();
        record1.put("_id", "rec1");
        record1.put("category", "digestive system");
        record1.put("chunk_text", "Apples are a great source of dietary fiber, which supports digestion and helps maintain a healthy gut.");

        HashMap<String, String> record2 = new HashMap<>();
        record2.put("_id", "rec2");
        record2.put("category", "cultivation");
        record2.put("chunk_text", "Apples originated in Central Asia and have been cultivated for thousands of years, with over 7,500 varieties available today.");

        HashMap<String, String> record3 = new HashMap<>();
        record3.put("_id", "rec3");
        record3.put("category", "immune system");
        record3.put("chunk_text", "Rich in vitamin C and other antioxidants, apples contribute to immune health and may reduce the risk of chronic diseases.");

        HashMap<String, String> record4 = new HashMap<>();
        record4.put("_id", "rec4");
        record4.put("category", "endocrine system");
        record4.put("chunk_text", "The high fiber content in apples can also help regulate blood sugar levels, making them a favorable snack for people with diabetes.");

        upsertRecords.add(record1);
        upsertRecords.add(record2);
        upsertRecords.add(record3);
        upsertRecords.add(record4);

        index.upsertRecords("example-namespace", upsertRecords);
    }
}
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/pinecone-io/go-pinecone/v4/pinecone"
)

func main() {
    ctx := context.Background()

    pc, err := pinecone.NewClient(pinecone.NewClientParams{
        ApiKey: "YOUR_API_KEY",
    })
    if err != nil {
        log.Fatalf("Failed to create Client: %v", err)
    }

    // To get the unique host for an index, 
    // see https://docs.pinecone.io/guides/manage-data/target-an-index
    idxConnection, err := pc.Index(pinecone.NewIndexConnParams{Host: "INDEX_HOST", Namespace: "example-namespace"})
    if err != nil {
        log.Fatalf("Failed to create IndexConnection for Host: %v", err)
	  }

    // Upsert records into a namespace
    // `chunk_text` fields are converted to dense vectors
    // `category` is stored as metadata
	records := []*pinecone.IntegratedRecord{
        {
            "_id": "rec1",
            "chunk_text": "Apples are a great source of dietary fiber, which supports digestion and helps maintain a healthy gut.",
            "category": "digestive system", 
        },
        {
            "_id": "rec2",
            "chunk_text": "Apples originated in Central Asia and have been cultivated for thousands of years, with over 7,500 varieties available today.",
            "category": "cultivation",
        },
        {
            "_id": "rec3",
            "chunk_text": "Rich in vitamin C and other antioxidants, apples contribute to immune health and may reduce the risk of chronic diseases.",
            "category": "immune system",
        },
        {
            "_id": "rec4",
            "chunk_text": "The high fiber content in apples can also help regulate blood sugar levels, making them a favorable snack for people with diabetes.",
            "category": "endocrine system",
        },
	}

	err = idxConnection.UpsertRecords(ctx, records)
	if err != nil {
		log.Fatalf("Failed to upsert vectors: %v", err)
	}
}
# To get the unique host for an index,
# see https://docs.pinecone.io/guides/manage-data/target-an-index
INDEX_HOST="INDEX_HOST"
NAMESPACE="YOUR_NAMESPACE"
PINECONE_API_KEY="YOUR_API_KEY"

# Upsert records into a namespace
# `chunk_text` fields are converted to dense vectors
# `category` is stored as metadata
curl "https://$INDEX_HOST/records/namespaces/$NAMESPACE/upsert" \
  -H "Content-Type: application/x-ndjson" \
  -H "Api-Key: $PINECONE_API_KEY" \
  -H "X-Pinecone-Api-Version: 2025-10" \
  -d '{"_id": "rec1", "chunk_text": "Apples are a great source of dietary fiber, which supports digestion and helps maintain a healthy gut.", "category": "digestive system"}
      {"_id": "rec2", "chunk_text": "Apples originated in Central Asia and have been cultivated for thousands of years, with over 7,500 varieties available today.", "category": "cultivation"}
      {"_id": "rec3", "chunk_text": "Rich in vitamin C and other antioxidants, apples contribute to immune health and may reduce the risk of chronic diseases.", "category": "immune system"}
      {"_id": "rec4", "chunk_text": "The high fiber content in apples can also help regulate blood sugar levels, making them a favorable snack for people with diabetes.", "category": "endocrine system"}'

Upsert sparse vectors

Sparse-vector upsert is the right choice when your data is encoded by a learned sparse model (for example, pinecone-sparse-english-v0) or when your application owns the sparse-vector representation directly. For BM25-style keyword search over raw text with no model to manage, see Upsert documents.
Upserting text is supported only for indexes with integrated embedding.
To upsert source text into an index of sparse vectors with integrated embedding, use the upsert_records operation. Pinecone converts the text to sparse vectors automatically using the hosted sparse embedding model associated with the index.
  • Specify the namespace to upsert into. If the namespace doesn’t exist, it is created. To use the default namespace, set the namespace to "__default__".
  • Format your input data as records, each with the following:
    • An _id field with a unique record identifier for the index namespace. id can be used as an alias for _id.
    • A field with the source text to convert to a vector. This field must match the field_map specified in the index.
    • Additional fields are stored as record metadata and can be returned in search results or used to filter search results.
For example, the following code converts the sentences in the chunk_text fields to sparse vectors and then upserts them into example-namespace in an example index. The additional category and quarter fields are stored as metadata.
from pinecone import Pinecone

pc = Pinecone(api_key="YOUR_API_KEY")

# To get the unique host for an index, 
# see https://docs.pinecone.io/guides/manage-data/target-an-index
index = pc.Index(host="INDEX_HOST")

# Upsert records into a namespace
# `chunk_text` fields are converted to sparse vectors
# `category` and `quarter` fields are stored as metadata
index.upsert_records(
    "example-namespace",
    [
        { 
            "_id": "vec1", 
            "chunk_text": "AAPL reported a year-over-year revenue increase, expecting stronger Q3 demand for its flagship phones.", 
            "category": "technology",
            "quarter": "Q3"
        },
        { 
            "_id": "vec2", 
            "chunk_text": "Analysts suggest that AAPL'\''s upcoming Q4 product launch event might solidify its position in the premium smartphone market.", 
            "category": "technology",
            "quarter": "Q4"
        },
        { 
            "_id": "vec3", 
            "chunk_text": "AAPL'\''s strategic Q3 partnerships with semiconductor suppliers could mitigate component risks and stabilize iPhone production.",
            "category": "technology",
            "quarter": "Q3"
        },
        { 
            "_id": "vec4", 
            "chunk_text": "AAPL may consider healthcare integrations in Q4 to compete with tech rivals entering the consumer wellness space.", 
            "category": "technology",
            "quarter": "Q4"
        }
    ]
)

time.sleep(10) # Wait for the upserted vectors to be indexed
import { Pinecone } from '@pinecone-database/pinecone'

const pc = new Pinecone({ apiKey: "YOUR_API_KEY" })

// To get the unique host for an index, 
// see https://docs.pinecone.io/guides/manage-data/target-an-index
const namespace = pc.index("INDEX_NAME", "INDEX_HOST").namespace("example-namespace");

// Upsert records into a namespace
// `chunk_text` fields are converted to sparse vectors
// `category` and `quarter` fields are stored as metadata
await namespace.upsertRecords([
    { 
        "_id": "vec1", 
        "chunk_text": "AAPL reported a year-over-year revenue increase, expecting stronger Q3 demand for its flagship phones.", 
        "category": "technology",
        "quarter": "Q3"
    },
    { 
        "_id": "vec2", 
        "chunk_text": "Analysts suggest that AAPL'\''s upcoming Q4 product launch event might solidify its position in the premium smartphone market.", 
        "category": "technology",
        "quarter": "Q4"
    },
    { 
        "_id": "vec3", 
        "chunk_text": "AAPL'\''s strategic Q3 partnerships with semiconductor suppliers could mitigate component risks and stabilize iPhone production.",
        "category": "technology",
        "quarter": "Q3"
    },
    { 
        "_id": "vec4", 
        "chunk_text": "AAPL may consider healthcare integrations in Q4 to compete with tech rivals entering the consumer wellness space.", 
        "category": "technology",
        "quarter": "Q4"
    }
]);
import io.pinecone.clients.Index;
import io.pinecone.configs.PineconeConfig;
import io.pinecone.configs.PineconeConnection;
import org.openapitools.db_data.client.ApiException;

import java.util.*;

public class UpsertText {
    public static void main(String[] args) throws ApiException {
        PineconeConfig config = new PineconeConfig("YOUR_API_KEY");
        config.setHost("INDEX_HOST");
        PineconeConnection connection = new PineconeConnection(config);

        Index index = new Index(config, connection, "integrated-sparse-java");
        ArrayList<Map<String, String>> upsertRecords = new ArrayList<>();

        HashMap<String, String> record1 = new HashMap<>();
        record1.put("_id", "rec1");
        record1.put("category", "digestive system");
        record1.put("chunk_text", "Apples are a great source of dietary fiber, which supports digestion and helps maintain a healthy gut.");

        HashMap<String, String> record2 = new HashMap<>();
        record2.put("_id", "rec2");
        record2.put("category", "cultivation");
        record2.put("chunk_text", "Apples originated in Central Asia and have been cultivated for thousands of years, with over 7,500 varieties available today.");

        HashMap<String, String> record3 = new HashMap<>();
        record3.put("_id", "rec3");
        record3.put("category", "immune system");
        record3.put("chunk_text", "Rich in vitamin C and other antioxidants, apples contribute to immune health and may reduce the risk of chronic diseases.");

        HashMap<String, String> record4 = new HashMap<>();
        record4.put("_id", "rec4");
        record4.put("category", "endocrine system");
        record4.put("chunk_text", "The high fiber content in apples can also help regulate blood sugar levels, making them a favorable snack for people with diabetes.");

        upsertRecords.add(record1);
        upsertRecords.add(record2);
        upsertRecords.add(record3);
        upsertRecords.add(record4);

        index.upsertRecords("example-namespace", upsertRecords);
    }
}
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/pinecone-io/go-pinecone/v4/pinecone"
)

func main() {
    ctx := context.Background()

    pc, err := pinecone.NewClient(pinecone.NewClientParams{
        ApiKey: "YOUR_API_KEY",
    })
    if err != nil {
        log.Fatalf("Failed to create Client: %v", err)
    }

    // To get the unique host for an index, 
    // see https://docs.pinecone.io/guides/manage-data/target-an-index
    idxConnection, err := pc.Index(pinecone.NewIndexConnParams{Host: "INDEX_HOST", Namespace: "example-namespace"})
    if err != nil {
        log.Fatalf("Failed to create IndexConnection for Host: %v", err)
	  }

    // Upsert records into a namespace
    // `chunk_text` fields are converted to sparse vectors
    // `category` and `quarter` fields are stored as metadata
	records := []*pinecone.IntegratedRecord{
		{
			"_id":        "vec1",
			"chunk_text": "AAPL reported a year-over-year revenue increase, expecting stronger Q3 demand for its flagship phones.",
			"category":   "technology",
			"quarter":    "Q3",
		},
		{
			"_id":        "vec2",
			"chunk_text": "Analysts suggest that AAPL's upcoming Q4 product launch event might solidify its position in the premium smartphone market.",
			"category":   "technology",
			"quarter":    "Q4",
		},
		{
			"_id":        "vec3",
			"chunk_text": "AAPL's strategic Q3 partnerships with semiconductor suppliers could mitigate component risks and stabilize iPhone production.",
			"category":   "technology",
			"quarter":    "Q3",
		},
		{
			"_id":        "vec4",
			"chunk_text": "AAPL may consider healthcare integrations in Q4 to compete with tech rivals entering the consumer wellness space.",
			"category":   "technology",
			"quarter":    "Q4",
		},
	}

	err = idxConnection.UpsertRecords(ctx, records)
	if err != nil {
		log.Fatalf("Failed to upsert vectors: %v", err)
	}
}
INDEX_HOST="INDEX_HOST"
NAMESPACE="YOUR_NAMESPACE"
PINECONE_API_KEY="YOUR_API_KEY"

curl  "https://$INDEX_HOST/records/namespaces/$NAMESPACE/upsert" \
    -H "Content-Type: application/x-ndjson" \
    -H "Api-Key: $PINECONE_API_KEY" \
    -H "X-Pinecone-Api-Version: 2025-10" \
    -d '{ "_id": "vec1", "chunk_text": "AAPL reported a year-over-year revenue increase, expecting stronger Q3 demand for its flagship phones.", "category": "technology", "quarter": "Q3" }
      { "_id": "vec2", "chunk_text": "Analysts suggest that AAPL'\''s upcoming Q4 product launch event might solidify its position in the premium smartphone market.", "category": "technology", "quarter": "Q4" }
      { "_id": "vec3", "chunk_text": "AAPL'\''s strategic Q3 partnerships with semiconductor suppliers could mitigate component risks and stabilize iPhone production.", "category": "technology", "quarter": "Q3" }
      { "_id": "vec4", "chunk_text": "AAPL may consider healthcare integrations in Q4 to compete with tech rivals entering the consumer wellness space.", "category": "technology", "quarter": "Q4" }'

Upsert documents

Documents are the unit of data in an index with a document schema; see Document for the definition. Each field in a document is indexed according to the configuration you declared for it in the schema, not just its type — for example, a string field can be indexed for BM25 via the full_text_search config, and a separate dense_vector field can store vector values you provide at upsert time. Indexes with document schemas do not support integrated inference fields such as semantic_text. The example below upserts two documents into the articles namespace using the document API. Each document is indexed for BM25 ranking on body. The category field is upserted as metadata — it isn’t declared in the schema but is auto-indexed for filtering at upsert time:
curl -X POST "https://INDEX_HOST/namespaces/articles/documents/upsert" \
  -H "Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-Pinecone-Api-Version: 2026-01.alpha" \
  -d '{
    "documents": [
      {
        "_id": "doc1",
        "body": "Pinecone serverless indexes scale automatically with your workload.",
        "category": "platform"
      },
      {
        "_id": "doc2",
        "body": "Full-text search uses BM25 ranking on text fields with full-text search enabled.",
        "category": "search"
      }
    ]
  }'
The document API is in public preview and uses the 2026-01.alpha API version. Indexes with dense or sparse vectors use the stable 2025-10 API version shown in the upsert examples above.
Field-name rules:
  • Fields not declared in the schema are stored on the document, returned via include_fields, and automatically indexed for filtering as metadata. The schema declares only ranking fields (FTS-enabled string, dense_vector, sparse_vector).
  • Field names must be unique, non-empty strings, must not start with _ (reserved for system-managed fields like _id and _score) or $ (reserved for filter operators), and are limited to 64 bytes.
Document upsert limits:
  • Each upsert request can contain up to 1000 documents and must be no larger than 2 MB.
  • Each document can be no larger than 2 MB.
  • Each full_text_search string field can be no larger than 100 KB and can contain up to 10,000 tokens.
  • Each token can be no larger than 256 bytes before analyzer truncation.
  • Metadata fields on a document (everything outside FTS-enabled string fields) are limited to 40 KB per document in total. This limit does not apply to full_text_search text fields.
For the full upsert reference (SDK examples, batching, and the response schema), see Full-text search.

Upsert in batches

To control costs when ingesting large datasets (10,000,000+ records), use import instead of upsert.
Send upserts in batches to help increase throughput.
  • When upserting records with vectors, a batch should be as large as possible (up to 1000 records) without exceeding the max request size of 2 MB. To understand the number of records you can fit into one batch based on the vector dimensions and metadata size, see the following table:
    DimensionMetadata (bytes)Max batch size
    38601000
    768500559
    15362000245
  • When upserting records with text, a batch can contain up to 96 records. This limit comes from the hosted embedding models used during integrated embedding rather than the batch size limit for upserting raw vectors.
import random
import itertools
from pinecone.grpc import PineconeGRPC as Pinecone

pc = Pinecone(api_key="YOUR_API_KEY")

# To get the unique host for an index, 
# see https://docs.pinecone.io/guides/manage-data/target-an-index
index = pc.Index(host="INDEX_HOST")

def chunks(iterable, batch_size=200):
    """A helper function to break an iterable into chunks of size batch_size."""
    it = iter(iterable)
    chunk = tuple(itertools.islice(it, batch_size))
    while chunk:
        yield chunk
        chunk = tuple(itertools.islice(it, batch_size))

vector_dim = 128
vector_count = 10000

# Example generator that generates many (id, vector) pairs
example_data_generator = map(lambda i: (f'id-{i}', [random.random() for _ in range(vector_dim)]), range(vector_count))

# Upsert data with 200 vectors per upsert request
for ids_vectors_chunk in chunks(example_data_generator, batch_size=200):
    index.upsert(vectors=ids_vectors_chunk) 
import { Pinecone } from "@pinecone-database/pinecone";

const RECORD_COUNT = 10000;
const RECORD_DIMENSION = 128;

const client = new Pinecone({ apiKey: "YOUR_API_KEY" });
const index = client.index("docs-example");

// A helper function that breaks an array into chunks of size batchSize
const chunks = (array, batchSize = 200) => {
  const chunks = [];

  for (let i = 0; i < array.length; i += batchSize) {
    chunks.push(array.slice(i, i + batchSize));
  }

  return chunks;
};

// Example data generation function, creates many (id, vector) pairs
const generateExampleData = () =>
  Array.from({ length: RECORD_COUNT }, (_, i) => {
    return {
      id: `id-${i}`,
      values: Array.from({ length: RECORD_DIMENSION }, (_, i) => Math.random()),
    };
  });

const exampleRecordData = generateExampleData();
const recordChunks = chunks(exampleRecordData);

// Upsert data with 200 records per upsert request
for (const chunk of recordChunks) {
  await index.upsert({ records: chunk })
}
import io.pinecone.clients.Index;
import io.pinecone.configs.PineconeConfig;
import io.pinecone.configs.PineconeConnection;
import io.pinecone.unsigned_indices_model.VectorWithUnsignedIndices;

import java.util.Arrays;
import java.util.List;

public class UpsertBatchExample  {
    public static void main(String[] args) {
        PineconeConfig config = new PineconeConfig("YOUR_API_KEY");
        // To get the unique host for an index, 
        // see https://docs.pinecone.io/guides/manage-data/target-an-index
        config.setHost("INDEX_HOST");
        PineconeConnection connection = new PineconeConnection(config);
        Index index = new Index(connection, "INDEX_NAME");

        ArrayList<VectorWithUnsignedIndices> vectors = generateVectors();
        ArrayList<ArrayList<VectorWithUnsignedIndices>> chunks = chunks(vectors, BATCH_SIZE);

        for (ArrayList<VectorWithUnsignedIndices> chunk : chunks) {
            index.upsert(chunk, "example-namespace");
        }
    }

    // A helper function that breaks an ArrayList into chunks of batchSize
    private static ArrayList<ArrayList<VectorWithUnsignedIndices>> chunks(ArrayList<VectorWithUnsignedIndices> vectors, int batchSize) {
        ArrayList<ArrayList<VectorWithUnsignedIndices>> chunks = new ArrayList<>();
        ArrayList<VectorWithUnsignedIndices> chunk = new ArrayList<>();

        for (int i = 0; i < vectors.size(); i++) {
            if (i % BATCH_SIZE == 0 && i != 0) {
                chunks.add(chunk);
                chunk = new ArrayList<>();
            }

            chunk.add(vectors.get(i));
        }

        return chunks;
    }

    // Example data generation function, creates many (id, vector) pairs
    private static ArrayList<VectorWithUnsignedIndices> generateVectors() {
        Random random = new Random();
        ArrayList<VectorWithUnsignedIndices> vectors = new ArrayList<>();


        for (int i = 0; i <= RECORD_COUNT; i++) {
            String id = "id-" + i;
            ArrayList<Float> values = new ArrayList<>();

            for (int j = 0; j < RECORD_DIMENSION; j++) {
                values.add(random.nextFloat());
            }

            VectorWithUnsignedIndices vector = new VectorWithUnsignedIndices();
            vector.setId(id);
            vector.setValues(values);
            vectors.add(vector);
        }

        return vectors;
    }
}
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/pinecone-io/go-pinecone/v4/pinecone"
)

func main() {
    ctx := context.Background()

    pc, err := pinecone.NewClient(pinecone.NewClientParams{
        ApiKey: "YOUR_API_KEY",
    })
    if err != nil {
        log.Fatalf("Failed to create Client: %v", err)
    }

    // To get the unique host for an index, 
    // see https://docs.pinecone.io/guides/manage-data/target-an-index
    idxConnection, err := pc.Index(pinecone.NewIndexConnParams{Host: "INDEX_HOST"})
    if err != nil {
        log.Fatalf("Failed to create IndexConnection for Host: %v", err)
	  }

    // Generate a large number of vectors to upsert
    vectorCount := 10000
    vectorDim := idx.Dimension

    vectors := make([]*pinecone.Vector, vectorCount)
    for i := 0; i < int(vectorCount); i++ {
        randomFloats := make([]float32, vectorDim)

        for i := int32(0); i < vectorDim; i++ {
            randomFloats[i] = rand.Float32()
        }

        vectors[i] = &pinecone.Vector{
            Id:     fmt.Sprintf("doc1#-vector%d", i),
            Values: randomFloats,
        }
    }

    // Break the vectors into batches of 200
    var batches [][]*pinecone.Vector
    batchSize := 200

    for len(vectors) > 0 {
        batchEnd := batchSize
        if len(vectors) < batchSize {
            batchEnd = len(vectors)
        }
        batches = append(batches, vectors[:batchEnd])
        vectors = vectors[batchEnd:]
    }

    // Upsert batches
    for i, batch := range batches {
        upsertResp, err := idxConn.UpsertVectors(context.Background(), batch)
        if err != nil {
            panic(err)
        }

        fmt.Printf("upserted %d vectors (%v of %v batches)\n", upsertResp, i+1, len(batches))
    }
}

Upsert in parallel

Python SDK v6.0.0 and later provide async methods for use with asyncio. Asyncio support makes it possible to use Pinecone with modern async web frameworks such as FastAPI, Quart, and Sanic. For more details, see Async requests.
Send multiple upserts in parallel to help increase throughput. Vector operations block until the response has been received. However, they can be made asynchronously as follows:
# This example uses `async_req=True` and multiple threads.
# For a single-threaded approach compatible with modern async web frameworks, 
# see https://docs.pinecone.io/reference/sdks/python/overview#async-requests
import random
import itertools
from pinecone import Pinecone

# Initialize the client with pool_threads=30. This limits simultaneous requests to 30.
pc = Pinecone(api_key="YOUR_API_KEY", pool_threads=30)

# To get the unique host for an index, 
# see https://docs.pinecone.io/guides/manage-data/target-an-index
index = pc.Index(host="INDEX_HOST")

def chunks(iterable, batch_size=200):
    """A helper function to break an iterable into chunks of size batch_size."""
    it = iter(iterable)
    chunk = tuple(itertools.islice(it, batch_size))
    while chunk:
        yield chunk
        chunk = tuple(itertools.islice(it, batch_size))

vector_dim = 128
vector_count = 10000

example_data_generator = map(lambda i: (f'id-{i}', [random.random() for _ in range(vector_dim)]), range(vector_count))

# Upsert data with 200 vectors per upsert request asynchronously
# - Pass async_req=True to index.upsert()
with pc.Index(host="INDEX_HOST", pool_threads=30) as index:
    # Send requests in parallel
    async_results = [
        index.upsert(vectors=ids_vectors_chunk, async_req=True)
        for ids_vectors_chunk in chunks(example_data_generator, batch_size=200)
    ]
    # Wait for and retrieve responses (this raises in case of error)
    [async_result.get() for async_result in async_results]
import { Pinecone } from "@pinecone-database/pinecone";

const RECORD_COUNT = 10000;
const RECORD_DIMENSION = 128;

const client = new Pinecone({ apiKey: "YOUR_API_KEY" });

// To get the unique host for an index, 
// see https://docs.pinecone.io/guides/manage-data/target-an-index
const index = pc.index("INDEX_NAME", "INDEX_HOST")

// A helper function that breaks an array into chunks of size batchSize
const chunks = (array, batchSize = 200) => {
  const chunks = [];

  for (let i = 0; i < array.length; i += batchSize) {
    chunks.push(array.slice(i, i + batchSize));
  }

  return chunks;
};

// Example data generation function, creates many (id, vector) pairs
const generateExampleData = () =>
  Array.from({ length: RECORD_COUNT }, (_, i) => {
    return {
      id: `id-${i}`,
      values: Array.from({ length: RECORD_DIMENSION }, (_, i) => Math.random()),
    };
  });

const exampleRecordData = generateExampleData();
const recordChunks = chunks(exampleRecordData);

// Upsert data with 200 records per request asynchronously using Promise.all()
await Promise.all(recordChunks.map((chunk) => index.upsert({ records: chunk })));
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import io.pinecone.clients.Index;
import io.pinecone.configs.PineconeConfig;
import io.pinecone.configs.PineconeConnection;
import io.pinecone.proto.UpsertResponse;
import io.pinecone.unsigned_indices_model.VectorWithUnsignedIndices;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.List;

public class UpsertExample {
    public static void main(String[] args) {
        PineconeConfig config = new PineconeConfig("YOUR_API_KEY");
        // To get the unique host for an index, 
        // see https://docs.pinecone.io/guides/manage-data/target-an-index
        config.setHost("INDEX_HOST");
        PineconeConnection connection = new PineconeConnection(config);
        Index index = new Index(connection, "INDEX_NAME");

        // Run 5 threads concurrently and upsert data into pinecone
        int numberOfThreads = 5;

        // Create a fixed thread pool
        ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);

        // Submit tasks to the executor
        for (int i = 0; i < numberOfThreads; i++) {
            // upsertData
            int batchNumber = i+1;
            executor.submit(() -> upsertData(index, batchNumber));
        }

        // Shutdown the executor
        executor.shutdown();
    }

    private static void upsertData(Index index, int batchNumber) {
        // Vector ids to be upserted
        String prefix = "v" + batchNumber;
        List<String> upsertIds = Arrays.asList(prefix + "_1", prefix + "_2", prefix + "_3");

        // List of values to be upserted
        List<List<Float>> values = new ArrayList<>();
        values.add(Arrays.asList(1.0f, 2.0f, 3.0f));
        values.add(Arrays.asList(4.0f, 5.0f, 6.0f));
        values.add(Arrays.asList(7.0f, 8.0f, 9.0f));

        // List of sparse indices to be upserted
        List<List<Long>> sparseIndices = new ArrayList<>();
        sparseIndices.add(Arrays.asList(1L, 2L, 3L));
        sparseIndices.add(Arrays.asList(4L, 5L, 6L));
        sparseIndices.add(Arrays.asList(7L, 8L, 9L));

        // List of sparse values to be upserted
        List<List<Float>> sparseValues = new ArrayList<>();
        sparseValues.add(Arrays.asList(1000f, 2000f, 3000f));
        sparseValues.add(Arrays.asList(4000f, 5000f, 6000f));
        sparseValues.add(Arrays.asList(7000f, 8000f, 9000f));

        List<VectorWithUnsignedIndices> vectors = new ArrayList<>(3);

        // Metadata to be upserted
        Struct metadataStruct1 = Struct.newBuilder()
                .putFields("genre", Value.newBuilder().setStringValue("action").build())
                .putFields("year", Value.newBuilder().setNumberValue(2019).build())
                .build();

        Struct metadataStruct2 = Struct.newBuilder()
                .putFields("genre", Value.newBuilder().setStringValue("thriller").build())
                .putFields("year", Value.newBuilder().setNumberValue(2020).build())
                .build();

        Struct metadataStruct3 = Struct.newBuilder()
                .putFields("genre", Value.newBuilder().setStringValue("comedy").build())
                .putFields("year", Value.newBuilder().setNumberValue(2021).build())
                .build();
        List<Struct> metadataStructList = Arrays.asList(metadataStruct1, metadataStruct2, metadataStruct3);

        // Upsert data
        for (int i = 0; i < metadataStructList.size(); i++) {
            vectors.add(buildUpsertVectorWithUnsignedIndices(upsertIds.get(i), values.get(i), sparseIndices.get(i), sparseValues.get(i), metadataStructList.get(i)));
        }

        UpsertResponse upsertResponse = index.upsert(vectors, "example-namespace");
    }
}
package main

import (
    "context"
    "fmt"
    "log"
    "math/rand"
    "sync"
    
    "github.com/pinecone-io/go-pinecone/v4/pinecone"
)

func main() {
    ctx := context.Background()

    pc, err := pinecone.NewClient(pinecone.NewClientParams{
        ApiKey: "YOUR_API_KEY",
    })
    if err != nil {
        log.Fatalf("Failed to create Client: %v", err)
    }

    // To get the unique host for an index, 
    // see https://docs.pinecone.io/guides/manage-data/target-an-index
    idxConn, err := pc.Index(pinecone.NewIndexConnParams{Host: "INDEX_HOST"})
    if err != nil {
        log.Fatalf("Failed to create IndexConnection for Host: %v", err)
	  }

    // Generate a large number of vectors to upsert
    vectorCount := 10000
    vectorDim := idx.Dimension

    vectors := make([]*pinecone.Vector, vectorCount)
    for i := 0; i < int(vectorCount); i++ {
        randomFloats := make([]float32, vectorDim)

        for i := int32(0); i < vectorDim; i++ {
            randomFloats[i] = rand.Float32()
        }

        vectors[i] = &pinecone.Vector{
            Id:     fmt.Sprintf("doc1#-vector%d", i),
            Values: randomFloats,
        }
    }

    // Break the vectors into batches of 200
    var batches [][]*pinecone.Vector
    batchSize := 200

    for len(vectors) > 0 {
        batchEnd := batchSize
        if len(vectors) < batchSize {
            batchEnd = len(vectors)
        }
        batches = append(batches, vectors[:batchEnd])
        vectors = vectors[batchEnd:]
    }

    // Use channels to manage concurrency and possible errors
    maxConcurrency := 10
    errChan := make(chan error, len(batches))
    semaphore := make(chan struct{}, maxConcurrency)
    var wg sync.WaitGroup

    for i, batch := range batches {
        wg.Add(1)
        semaphore <- struct{}{}

        go func(batch []*pinecone.Vector, i int) {
            defer wg.Done()
            defer func() { <-semaphore }()

            upsertResp, err := idxConn.UpsertVectors(context.Background(), batch)
            if err != nil {
                errChan <- fmt.Errorf("batch %d failed: %v", i, err)
                return
            }

            fmt.Printf("upserted %d vectors (%v of %v batches)\n", upsertResp, i+1, len(batches))
        }(batch, i)
    }

    wg.Wait()
    close(errChan)

    for err := range errChan {
        if err != nil {
            fmt.Printf("Error while upserting batch: %v\n", err)
        }
    }
}

Python SDK with gRPC

Using the Python SDK with gRPC extras can provide higher upsert speeds. Through multiplexing, gRPC is able to handle large amounts of requests in parallel without slowing down the rest of the system (HoL blocking), unlike REST. Moreover, you can pass various retry strategies to the gRPC SDK, including exponential backoff. To install the gRPC version of the SDK:
Shell
pip install "pinecone[grpc]"
To use the gRPC SDK, import the pinecone.grpc subpackage and target an index as usual:
Python
from pinecone.grpc import PineconeGRPC as Pinecone

# This is gRPC client aliased as "Pinecone"
pc = Pinecone(api_key='YOUR_API_KEY')  

# To get the unique host for an index, 
# see https://docs.pinecone.io/guides/manage-data/target-an-index
index = pc.Index(host="INDEX_HOST")
To launch multiple read and write requests in parallel, pass async_req to the upsert operation:
Python
def chunker(seq, batch_size):
  return (seq[pos:pos + batch_size] for pos in range(0, len(seq), batch_size))

async_results = [
  index.upsert(vectors=chunk, async_req=True)
  for chunk in chunker(data, batch_size=200)
]

# Wait for and retrieve responses (in case of error)
[async_result.result() for async_result in async_results]
It is possible to get write-throttled faster when upserting using the gRPC SDK. If you see this often, implement retry logic with exponential backoff while upserting.The syntax for upsert, query, fetch, and delete with the gRPC SDK remain the same as the standard SDK.

Upsert limits

MetricLimit
Max batch size2 MB or 1000 records with vectors
96 records with text
Max documents per upsert request1000
Max document upsert request size2 MB
Max document size2 MB
Max full_text_search string fields per schema100
Max size per full_text_search string field100 KB
Max tokens per full_text_search string field10,000
Max bytes per token256 bytes
Max filterable metadata size per document40 KB
Max length for a record ID512 characters
Max dimensionality for dense vectors20,000
Max non-zero values for sparse vectors2048
Max dimensionality for sparse vectors4.2 billion
The 40 KB filterable metadata limit does not apply to full_text_search text fields.