Traffine I/O

日本語

2023-06-14

PineconeのUpsertとUpdateの使い分け

はじめに

Pineconeでは、ベクトルデータを更新する際に、全部更新を行うupsertと、部分更新を行うupdateの二つのAPIがあります。この記事では、これらのAPIの使い分けについて説明します。

インデックスの作成

以下のコマンドやコードを実行してPineconeのインデックスを作成します。

bash
$ pip install -U pinecone-client
python
import pinecone

pinecone.init(
    api_key="API_KEY",
    environment="ENVIRONMENT"
)

if "sample" not in pinecone.list_indexes():
    pinecone.create_index("sample", dimension=1536)

index = pinecone.Index("sample")

データの追加

ベクトルデータを登録します。

python
index.upsert(
    vectors=[{
        "id": "1",
        "values': [0.0] * 1536,
        "metadata": {
            "content": "This is a sample vector"
        }
    }],
    namespace='my_namespace'
)

res = index.fetch(
    ids=["1"],
    namespace="my_namespace"
)

print(res["vectors"]["1"]["metadata"])
{'content': 'This is a sample vector'}

データの更新

データを更新するには、updateupsertのAPIにidを指定してデータを更新します。upsertを使う場合は以下のようになります。

python
index.upsert(
    vectors=[{
        "id": "1",
        "values": [0.0] * 1536,
        "metadata": {
            "content": "Updated"
        }
    }],
    namespace="my_namespace"
)

res = index.fetch(
    ids=["1"],
    namespace="my_namespace"
)

print(res["vectors"]["1"]["metadata"])
{'content': 'Updated'}

ベクトルを作るのにコンピューティングリソースがかかります。ベクトルを再生成する必要がない場合は、updatemetadataのみの更新をするのが良いです。

python
index.update(
    id="1",
    setMetadata={
        "content": "Only metatada updated"
    },
    namespace="my_namespace"
)

res = index.fetch(
    ids=["1"],
    namespace="my_namespace"
)

print(res["vectors"]["1"]["metadata"])
{'content': 'Only metatada updated'}

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!