# Create a collection control_2024-07 post /collections This operation creates a Pinecone collection. Serverless indexes do not support collections. ```python Python # pip install pinecone[grpc] from pinecone.grpc import PineconeGRPC as Pinecone pc = Pinecone(api_key="API_KEY") pc.create_collection("example-collection", "example-index") ``` ```javascript JavaScript // npm install @pinecone-database/pinecone import { Pinecone } from '@pinecone-database/pinecone' const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }); await pc.createCollection({ name: "example-collection", source: "example-index", }); ``` ```java Java import io.pinecone.clients.Pinecone; public class CreateCollectionExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); pc.createCollection("example-collection", "example-index"); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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) } collection, err := pc.CreateCollection(ctx, &pinecone.CreateCollectionRequest{ Name: "example-collection", Source: "example-index", }) if err != nil { log.Fatalf("Failed to create collection: %v", err) } else { fmt.Printf("Successfully created collection: %v", collection.Name) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); var collectionModel = await pinecone.CreateCollectionAsync(new CreateCollectionRequest { Name = "example-collection", Source = "example-index", }); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -s "https://api.pinecone.io/collections" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-07" \ -d '{ "name": "example-collection", "source": "example-index" }' ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -s https://api.pinecone.io/collections \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-07" \ -d '{ "name": "example-collection", "source": "example-index" }' ``` # Delete a collection control_2024-07 delete /collections/{collection_name} This operation deletes an existing collection. Serverless indexes do not support collections. ```python Python # pip install pinecone[grpc] from pinecone.grpc import PineconeGRPC as Pinecone pc = Pinecone(api_key='API_KEY') pc.delete_collection("example-collection") ``` ```javascript JavaScript // npm install @pinecone-database/pinecone import { Pinecone } from '@pinecone-database/pinecone' const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }) await pc.deleteCollection("example-collection"); ``` ```java Java import io.pinecone.clients.Pinecone; public class DeleteCollectionExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); pc.deleteCollection("example-collection"); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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) } collectionName := "example-collection" err = pc.DeleteCollection(ctx, collectionName) if err != nil { log.Fatalf("Failed to delete collection: %v\n", err) } else { if len(collections) == 0 { fmt.Printf("No collections found in project") } else { fmt.Printf("Successfully deleted collection \"%v\"\n", collectionName) } } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); await pinecone.DeleteCollectionAsync("example-collection"); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -i -X DELETE "https://api.pinecone.io/collections/example-collection" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-07" ``` # Describe a collection control_2024-07 get /collections/{collection_name} This operation gets a description of a collection. Serverless indexes do not support collections. ```python Python # pip install pinecone[grpc] from pinecone.grpc import PineconeGRPC as Pinecone pc = Pinecone(api_key='API_KEY') pc.describe_collection("tiny-collection") ``` ```javascript JavaScript // npm install @pinecone-database/pinecone import { Pinecone } from '@pinecone-database/pinecone'; const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }); await pc.describeCollection('tiny-collection'); ``` ```java Java import io.pinecone.clients.Pinecone; import org.openapitools.client.model.CollectionModel; public class DescribeCollectionExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); CollectionModel collectionModel = pc.describeCollection("tiny-collection"); System.out.println(collectionModel); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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) } collectionName := "tiny-collection" collection, err := pc.DescribeCollection(ctx, collectionName) if err != nil { log.Fatalf("Error describing collection %v: %v", collectionName, err) } else { fmt.Printf("Collection: %+v", collection) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); var collectionModel = await pinecone.DescribeCollectionAsync("tiny-collection"); Console.WriteLine(collectionModel); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -i -X GET "https://api.pinecone.io/collections/tiny-collection" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-07" ``` # List collections control_2024-07 get /collections This operation returns a list of all collections in a project. Serverless indexes do not support collections. ```python Python from pinecone.grpc import PineconeGRPC as Pinecone pc = Pinecone(api_key='YOUR_API_KEY') active_collections = pc.list_collections() ``` ```javascript JavaScript // npm install @pinecone-database/pinecone import { Pinecone } from '@pinecone-database/pinecone' const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }) await pc.listCollections(); ``` ```java Java import io.pinecone.clients.Pinecone; import org.openapitools.client.model.CollectionModel; public class ListCollectionsExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); List collectionList = pc.listCollections().getCollections(); System.out.println(collectionList); } } ``` ```go Go package main import ( "context" "encoding/json" "fmt" "log" "github.com/pinecone-io/go-pinecone/pinecone" ) func prettifyStruct(obj interface{}) string { bytes, _ := json.MarshalIndent(obj, "", " ") return string(bytes) } 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) } collections, err := pc.ListCollections(ctx) if err != nil { log.Fatalf("Failed to list collections: %v", err) } else { if len(collections) == 0 { fmt.Printf("No collections found in project") } else { for _, collection := range collections { fmt.Printf("collection: %v\n", prettifyStruct(collection)) } } } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); var collectionList = await pinecone.ListCollectionsAsync(); Console.WriteLine(collectionList); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -i -X GET "https://api.pinecone.io/collections" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-07" ``` # Configure an index control_2024-10 patch /indexes/{index_name} This operation configures an existing index. For serverless indexes, you can configure only index deletion protection and tags. For pod-based indexes, you can configure the pod size, number of replicas, tags, and index deletion protection. It is not possible to change the pod type of a pod-based index. However, you can create a collection from a pod-based index and then [create a new pod-based index with a different pod type](http://docs.pinecone.io/guides/indexes/create-an-index#create-an-index-from-a-collection) from the collection. For guidance and examples, see [Configure an index](http://docs.pinecone.io/guides/indexes/configure-an-index). ```python Python from pinecone.grpc import PineconeGRPC as Pinecone pc = Pinecone(api_key="YOUR_API_KEY") pc.configure_index( name="example-index", pod_type="p1.x2", replicas=4, deletion_protection="enabled") ``` ```javascript JavaScript import { Pinecone } from '@pinecone-database/pinecone' const pinecone = new Pinecone({ apiKey: 'YOUR_API_KEY' }); await pinecone.configureIndex('example-index', { podType: 'p1.x2', replicas: 4, deletionProtection: 'enabled' }); ``` ```java Java import io.pinecone.clients.Pinecone; public class ConfigureIndexExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); pc.configureIndex("example-index", "p1.x2", 4, DeletionProtection.ENABLED); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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) } idx, err := pc.ConfigureIndex(ctx, "example-index", pinecone.ConfigureIndexParams{PodType: "p1.x2", Replicas: 4, DeletionProtection: "enabled"}) if err != nil { log.Fatalf("Failed to configure index \"%v\": %v", idx.Name, err) } else { fmt.Printf("Successfully configured index \"%v\"", idx.Name) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); var indexMetadata = await pinecone.ConfigureIndexAsync("example-index", new ConfigureIndexRequest { Spec = new ConfigureIndexRequestSpec { Pod = new ConfigureIndexRequestSpecPod { Replicas = 4, PodType = "p1.x2", } }, DeletionProtection = DeletionProtection.Disabled, }); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -s -X PATCH "https://api.pinecone.io/indexes/example-index" \ -H "Content-Type: application/json" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" \ -d '{ "spec": { "pod": { "pod_type": "p1.x2", "replicas": 4 } }, deletion_protection": "enabled" }' ``` # Create an index control_2024-10 post /indexes This operation deploys a Pinecone index. This is where you specify the measure of similarity, the dimension of vectors to be stored in the index, which cloud provider you would like to deploy with, and more. For guidance and examples, see [Create an index](https://docs.pinecone.io/guides/indexes/create-an-index#create-a-serverless-index). ```python Python # pip install pinecone[grpc] # Serverless index from pinecone.grpc import PineconeGRPC as Pinecone from pinecone import ServerlessSpec pc = Pinecone(api_key="YOUR_API_KEY") pc.create_index( name="example-index1", dimension=1536, metric="cosine", spec=ServerlessSpec( cloud="aws", region="us-east-1", ), deletion_protection="disabled" ) # Pod-based index from pinecone.grpc import PineconeGRPC as Pinecone, PodSpec pc = Pinecone(api_key="YOUR_API_KEY") pc.create_index( name="example-index2", dimension=1536, metric="cosine", spec=PodSpec( environment="us-west1-gcp", pod_type="p1.x1", pods=1, ), deletion_protection="disabled" ) ``` ```javascript JavaScript // npm install @pinecone-database/pinecone // Serverles index import { Pinecone } from '@pinecone-database/pinecone' const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }); await pc.createIndex({ name: 'severless-index', dimension: 1536, metric: 'cosine', spec: { serverless: { cloud: 'aws', region: 'us-east-1' } }, deletionProtection: 'disabled', }); // Pod-based index await pc.createIndex({ name: 'example-index2', dimension: 1536, metric: 'cosine', spec: { pod: { environment: 'us-west1-gcp', podType: 'p1.x1', pods: 1 } }, deletionProtection: 'disabled', }); ``` ```java Java import io.pinecone.clients.Pinecone; // Serverless index public class CreateServerlessIndexExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); pc.createServerlessIndex("example-index1", "cosine", 1536, "aws", "us-east-1", DeletionProtection.disabled); } } // Pod-based index public class CreatePodIndexExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); pc.createPodsIndex("example-index2", 1536, "us-west1-gcp", "p1.x1", "cosine", DeletionProtection.disabled); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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) } // Serverless index idx, err := pc.CreateServerlessIndex(ctx, &pinecone.CreateServerlessIndexRequest{ Name: "example-index1", Dimension: 1536, Metric: pinecone.Cosine, Cloud: pinecone.Aws, Region: "us-east-1", DeletionProtection: "disabled", }) if err != nil { log.Fatalf("Failed to create serverless index: %v", idx.Name) } else { fmt.Printf("Successfully created serverless index: %v", idx.Name) } // Pod-based index idx, err := pc.CreatePodIndex(ctx, &pinecone.CreatePodIndexRequest{ Name: "example-index2", Dimension: 1536, Metric: pinecone.Cosine, Environment: "us-east1-gcp", PodType: "p1.x1", DeletionProtection: "disabled", }) if err != nil { log.Fatalf("Failed to create pod-based index: %v", idx.Name) } else { fmt.Printf("Successfully created pod-based index: %v", idx.Name) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // Serverless index var createIndexRequest = await pinecone.CreateIndexAsync(new CreateIndexRequest { Name = "example-index1", Dimension = 1536, Metric = CreateIndexRequestMetric.Cosine, Spec = new ServerlessIndexSpec { Serverless = new ServerlessSpec { Cloud = ServerlessSpecCloud.Aws, Region = "us-east-1", } }, DeletionProtection = DeletionProtection.Disabled }); // Pod-based index var createIndexRequest = await pinecone.CreateIndexAsync(new CreateIndexRequest { Name = "pod index", Dimension = 1536, Metric = CreateIndexRequestMetric.Cosine, Spec = new PodIndexSpec { Pod = new PodSpec { Environment = "us-east1-gcp", PodType = "p1.x1", Pods = 1, } }, DeletionProtection = DeletionProtection.Disabled }); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" # Serverless index curl -s "https://api.pinecone.io/indexes" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" \ -d '{ "name": "example-index1", "dimension": 1536, "metric": "cosine", "spec": { "serverless": { "cloud": "aws", "region": "us-east-1" } }, "tags"={ "example": "tag", "environment": "production" }, "deletion_protection"="disabled" }' # Pod-based index curl -s "https://api.pinecone.io/indexes" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-07" \ -d '{ "name": "example-index2", "dimension": 1536, "metric": "cosine", "spec": { "pod": { "environment": "us-west1-gcp", "pod_type": "p1.x1", "pods": 1 } }, "tags"={ "example": "tag", "environment": "production" }, "deletion_protection"="disabled" }' ``` ```shell # Serverless index { "name": "example-index1", "metric": "cosine", "dimension": 1536, "status": { "ready": true, "state": "Ready" }, "host": "example-index1-4zo0ijk.svc.dev-us-west2-aws.pinecone.io", "spec": { "serverless": { "region": "us-east-1", "cloud": "aws" }, "tags": { "example": "tag", "environment": "production" } } } # Pod-based index { "name": "example-index2", "metric": "cosine", "dimension": 1536, "status": { "ready": true, "state": "Ready" }, "host": "example-index2-4zo0ijk.svc.us-west1-gcp.pinecone.io", "spec": { "pod": { "replicas": 1, "shards": 1, "pods": 1, "pod_type": "p1.x1", "environment": "us-west1-gcp" }, "tags": { "example": "tag", "environment": "production" } } } ``` # Delete an index control_2024-10 delete /indexes/{index_name} This operation deletes an existing index. ```python Python # pip install pinecone[grpc] from pinecone.grpc import PineconeGRPC as Pinecone, PodSpec pc = Pinecone(api_key="YOUR_API_KEY") pc.delete_index("example-index") ``` ```javascript JavaScript // npm install @pinecone-database/pinecone import { Pinecone } from '@pinecone-database/pinecone' const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }); await pc.deleteIndex('example-index'); ``` ```java Java import io.pinecone.clients.Pinecone; public class DeleteIndexExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); pc.deleteIndex("example-index"); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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) } indexName := "example-index" err = pc.DeleteIndex(ctx, indexName) if err != nil { log.Fatalf("Failed to delete index: %v", err) } else { fmt.Println("Index \"%v\" deleted successfully", indexName) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); await pinecone.DeleteIndexAsync("example-index"); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -i -X DELETE "https://api.pinecone.io/indexes/example-index" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" ``` # Describe an index control_2024-10 get /indexes/{index_name} Get a description of an index. **Do not target an index by name in production.** When you target an index by name for data operations such as `upsert` and `query`, the SDK gets the unique DNS host for the index using the `describe_index` operation. This is convenient for testing but should be avoided in production because `describe_index` uses a different API than data operations and therefore adds an additional network call and point of failure. Instead, you should get an index host once and cache it for reuse or specify the host directly. ```python Python # pip install pinecone[grpc] from pinecone.grpc import PineconeGRPC as Pinecone pc = Pinecone(api_key="YOUR_API_KEY") pc.describe_index("movie-recommendations") ``` ```javascript JavaScript // npm install @pinecone-database/pinecone import { Pinecone } from '@pinecone-database/pinecone'; const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }); await pc.describeIndex('movie-recommendations'); ``` ```java Java import io.pinecone.clients.Pinecone; import org.openapitools.db_control.client.model.*; public class DescribeIndexExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOURE_API_KEY").build(); IndexModel indexModel = pc.describeIndex("movie-recommendations"); System.out.println(indexModel); } } ``` ```go Go package main import ( "context" "encoding/json" "fmt" "log" "github.com/pinecone-io/go-pinecone/pinecone" ) func prettifyStruct(obj interface{}) string { bytes, _ := json.MarshalIndent(obj, "", " ") return string(bytes) } 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) } idx, err := pc.DescribeIndex(ctx, "movie-recommendations") if err != nil { log.Fatalf("Failed to describe index \"%v\": %v", idx.Name, err) } else { fmt.Printf("index: %v\n", prettifyStruct(idx)) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); var indexModel = await pinecone.DescribeIndexAsync("example-index"); Console.WriteLine(indexModel); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -i -X GET "https://api.pinecone.io/indexes/movie-recommendations" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" ``` # List indexes control_2024-10 get /indexes This operation returns a list of all indexes in a project. ```python Python # pip install pinecone[grpc] from pinecone.grpc import PineconeGRPC as Pinecone pc = Pinecone(api_key="YOUR_API_KEY") pc.list_indexes() ``` ```javascript JavaScript // npm install @pinecone-database/pinecone import { Pinecone } from '@pinecone-database/pinecone' const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }) await pc.listIndexes(); ``` ```java Java import io.pinecone.clients.Pinecone; import org.openapitools.db_control.client.model.*; public class ListIndexesExample { public static void main(String[] args) { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); IndexList indexList = pc.listIndexes(); System.out.println(indexList); } } ``` ```go Go package main import ( "context" "encoding/json" "fmt" "log" "github.com/pinecone-io/go-pinecone/pinecone" ) func prettifyStruct(obj interface{}) string { bytes, _ := json.MarshalIndent(obj, "", " ") return string(bytes) } 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) } idxs, err := pc.ListIndexes(ctx) if err != nil { log.Fatalf("Failed to list indexes: %v", err) } else { for _, index := range idxs { fmt.Printf("index: %v\n", prettifyStruct(index)) } } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); var indexList = await pinecone.ListIndexesAsync(); Console.WriteLine(indexList); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl -i -X GET "https://api.pinecone.io/indexes" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" ``` # Cancel an import data_2024-10 delete /bulk/imports/{id} The `cancel_import` operation cancels an import operation if it is not yet finished. It has no effect if the operation is already finished. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). This feature is in [public preview](/release-notes/feature-availability) and available only on [Standard and Enterprise plans](https://www.pinecone.io/pricing/). ```python Python 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/data/target-an-index index = pc.Index(host="INDEX_HOST") index.cancel_import(id="101") ``` ```javascript JavaScript 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") await index.cancelImport(id='101'); ``` ```java Java import io.pinecone.clients.Pinecone; import io.pinecone.clients.AsyncIndex; import org.openapitools.db_data.client.ApiException; public class CancelImport { public static void main(String[] args) throws ApiException { // Initialize a Pinecone client with your API key Pinecone pinecone = new Pinecone.Builder("YOUR_API_KEY").build(); // Get async imports connection object AsyncIndex asyncIndex = pinecone.getAsyncIndexConnection("example-index"); // Cancel import asyncIndex.cancelImport("2"); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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/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) } importID := "101" err = idxConnection.CancelImport(ctx, importID) if err != nil { log.Fatalf("Failed to cancel import: %s", importID) } importDesc, err := idxConnection.DescribeImport(ctx, importID) if err != nil { log.Fatalf("Failed to describe import: %s - %v", importID, err) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var cancelResponse = await index.CancelBulkImportAsync("101"); ``` ```bash curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl -X DELETE "https://{INDEX_HOST}/bulk/imports/101" \ -H 'Api-Key: $YOUR_API_KEY' \ -H "X-Pinecone-API-Version: 2024-10" ``` # Delete vectors data_2024-10 post /vectors/delete The `delete` operation deletes vectors, by id, from a single namespace. For guidance and examples, see [Delete data](https://docs.pinecone.io/guides/data/delete-data). ```python Python # pip install pinecone[grpc] 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/data/target-an-index index = pc.Index(host="INDEX_HOST") index.delete(ids=["id-1", "id-2"], namespace="example-namespace") ``` ```javascript JavaScript 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") const ns = index.namespace('example-namespace') // Delete one record by ID. await ns.deleteOne('id-1'); // Delete more than one record by ID. await ns.deleteMany(['id-2', 'id-3']); ``` ```java Java import io.pinecone.clients.Index; import io.pinecone.configs.PineconeConfig; import io.pinecone.configs.PineconeConnection; import java.util.Arrays; import java.util.List; public class DeleteVectorsExample { 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/data/target-an-index config.setHost("INDEX_HOST"); PineconeConnection connection = new PineconeConnection(config); Index index = new Index(connection, "INDEX_NAME"); List ids = Arrays.asList("id-1 ", "id-2"); index.deleteByIds(ids, "example-namespace"); } } ``` ```go Go package main import ( "context" "log" "github.com/pinecone-io/go-pinecone/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/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) } id1 := "id-1" id2 := "id-2" err = idxConnection.DeleteVectorsByID(ctx, []string{id1, id2}) if err != nil { log.Fatalf("Failed to delete vector with ID %v: %v", id, err) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var deleteResponse = await index.DeleteAsync(new DeleteRequest { Ids = new List { "id-1", "id-2" }, Namespace = "example-namespace", }); ``` ```shell curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl "https://$INDEX_HOST/vectors/delete" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "Content-Type: application/json" \ -H "X-Pinecone-API-Version: 2024-10" \ -d '{ "ids": [ "id-1", "id-2" ], "namespace": "example-namespace" } ' ``` # Describe an import data_2024-10 get /bulk/imports/{id} The `describe_import` operation returns details of a specific import operation. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). This feature is in [public preview](/release-notes/feature-availability) and available only on [Standard and Enterprise plans](https://www.pinecone.io/pricing/). ```python Python 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/data/target-an-index index = pc.Index(host="INDEX_HOST") index.describe_import(id="101") ``` ```javascript JavaScript 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") const results = await index.describeImport(id='101'); console.log(results); ``` ```java Java import io.pinecone.clients.Pinecone; import io.pinecone.clients.AsyncIndex; import org.openapitools.db_data.client.ApiException; import org.openapitools.db_data.client.model.ImportModel; public class DescribeImport { public static void main(String[] args) throws ApiException { // Initialize a Pinecone client with your API key Pinecone pinecone = new Pinecone.Builder("YOUR_API_KEY").build(); // Get async imports connection object AsyncIndex asyncIndex = pinecone.getAsyncIndexConnection("example-index"); // Describe import ImportModel importDetails = asyncIndex.describeImport("101"); System.out.println(importDetails); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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/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) } importID := "101" importDesc, err := idxConnection.DescribeImport(ctx, importID) if err != nil { log.Fatalf("Failed to describe import: %s - %v", importID, err) } fmt.Printf("Import ID: %s, Status: %s", importDesc.Id, importDesc.Status) } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var importDetails = await index.DescribeBulkImportAsync("101"); ``` ```bash curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl -X GET "https://{INDEX_HOST}/bulk/imports/101" \ -H 'Api-Key: $YOUR_API_KEY' \ -H 'X-Pinecone-API-Version: 2024-10' ``` # Get index stats data_2024-10 post /describe_index_stats The `describe_index_stats` operation returns statistics about the contents of an index, including the vector count per namespace, the number of dimensions, and the index fullness. Serverless indexes scale automatically as needed, so index fullness is relevant only for pod-based indexes. For pod-based indexes, the index fullness result may be inaccurate during pod resizing; to get the status of a pod resizing process, use [`describe_index`](https://docs.pinecone.io/reference/api/control-plane/describe_index). ```python Python # pip install pinecone[grpc] 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/data/target-an-index index = pc.Index(host="INDEX_HOST") index.describe_index_stats() ``` ```javascript JavaScript // npm install @pinecone-database/pinecone 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") const stats = await index.describeIndexStats(); ``` ```java Java import io.pinecone.clients.Index; import io.pinecone.configs.PineconeConfig; import io.pinecone.configs.PineconeConnection; import io.pinecone.proto.DescribeIndexStatsResponse; public class DescribeIndexStatsExample { 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/data/target-an-index config.setHost("INDEX_HOST"); PineconeConnection connection = new PineconeConnection(config); Index index = new Index(connection, "INDEX_NAME"); DescribeIndexStatsResponse indexStatsResponse = index.describeIndexStats(); System.out.println(indexStatsResponse); } } ``` ```go Go package main import ( "context" "log" "github.com/pinecone-io/go-pinecone/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/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) } stats, err := idxConnection.DescribeIndexStats(ctx) if err != nil { log.Fatalf("Failed to describe index \"%v\": %v", idx.Name, err) } else { fmt.Printf("%+v", *stats) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var indexStatsResponse = await index.DescribeIndexStatsAsync(new DescribeIndexStatsRequest()); Console.WriteLine(indexStatsResponse); ``` ```shell curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl -X POST "https://$INDEX_HOST/describe_index_stats" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" ``` {/* ```shell { "namespaces": { "example-namespace1": { "vectorCount": 4 }, "example-namespace2": { "vectorCount": 4 } }, "dimension": 8, "indexFullness": 0.00008, "totalVectorCount": 8 } ``` */} # Fetch vectors data_2024-10 get /vectors/fetch The `fetch` operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. For guidance and examples, see [Fetch data](https://docs.pinecone.io/guides/data/fetch-data). ```python Python # pip install pinecone[grpc] 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/data/target-an-index index = pc.Index(host="INDEX_HOST") index.fetch(ids=["id-1", "id-2"], namespace="example-namespace") ``` ```javascript JavaScript // npm install @pinecone-database/pinecone 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") const fetchResult = await index.namespace('example-namespace').fetch(['id-1', 'id-2']); ``` ```java Java import io.pinecone.clients.Index; import io.pinecone.configs.PineconeConfig; import io.pinecone.configs.PineconeConnection; import io.pinecone.proto.FetchResponse; import java.util.Arrays; import java.util.List; public class FetchExample { 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/data/target-an-index config.setHost("INDEX_HOST"); PineconeConnection connection = new PineconeConnection(config); Index index = new Index(connection, "INDEX_NAME"); List ids = Arrays.asList("id-1", "id-2"); FetchResponse fetchResponse = index.fetch(ids, "example-namespace"); System.out.println(fetchResponse); } } ``` ```go Go package main import ( "context" "encoding/json" "fmt" "log" "github.com/pinecone-io/go-pinecone/pinecone" ) func prettifyStruct(obj interface{}) string { bytes, _ := json.MarshalIndent(obj, "", " ") return string(bytes) } 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/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) } res, err := idxConnection.FetchVectors(ctx, []string{"id-1", "id-2"}) if err != nil { log.Fatalf("Failed to fetch vectors: %+v", err) } else { fmt.Printf(prettifyStruct(res)) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var fetchResponse = await index.FetchAsync(new FetchRequest { Ids = new List { "id-1", "id-2" }, Namespace = "example-namespace", }); Console.WriteLine(fetchResponse); ``` ```shell curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl -X GET "https://$INDEX_HOST/vectors/fetch?ids=id-1&ids=id-2&namespace=example-namespace" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" ``` {/* ```shell { "vectors": { "id-1": { "id": "id-1", "values": [0.568879, 0.632687092, 0.856837332, ...] }, "id-2": { "id": "id-2", "values": [0.00891787093, 0.581895, 0.315718859, ...] } }, "namespace": "example-namespace" "usage": {"readUnits": 1}, } ``` */} # List vector IDs data_2024-10 get /vectors/list The `list` operation lists the IDs of vectors in a single namespace of a serverless index. An optional prefix can be passed to limit the results to IDs with a common prefix. By default, `list` returns up to 100 IDs per page in sorted order (bitwise "C" collation). If the `limit` parameter is set, `list` returns up to that number of IDs instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of IDs. When the response does not include a `pagination_token`, there are no more IDs to return. For guidance and examples, see [List record IDs](https://docs.pinecone.io/guides/data/list-record-ids). **Note:** `list_vectors` is supported only for serverless indexes. ```python Python # pip install pinecone[grpc] 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/data/target-an-index index = pc.Index(host="INDEX_HOST") # To iterate over all result pages using a generator function for ids in index.list(prefix="document1#", namespace="example-namespace"): print(ids) # For manual control over pagination results = index.list_paginated( prefix="document1#", limit=3, namespace="example-namespace", pagination_token="eyJza2lwX3Bhc3QiOiIxMDEwMy0=" ) ``` ```javascript JavaScript // npm install @pinecone-database/pinecone import { Pinecone } from '@pinecone-database/pinecone'; const pc = new Pinecone(); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST").namespace("example-namespace"); const results = await index.listPaginated({ prefix: 'document1#' }); console.log(results); // Fetch the next page of results await index.listPaginated({ prefix: 'document1#', paginationToken: results.pagination.next}); ``` ```java Java import io.pinecone.clients.Index; import io.pinecone.configs.PineconeConfig; import io.pinecone.configs.PineconeConnection; import io.pinecone.proto.ListResponse; public class ListExample { 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/data/target-an-index config.setHost("INDEX_HOST"); PineconeConnection connection = new PineconeConnection(config); Index index = new Index(connection, "INDEX_NAME"); ListResponse listResponse = index.list("example-namespace", "document1#"); System.out.println(listResponse); } } ``` ```go Go package main import ( "context" "encoding/json" "fmt" "log" "github.com/pinecone-io/go-pinecone/pinecone" ) func prettifyStruct(obj interface{}) string { bytes, _ := json.MarshalIndent(obj, "", " ") return string(bytes) } 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/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) } limit := uint32(3) prefix := "document1#" res, err := idxConnection.ListVectors(ctx, &pinecone.ListVectorsRequest{ Limit: &limit, Prefix: &prefix, }) if len(res.VectorIds) == 0 { fmt.Println("No vectors found") } else { fmt.Printf(prettifyStruct(res)) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var listResponse = await index.ListAsync(new ListRequest { Namespace = "example-namespace", Prefix = "document1#", }); Console.WriteLine(listResponse); ``` ```shell curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl -X GET "https://$INDEX_HOST/vectors/list?namespace=example-namespace&prefix=document1#" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" ``` # List imports data_2024-10 get /bulk/imports The `list_imports` operation lists all recent and ongoing import operations. By default, `list_imports` returns up to 100 imports per page. If the `limit` parameter is set, `list` returns up to that number of imports instead. Whenever there are additional IDs to return, the response also includes a `pagination_token` that you can use to get the next batch of imports. When the response does not include a `pagination_token`, there are no more imports to return. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). This feature is in [public preview](/release-notes/feature-availability) and available only on [Standard and Enterprise plans](https://www.pinecone.io/pricing/). ```python Python from pinecone import Pinecone, ImportErrorMode pc = Pinecone(api_key="YOUR_API_KEY") # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index index = pc.Index(host="INDEX_HOST") # List using a generator that handles pagination for i in index.list_imports(): print(f"id: {i.id} status: {i.status}") # List using a generator that fetches all results at once operations = list(index.list_imports()) print(operations) ``` ```javascript JavaScript 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") const results = await index.listImports(); console.log(results); // Fetch the next page of results const results = await index.listImports({ paginationToken: 'Tm90aGluZyB0byBzZWUgaGVyZQo' }); ``` ```java Java import io.pinecone.clients.Pinecone; import io.pinecone.clients.AsyncIndex; import org.openapitools.db_data.client.ApiException; import org.openapitools.db_data.client.model.ListImportsResponse; public class ListImports { public static void main(String[] args) throws ApiException { // Initialize a Pinecone client with your API key Pinecone pinecone = new Pinecone.Builder("YOUR_API_KEY").build(); // Get async imports connection object AsyncIndex asyncIndex = pinecone.getAsyncIndexConnection("example-index"); // List imports ListImportsResponse response = asyncIndex.listImports(10, "Tm90aGluZyB0byBzZWUgaGVyZQo"); System.out.println(response); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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/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) } limit := int32(10) firstImportPage, err := idxConnection.ListImports(ctx, &limit, nil) if err != nil { log.Fatalf("Failed to list imports: %v", err) } fmt.Printf("First page of imports: %+v", firstImportPage.Imports) paginationToken := firstImportPage.NextPaginationToken nextImportPage, err := idxConnection.ListImports(ctx, &limit, paginationToken) if err != nil { log.Fatalf("Failed to list imports: %v", err) } fmt.Printf("Second page of imports: %+v", nextImportPage.Imports) } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var imports = await index.ListBulkImportsAsync(new ListBulkImportsRequest { Limit = 10, PaginationToken = "Tm90aGluZyB0byBzZWUgaGVyZQo" }); ``` ```bash curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl -X GET "https://$INDEX_HOST/bulk/imports?paginationToken==Tm90aGluZyB0byBzZWUgaGVyZQo" \ -H "Api-Key: $YOUR_API_KEY" \ -H "X-Pinecone-API-Version: 2024-10" ``` # Query vectors data_2024-10 post /query The `query` operation searches a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. For guidance and examples, see [Query data](https://docs.pinecone.io/guides/data/query-data). ```python Python # pip install pinecone[grpc] 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/data/target-an-index index = pc.Index(host="INDEX_HOST") index.query( namespace="example-namespace", vector=[0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3], filter={ "genre": {"$eq": "documentary"} }, top_k=3, include_values=True ) ``` ```javascript JavaScript // npm install @pinecone-database/pinecone 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") const queryResponse = await index.namespace('example-namespace').query({ vector: [0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3], filter: { 'genre': {'$eq': 'documentary'} }, topK: 3, includeValues: true }); ``` ```java Java 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.unsigned_indices_model.QueryResponseWithUnsignedIndices; import java.util.Arrays; import java.util.List; public class QueryExample { 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/data/target-an-index config.setHost("INDEX_HOST"); PineconeConnection connection = new PineconeConnection(config); Index index = new Index(connection, "INDEX_NAME"); List query = Arrays.asList(0.3f, 0.3f, 0.3f, 0.3f, 0.3f, 0.3f, 0.3f, 0.3f); Struct filter = Struct.newBuilder() .putFields("genre", Value.newBuilder() .setStructValue(Struct.newBuilder() .putFields("$eq", Value.newBuilder() .setStringValue("documentary") .build())) .build()) .build(); QueryResponseWithUnsignedIndices queryResponse = index.query(3, query, null, null, null, "example-namespace", filter, false, true); System.out.println(queryResponse); } } ``` ```go Go package main import ( "context" "encoding/json" "fmt" "log" "github.com/pinecone-io/go-pinecone/pinecone" "google.golang.org/protobuf/types/known/structpb" ) func prettifyStruct(obj interface{}) string { bytes, _ := json.MarshalIndent(obj, "", " ") return string(bytes) } 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/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) } queryVector := []float32{0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3} metadataMap := map[string]interface{}{ "genre": map[string]interface{}{ "$eq": "documentary", }, } metadataFilter, err := structpb.NewStruct(metadataMap) if err != nil { log.Fatalf("Failed to create metadata map: %v", err) } res, err := idxConnection.QueryByVectorValues(ctx, &pinecone.QueryByVectorValuesRequest{ Vector: queryVector, TopK: 3, MetadataFilter: metadataFilter, IncludeValues: true, }) if err != nil { log.Fatalf("Error encountered when querying by vector: %v", err) } else { fmt.Printf(prettifyStruct(res)) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var queryResponse = await index.QueryAsync(new QueryRequest { Vector = new[] { 0.3f, 0.3f, 0.3f, 0.3f, 0.3f, 0.3f, 0.3f, 0.3f }, Namespace = "example-namespace", TopK = 3, Filter = new Metadata { ["genre"] = new Metadata { ["$eq"] = "documentary", } } }); Console.WriteLine(queryResponse); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl "https://$INDEX_HOST/query" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "Content-Type: application/json" \ -H "X-Pinecone-API-Version: 2024-10" \ -d '{ "namespace": "example-namespace", "vector": [0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3], "filter": {"genre": {"$eq": "documentary"}}, "topK": 3, "includeValues": true }' ``` ```shell { "matches":[ { "id": "vec3", "score": 0, "values": [0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3] }, { "id": "vec2", "score": 0.0800000429, "values": [0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2] }, { "id": "vec4", "score": 0.0799999237, "values": [0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4] } ], "namespace": "example-namespace", "usage": {"read_units": 6} } ``` # Start import data_2024-10 post /bulk/imports The `start_import` operation starts an asynchronous import of vectors from object storage into an index. For guidance and examples, see [Import data](https://docs.pinecone.io/guides/data/import-data). This feature is in [public preview](/release-notes/feature-availability) and available only on [Standard and Enterprise plans](https://www.pinecone.io/pricing/). ```python Python from pinecone import Pinecone, ImportErrorMode pc = Pinecone(api_key="YOUR_API_KEY") # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index index = pc.Index(host="INDEX_HOST") root = "s3://BUCKET_NAME/PATH/TO/DIR" index.start_import( uri=root, error_mode=ImportErrorMode.CONTINUE, # or ImportErrorMode.ABORT integration_id="a12b3d4c-47d2-492c-a97a-dd98c8dbefde" # Optional for public buckets ) ``` ```javascript JavaScript 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") const storageURI = 's3://BUCKET_NAME/PATH/TO/DIR'; const errorMode = 'continue'; // or 'abort' const integrationID = 'a12b3d4c-47d2-492c-a97a-dd98c8dbefde'; // Optional for public buckets await index.startImport(storageURI, errorMode, integrationID); ``` ```java Java import io.pinecone.clients.Pinecone; import io.pinecone.clients.AsyncIndex; import org.openapitools.db_data.client.ApiException; import org.openapitools.db_data.client.model.ImportErrorMode; import org.openapitools.db_data.client.model.StartImportResponse; public class StartImport { public static void main(String[] args) throws ApiException { // Initialize a Pinecone client with your API key Pinecone pinecone = new Pinecone.Builder("YOUR_API_KEY").build(); // Get async imports connection object AsyncIndex asyncIndex = pinecone.getAsyncIndexConnection("example-index"); // s3 uri String uri = "s3://BUCKET_NAME/PATH/TO/DIR"; // Integration ID (optional for public buckets) String integrationId = "a12b3d4c-47d2-492c-a97a-dd98c8dbefde"; // Start an import StartImportResponse response = asyncIndex.startImport(uri, integrationId, ImportErrorMode.OnErrorEnum.CONTINUE); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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/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) } uri := "s3://BUCKET_NAME/PATH/TO/DIR" errorMode := "continue" // or "abort" importRes, err := idxConnection.StartImport(ctx, uri, nil, (*pinecone.ImportErrorMode)(&errorMode)) if err != nil { log.Fatalf("Failed to start import: %v", err) } fmt.Printf("Import started with ID: %s", importRes.Id) } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var uri = "s3://BUCKET_NAME/PATH/TO/DIR"; var response = await index.StartBulkImportAsync(new StartImportRequest { Uri = uri, IntegrationId = "a12b3d4c-47d2-492c-a97a-dd98c8dbefde", ErrorMode = new ImportErrorMode { OnError = ImportErrorModeOnError.Continue } }); ``` ```bash curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl "https://$INDEX_HOST/bulk/imports" \ -H 'Api-Key: $YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -H 'X-Pinecone-API-Version: 2024-10' \ -d '{ "integrationId": "a12b3d4c-47d2-492c-a97a-dd98c8dbefde", "uri": "s3://BUCKET_NAME/PATH/TO/DIR", "errorMode": { "onError": "continue" } }' ``` # Update a vector data_2024-10 post /vectors/update The `update` operation updates a vector in a namespace. If a value is included, it will overwrite the previous value. If a `set_metadata` is included, the values of the fields specified in it will be added or overwrite the previous value. For guidance and examples, see [Update data](https://docs.pinecone.io/guides/data/update-data). ```python Python # pip install pinecone[grpc] 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/data/target-an-index index = pc.Index(host="INDEX_HOST") index.update( id="id-3", values=[4.0, 2.0], set_metadata={"genre": "comedy"}, namespace="example-namespace" ) ``` ```javascript JavaScript // npm install @pinecone-database/pinecone 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") await index.namespace('example-namespace').update({ id: 'id-3', values: [4.0, 2.0], metadata: { genre: "comedy", }, }); ``` ```java Java 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.UpdateResponse; import java.util.Arrays; import java.util.List; public class UpdateExample { 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/data/target-an-index config.setHost("INDEX_HOST"); PineconeConnection connection = new PineconeConnection(config); Index index = new Index(connection, "INDEX_NAME"); List values = Arrays.asList(4.0f, 2.0f); Struct metaData = Struct.newBuilder() .putFields("genre", Value.newBuilder().setStringValue("comedy").build()) .build(); UpdateResponse updateResponse = index.update("id-3", values, metaData, "example-namespace", null, null); System.out.println(updateResponse); } } ``` ```go Go package main import ( "context" "log" "github.com/pinecone-io/go-pinecone/pinecone" "google.golang.org/protobuf/types/known/structpb" ) 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/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) } id := "id-3" metadataMap := map[string]interface{}{ "genre": "comedy", } metadataFilter, err := structpb.NewStruct(metadataMap) if err != nil { log.Fatalf("Failed to create metadata map: %v", err) } err = idxConnection.UpdateVector(ctx, &pinecone.UpdateVectorRequest{ Id: id, Metadata: metadataFilter, }) if err != nil { log.Fatalf("Failed to update vector with ID %v: %v", id, err) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var updateResponse = await index.UpdateAsync(new UpdateRequest { Id = "id-3", Values = new[] { 4.0f, 2.0f }, SetMetadata = new Metadata { ["genre"] = "comedy" }, Namespace = "example-namespace", }); ``` ```shell curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl "https://$INDEX_HOST/vectors/update" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "Content-Type: application/json" \ -H "X-Pinecone-API-Version: 2024-10" \ -d '{ "id": "id-3", "values": [4.0, 2.0], "setMetadata": {"type": "comedy"}, "namespace": "example-namespace" }' ``` # Upsert vectors data_2024-10 post /vectors/upsert The `upsert` operation writes vectors into a namespace. If a new value is upserted for an existing vector ID, it will overwrite the previous value. For guidance and examples, see [Upsert data](https://docs.pinecone.io/guides/data/upsert-data). ```python Python # pip install pinecone[grpc] 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/data/target-an-index index = pc.Index(host="INDEX_HOST") upsert_response = index.upsert( vectors=[ { "id": "vec1", "values": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8], "sparse_values": { "indices": [1, 5], "values": [0.5, 0.5] }, "metadata": { "genre": "drama" } }, { "id": "vec2", "values": [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], "sparse_values": { "indices": [5, 6], "values": [0.4, 0.5] }, "metadata": { "genre": "action" } } ], namespace="example-namespace" ) ``` ```javascript JavaScript // npm install @pinecone-database/pinecone 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/data/target-an-index const index = pc.index("INDEX_NAME", "INDEX_HOST") await index.namespace('example-namespace').upsert([ { id: 'vec1', values: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8], sparseValues: { indices: [1, 5], values: [0.5, 0.5] }, metadata: {'genre': 'drama'}, }, { id: 'vec2', values: [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], metadata: {'genre': 'action'}, sparseValues: { indices: [5, 6], values: [0.4, 0.5] } } ]) ``` ```java Java 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 java.util.Arrays; 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/data/target-an-index config.setHost("INDEX_HOST"); PineconeConnection connection = new PineconeConnection(config); Index index = new Index(connection, "INDEX_NAME"); List values1 = Arrays.asList(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f); List values2 = Arrays.asList(0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f); Struct metaData1 = Struct.newBuilder() .putFields("genre", Value.newBuilder().setStringValue("drama").build()) .build(); Struct metaData2 = Struct.newBuilder() .putFields("genre", Value.newBuilder().setStringValue("action").build()) .build(); index.upsert("A", values1, null, null, metaData1, null); index.upsert("B", values2, null, null, metaData2, null); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/pinecone" "google.golang.org/protobuf/types/known/structpb" ) 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/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) } sparseValues1 := pinecone.SparseValues{ Indices: []uint32{1, 5}, Values: []float32{0.5, 0.5}, } sparseValues2 := pinecone.SparseValues{ Indices: []uint32{5, 6}, Values: []float32{0.4, 0.5}, } metadataMap1 := map[string]interface{}{ "genre": "comedy", "year": 2020, } metadata1, err := structpb.NewStruct(metadataMap1) if err != nil { log.Fatalf("Failed to create metadata map: %v", err) } metadataMap2 := map[string]interface{}{ "genre": "documentary", "year": 2019, } metadata2, err := structpb.NewStruct(metadataMap2) if err != nil { log.Fatalf("Failed to create metadata map: %v", err) } vectors := []*pinecone.Vector{ { Id: "vec1", Values: []float32{0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}, SparseValues: &sparseValues1, Metadata: metadata1, }, { Id: "vec2", Values: []float32{0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}, SparseValues: &sparseValues2, Metadata: metadata2, }, } count, err := idxConnection.UpsertVectors(ctx, vectors) if err != nil { log.Fatalf("Failed to upsert vectors: %v", err) } else { fmt.Printf("Successfully upserted %d vector(s)!\n", count) } } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // To get the unique host for an index, // see https://docs.pinecone.io/guides/data/target-an-index var index = pinecone.Index(host: "INDEX_HOST"); var upsertResponse = await index.UpsertAsync(new UpsertRequest { Vectors = new[] { new Vector { Id = "vec1", Values = new[] { 1.0f, 1.5f }, SparseValues = new SparseValues { Indices = [1, 5], Values = new[] { 0.5f, 0.5f }, }, Metadata = new Metadata { ["genre"] = new("comedy"), ["year"] = new(2020), } }, new Vector { Id = "vec2", Values = new[] { 2.0f, 1.0f }, SparseValues = new SparseValues { Indices = [5, 6], Values = new[] { 0.4f, 0.5f }, }, Metadata = new Metadata { ["genre"] = new("documentary"), ["year"] = new(2019), }, } }, Namespace = "example-namespace", }); ``` ```shell curl # To get the unique host for an index, # see https://docs.pinecone.io/guides/data/target-an-index PINECONE_API_KEY="YOUR_API_KEY" INDEX_HOST="INDEX_HOST" curl "https://$INDEX_HOST/vectors/upsert" \ -H "Api-Key: $PINECONE_API_KEY" \ -H "Content-Type: application/json" \ -H "X-Pinecone-API-Version: 2024-10" \ -d '{ "vectors": [ { "id": "vec1", "values": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8], "sparseValues": { "indices": [2, 7], "values": [0.4, 0.5] }, "metadata": { "genre": "drama" } }, { "id": "vec2", "values": [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], "sparseValues": { "indices": [1, 4], "values": [0.1, 0.2] }, "metadata": { "genre": "action" } } ], "namespace": "example-namespace" }' ``` # Embed data inference_2024-10 post /embed Generate embeddings for input data. For guidance and examples, see [Generate embeddings](https://docs.pinecone.io/guides/inference/generate-embeddings). ```python Python # Import the Pinecone library from pinecone.grpc import PineconeGRPC as Pinecone from pinecone import ServerlessSpec import time # Initialize a Pinecone client with your API key pc = Pinecone(api_key="YOUR_API_KEY") # Define a sample dataset where each item has a unique ID and piece of text data = [ {"id": "vec1", "text": "Apple is a popular fruit known for its sweetness and crisp texture."}, {"id": "vec2", "text": "The tech company Apple is known for its innovative products like the iPhone."}, {"id": "vec3", "text": "Many people enjoy eating apples as a healthy snack."}, {"id": "vec4", "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."}, {"id": "vec5", "text": "An apple a day keeps the doctor away, as the saying goes."}, {"id": "vec6", "text": "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership."} ] # Convert the text into numerical vectors that Pinecone can index embeddings = pc.inference.embed( model="multilingual-e5-large", inputs=[d['text'] for d in data], parameters={"input_type": "passage", "truncate": "END"} ) print(embeddings) ``` ```javascript JavaScript // Import the Pinecone library import { Pinecone } from '@pinecone-database/pinecone'; // Initialize a Pinecone client with your API key const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }); // Define a sample dataset where each item has a unique ID and piece of text const data = [ { id: 'vec1', text: 'Apple is a popular fruit known for its sweetness and crisp texture.' }, { id: 'vec2', text: 'The tech company Apple is known for its innovative products like the iPhone.' }, { id: 'vec3', text: 'Many people enjoy eating apples as a healthy snack.' }, { id: 'vec4', text: 'Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.' }, { id: 'vec5', text: 'An apple a day keeps the doctor away, as the saying goes.' }, { id: 'vec6', text: 'Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership.' } ]; // Convert the text into numerical vectors that Pinecone can index const model = 'multilingual-e5-large'; const embeddings = await pc.inference.embed( model, data.map(d => d.text), { inputType: 'passage', truncate: 'END' } ); console.log(embeddings); ``` ```java Java // Import the required classes import io.pinecone.clients.Index; import io.pinecone.clients.Inference; import io.pinecone.clients.Pinecone; import org.openapitools.inference.client.ApiException; import org.openapitools.inference.client.model.Embedding; import java.math.BigDecimal; import java.util.*; import java.util.stream.Collectors; public class GenerateEmbeddings { public static void main(String[] args) throws ApiException { // Initialize a Pinecone client with your API key Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); Inference inference = pc.getInferenceClient(); // Prepare input sentences to be embedded List data = Arrays.asList( new DataObject("vec1", "Apple is a popular fruit known for its sweetness and crisp texture."), new DataObject("vec2", "The tech company Apple is known for its innovative products like the iPhone."), new DataObject("vec3", "Many people enjoy eating apples as a healthy snack."), new DataObject("vec4", "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."), new DataObject("vec5", "An apple a day keeps the doctor away, as the saying goes."), new DataObject("vec6", "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership.") ); List inputs = data.stream() .map(DataObject::getText) .collect(Collectors.toList()); // Specify the embedding model and parameters String embeddingModel = "multilingual-e5-large"; Map parameters = new HashMap<>(); parameters.put("input_type", "passage"); parameters.put("truncate", "END"); // Convert the text into numerical vectors that Pinecone can index List embeddingsList = inference.embed(embeddingModel, parameters, inputs).getData(); } private static List convertBigDecimalToFloat(List bigDecimalValues) { return bigDecimalValues.stream() .map(BigDecimal::floatValue) .collect(Collectors.toList()); } } class DataObject { private String id; private String text; public DataObject(String id, String text) { this.id = id; this.text = text; } public String getId() { return id; } public String getText() { return text; } } ``` ```go Go package main // Import the required packages import ( "context" "encoding/json" "fmt" "log" "github.com/pinecone-io/go-pinecone/pinecone" ) type Data struct { ID string Text string } type Query struct { Text string } func prettifyStruct(obj interface{}) string { bytes, _ := json.MarshalIndent(obj, "", " ") return string(bytes) } func main() { ctx := context.Background() // Initialize a Pinecone client with your API key pc, err := pinecone.NewClient(pinecone.NewClientParams{ ApiKey: "YOUR_API_KEY", }) if err != nil { log.Fatalf("Failed to create Client: %v", err) } // Define a sample dataset where each item has a unique ID and piece of text data := []Data{ {ID: "vec1", Text: "Apple is a popular fruit known for its sweetness and crisp texture."}, {ID: "vec2", Text: "The tech company Apple is known for its innovative products like the iPhone."}, {ID: "vec3", Text: "Many people enjoy eating apples as a healthy snack."}, {ID: "vec4", Text: "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."}, {ID: "vec5", Text: "An apple a day keeps the doctor away, as the saying goes."}, {ID: "vec6", Text: "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership."}, } // Specify the embedding model and parameters embeddingModel := "multilingual-e5-large" docParameters := pinecone.EmbedParameters{ InputType: "passage", Truncate: "END", } // Convert the text into numerical vectors that Pinecone can index var documents []string for _, d := range data { documents = append(documents, d.Text) } docEmbeddingsResponse, err := pc.Inference.Embed(ctx, &pinecone.EmbedRequest{ Model: embeddingModel, TextInputs: documents, Parameters: docParameters, }) if err != nil { log.Fatalf("Failed to embed documents: %v", err) } else { fmt.Printf(prettifyStruct(docEmbeddingsResponse)) } } ``` ```csharp C# using Pinecone; using System; using System.Collections.Generic; // Initialize a Pinecone client with your API key var pinecone = new PineconeClient("YOUR_API_KEY"); // Prepare input sentences to be embedded var data = new[] { new { Id = "vec1", Text = "Apple is a popular fruit known for its sweetness and crisp texture." }, new { Id = "vec2", Text = "The tech company Apple is known for its innovative products like the iPhone." }, new { Id = "vec3", Text = "Many people enjoy eating apples as a healthy snack." }, new { Id = "vec4", Text = "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces." }, new { Id = "vec5", Text = "An apple a day keeps the doctor away, as the saying goes." }, new { Id = "vec6", Text = "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership." } }; // Specify the embedding model and parameters var embeddingModel = "multilingual-e5-large"; // Generate embeddings for the input data var embeddings = await pinecone.Inference.EmbedAsync(new EmbedRequest { Model = embeddingModel, Inputs = data.Select(item => new EmbedRequestInputsItem { Text = item.Text }), Parameters = new EmbedRequestParameters { InputType = "passage", Truncate = "END" } }); Console.WriteLine(embeddings); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl https://api.pinecone.io/embed \ -H "Api-Key: $PINECONE_API_KEY" \ -H "Content-Type: application/json" \ -H "X-Pinecone-API-Version: 2024-10" \ -d '{ "model": "multilingual-e5-large", "parameters": { "input_type": "passage", "truncate": "END" }, "inputs": [ {"text": "Apple is a popular fruit known for its sweetness and crisp texture."}, {"text": "The tech company Apple is known for its innovative products like the iPhone."}, {"text": "Many people enjoy eating apples as a healthy snack."}, {"text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."}, {"text": "An apple a day keeps the doctor away, as the saying goes."}, {"text": "Apple Computer Company was founded on April 1, 1976, by Steve Jobs, Steve Wozniak, and Ronald Wayne as a partnership."} ] }' ``` ```python Python EmbeddingsList( model='multilingual-e5-large', data=[ {'values': [0.04925537109375, -0.01313018798828125, -0.0112762451171875, ...]}, ... ], usage={'total_tokens': 130} ) ``` ```javascript JavaScript EmbeddingsList(1) [ { values: [ 0.04925537109375, -0.01313018798828125, -0.0112762451171875, ... ] }, ... model: 'multilingual-e5-large', data: [ { values: [Array] } ], usage: { totalTokens: 130 } ] ``` ```java Java class EmbeddingsList { model: multilingual-e5-large data: [class Embedding { values: [0.04925537109375, -0.01313018798828125, -0.0112762451171875, ...] additionalProperties: null }, ...] usage: class EmbeddingsListUsage { totalTokens: 130 additionalProperties: null } additionalProperties: null } ``` ```go Go { "data": [ { "values": [ 0.03942871, -0.010177612, -0.046051025, ... ] }, ... ], "model": "multilingual-e5-large", "usage": { "total_tokens": 130 } } ``` ```csharp C# { "model": "multilingual-e5-large", "data": [ { "values": [ 0.04913330078125, -0.01306915283203125, -0.01116180419921875, ... ] }, ... ], "usage": { "total_tokens": 130 } } ``` ```json curl { "data": [ { "values": [ 0.04925537109375, -0.01313018798828125, -0.0112762451171875, ... ] }, ... ], "model": "multilingual-e5-large", "usage": { "total_tokens": 130 } } ``` # Rerank documents inference_2024-10 post /rerank Rerank documents according to their relevance to a query. For guidance and examples, see [Rerank documents](https://docs.pinecone.io/guides/inference/rerank). ```python Python from pinecone.grpc import PineconeGRPC as Pinecone pc = Pinecone(api_key="YOUR_API_KEY") result = pc.inference.rerank( model="bge-reranker-v2-m3", query="The tech company Apple is known for its innovative products like the iPhone.", documents=[ {"id": "vec1", "text": "Apple is a popular fruit known for its sweetness and crisp texture."}, {"id": "vec2", "text": "Many people enjoy eating apples as a healthy snack."}, {"id": "vec3", "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."}, {"id": "vec4", "text": "An apple a day keeps the doctor away, as the saying goes."}, ], top_n=4, return_documents=True, parameters={ "truncate": "END" } ) print(result) ``` ```javascript JavaScript import { Pinecone } from '@pinecone-database/pinecone'; const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' }); const rerankingModel = 'bge-reranker-v2-m3'; const query = 'The tech company Apple is known for its innovative products like the iPhone.'; const documents = [ { id: 'vec1', text: 'Apple is a popular fruit known for its sweetness and crisp texture.' }, { id: 'vec2', text: 'Many people enjoy eating apples as a healthy snack.' }, { id: 'vec3', text: 'Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.' }, { id: 'vec4', text: 'An apple a day keeps the doctor away, as the saying goes.' }, ]; const rerankOptions = { topN: 4, returnDocuments: true, parameters: { truncate: 'END' }, }; const response = await pc.inference.rerank( rerankingModel, query, documents, rerankOptions ); console.log(response); ``` ```java Java import io.pinecone.clients.Inference; import io.pinecone.clients.Pinecone; import org.openapitools.inference.client.model.RerankResult; import org.openapitools.inference.client.ApiException; import java.util.*; public class RerankExample { public static void main(String[] args) throws ApiException { Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build(); Inference inference = pc.getInferenceClient(); // The model to use for reranking String model = "bge-reranker-v2-m3"; // The query to rerank documents against String query = "The tech company Apple is known for its innovative products like the iPhone."; // Add the documents to rerank List> documents = new ArrayList<>(); Map doc1 = new HashMap<>(); doc1.put("id", "vec1"); doc1.put("text", "Apple is a popular fruit known for its sweetness and crisp texture."); documents.add(doc1); Map doc2 = new HashMap<>(); doc2.put("id", "vec2"); doc2.put("text", "Many people enjoy eating apples as a healthy snack."); documents.add(doc2); Map doc3 = new HashMap<>(); doc3.put("id", "vec3"); doc3.put("text", "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."); documents.add(doc3); Map doc4 = new HashMap<>(); doc4.put("id", "vec4"); doc4.put("text", "An apple a day keeps the doctor away, as the saying goes."); documents.add(doc4); // The fields to rank the documents by. If not provided, the default is "text" List rankFields = Arrays.asList("text"); // The number of results to return sorted by relevance. Defaults to the number of inputs int topN = 4; // Whether to return the documents in the response boolean returnDocuments = true; // Additional model-specific parameters for the reranker Map parameters = new HashMap<>(); parameters.put("truncate", "END"); // Send ranking request RerankResult result = inference.rerank(model, query, documents, rankFields, topN, returnDocuments, parameters); // Get ranked data System.out.println(result.getData()); } } ``` ```go Go package main import ( "context" "fmt" "log" "github.com/pinecone-io/go-pinecone/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) } rerankModel := "bge-reranker-v2-m3" topN := 4 returnDocuments := true documents := []pinecone.Document{ {"id": "vec1", "text": "Apple is a popular fruit known for its sweetness and crisp texture."}, {"id": "vec2", "text": "Many people enjoy eating apples as a healthy snack."}, {"id": "vec3", "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."}, {"id": "vec4", "text": "An apple a day keeps the doctor away, as the saying goes."}, } ranking, err := pc.Inference.Rerank(ctx, &pinecone.RerankRequest{ Model: rerankModel, Query: "The tech company Apple is known for its innovative products like the iPhone.", ReturnDocuments: &returnDocuments, TopN: &topN, RankFields: &[]string{"text"}, Documents: documents, }) if err != nil { log.Fatalf("Failed to rerank: %v", err) } fmt.Printf("Rerank result: %+v\n", ranking) } ``` ```csharp C# using Pinecone; var pinecone = new PineconeClient("YOUR_API_KEY"); // The model to use for reranking var model = "bge-reranker-v2-m3"; // The query to rerank documents against var query = "The tech company Apple is known for its innovative products like the iPhone."; // Add the documents to rerank var documents = new List> { new() { ["id"] = "vec1", ["my_field"] = "Apple is a popular fruit known for its sweetness and crisp texture." }, new() { ["id"] = "vec2", ["my_field"] = "Many people enjoy eating apples as a healthy snack." }, new() { ["id"] = "vec3", ["my_field"] = "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces." }, new() { ["id"] = "vec4", ["my_field"] = "An apple a day keeps the doctor away, as the saying goes." } }; // The fields to rank the documents by. If not provided, the default is "text" var rankFields = new List { "my_field" }; // The number of results to return sorted by relevance. Defaults to the number of inputs int topN = 4; // Whether to return the documents in the response bool returnDocuments = true; // Additional model-specific parameters for the reranker var parameters = new Dictionary { ["truncate"] = "END" }; // Send ranking request var result = await pinecone.Inference.RerankAsync( new RerankRequest { Model = model, Query = query, Documents = documents, RankFields = rankFields, TopN = topN, Parameters = parameters }); Console.WriteLine(result); ``` ```shell curl PINECONE_API_KEY="YOUR_API_KEY" curl https://api.pinecone.io/rerank \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -H "X-Pinecone-API-Version: 2024-10" \ -H "Api-Key: $PINECONE_API_KEY" \ -d '{ "model": "bge-reranker-v2-m3", "query": "The tech company Apple is known for its innovative products like the iPhone.", "return_documents": true, "top_n": 4, "documents": [ {"id": "vec1", "text": "Apple is a popular fruit known for its sweetness and crisp texture."}, {"id": "vec2", "text": "Many people enjoy eating apples as a healthy snack."}, {"id": "vec3", "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."}, {"id": "vec4", "text": "An apple a day keeps the doctor away, as the saying goes."} ], "parameters": { "truncate": "END" } }' ``` ```python Python RerankResult( model='bge-reranker-v2-m3', data=[ { index=2, score=0.48357219, document={id="vec3", text="Apple Inc. has re..."} }, { index=0, score=0.048405956, document={id="vec1", text="Apple is a popula..."} }, { index=3, score=0.007846239, document={id="vec4", text="An apple a day ke..."} }, { index=1, score=0.0006563728, document={id="vec2", text="Many people enjoy..."} } ], usage={'rerank_units': 1} ) ``` ```javascript JavaScript { model: 'bge-reranker-v2-m3', data: [ { index: 2, score: 0.48357219, document: [Object] }, { index: 0, score: 0.048405956, document: [Object] }, { index: 3, score: 0.007846239, document: [Object] }, { index: 1, score: 0.0006563728, document: [Object] } ], usage: { rerankUnits: 1 } } ``` ```java Java [class RankedDocument { index: 2 score: 0.48357219 document: {id=vec3, text=Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.} additionalProperties: null }, class RankedDocument { index: 0 score: 0.048405956 document: {id=vec1, text=Apple is a popular fruit known for its sweetness and crisp texture.} additionalProperties: null }, class RankedDocument { index: 3 score: 0.007846239 document: {id=vec4, text=An apple a day keeps the doctor away, as the saying goes.} additionalProperties: null }, class RankedDocument { index: 1 score: 0.0006563728 document: {id=vec2, text=Many people enjoy eating apples as a healthy snack.} additionalProperties: null }] ``` ```go Go Rerank result: { "data": [ { "document": { "id": "vec3", "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces." }, "index": 2, "score": 0.48357219 }, { "document": { "id": "vec1", "text": "Apple is a popular fruit known for its sweetness and crisp texture." }, "index": 0, "score": 0.048405956 }, { "document": { "id": "vec4", "text": "An apple a day keeps the doctor away, as the saying goes." }, "index": 3, "score": 0.007846239 }, { "document": { "id": "vec2", "text": "Many people enjoy eating apples as a healthy snack." }, "index": 1, "score": 0.0006563728 } ], "model": "bge-reranker-v2-m3", "usage": { "rerank_units": 1 } } ``` ```csharp C# { "model": "bge-reranker-v2-m3", "data": [ { "index": 2, "score": 0.48357219, "document": { "id": "vec3", "my_field": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces." } }, { "index": 0, "score": 0.048405956, "document": { "id": "vec1", "my_field": "Apple is a popular fruit known for its sweetness and crisp texture." } }, { "index": 3, "score": 0.007846239, "document": { "id": "vec4", "my_field": "An apple a day keeps the doctor away, as the saying goes." } }, { "index": 1, "score": 0.0006563728, "document": { "id": "vec2", "my_field": "Many people enjoy eating apples as a healthy snack." } } ], "usage": { "rerank_units": 1 } } ``` ```JSON curl { "data":[ { "index":2, "document":{ "id":"vec3", "text":"Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces." }, "score":0.47654688 }, { "index":0, "document":{ "id":"vec1", "text":"Apple is a popular fruit known for its sweetness and crisp texture." }, "score":0.047963805 }, { "index":3, "document":{ "id":"vec4", "text":"An apple a day keeps the doctor away, as the saying goes." }, "score":0.007587992 }, { "index":1, "document":{ "id":"vec2", "text":"Many people enjoy eating apples as a healthy snack." }, "score":0.0006491712 } ], "usage":{ "rerank_units":1 } } ```