將向量插入向量索引 - Amazon Simple Storage Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

將向量插入向量索引

您可以使用 PutVectors API 操作將向量新增至向量索引。每個向量都包含一個索引鍵,可唯一識別向量索引中的每個向量。如果您放置的向量具有已存在於索引中之索引鍵,該向量會完全覆寫現有的向量,導致無法再搜尋先前的向量。若要最大化寫入輸送量並最佳化成本,建議您大量插入向量,直到 的批次大小上限為止PutVectors。不過,對於需要使用較小批次的工作負載 - 例如即時,傳入向量資料必須立即變成可搜尋 - 您可以透過使用較多的並行PutVectors請求來達到更高的寫入輸送量,最高可達每秒允許的請求上限。如需 批次大小上限的詳細資訊PutVectors,也就是每個 PutVectors API 呼叫的向量限制,以及每秒的請求和向量上限,請參閱 限制。此外,您可以將中繼資料 (例如年份、作者、類型、位置) 以鍵值對形式連接到每個向量。根據預設,連接至向量的所有中繼資料索引鍵都是可篩選的,並且可以當作相似度查詢中的篩選條件。只有在向量索引建立期間指定為不可篩選的中繼資料索引鍵,才會排除在篩選範圍外。S3 向量索引支援中繼資料的字串、數字、布林值和清單類型。如需有關每個向量的總中繼資料大小限制,和每個向量的可篩選中繼資料大小限制的詳細資訊,請參閱 限制。如果中繼資料大小超過這些限制,PutVectors API 操作會傳回 400 Bad Request 錯誤。

使用 PutVectors API 操作將向量資料加入至向量索引之前,您需要將原始資料轉換為向量嵌入,這是做為浮點數陣列的內容數字表示法。向量嵌入會擷取內容的語義,一旦透過 PutVectors 操作儲存在向量索引中,就會啟用相似性搜尋。您可以根據您的資料類型和使用案例,使用各種方法來產生向量嵌入。這些方法包括使用機器學習架構、專業嵌入程式庫,或 Amazon Bedrock 等的 AWS 服務。例如,若使用的是 Amazon Bedrock,您可以利用 InvokeModel API 操作和偏好的嵌入模型來產生嵌入。

此外,Amazon Bedrock 知識庫提供全託管端對端 RAG 工作流程,其中 Amazon Bedrock 會自動從 S3 資料來源擷取資料、將內容轉換為文字區塊、產生嵌入,然後將其儲存在向量索引中。接著您可以查詢知識庫,並根據從來源資料擷取的區塊產生回應。

此外,開放原始碼 Amazon S3 Vectors Embed CLI 工具會提供產生嵌入,並從命令列執行語義搜尋的簡化方法。如需有關此開放原始碼工具使用 Amazon Bedrock 基礎模型自動產生向量嵌入,以及在 S3 Vectors 索引中自動產生語義搜尋操作的詳細資訊,請參閱 使用 s3vectors-embed-cli 建立向量嵌入和執行語義搜尋

注意

將向量資料插入向量索引時,您必須提供向量資料來當作 float32 (32 位元浮點) 值。如果您將更精確的值傳遞至 AWS SDK,S3 Vectors 會在儲存值之前將值轉換為 32 位元浮點,而 GetVectorsListVectorsQueryVectors 操作會傳回float32值。 AWS SDKs可能會有不同的預設數值類型,因此請確保您的向量已正確格式化為float32值,無論您使用哪個 SDK。例如,在 Python 中,使用 numpy.float32 或明確轉換您的值。

SDK for Python
# Populate a vector index with embeddings from Amazon Titan Text Embeddings V2. import boto3 import json # Create Bedrock Runtime and S3 Vectors clients in the AWS Region of your choice. bedrock = boto3.client("bedrock-runtime", region_name="us-west-2") s3vectors = boto3.client("s3vectors", region_name="us-west-2") # Texts to convert to embeddings. texts = [ "Star Wars: A farm boy joins rebels to fight an evil empire in space", "Jurassic Park: Scientists create dinosaurs in a theme park that goes wrong", "Finding Nemo: A father fish searches the ocean to find his lost son" ] # Generate vector embeddings. embeddings = [] for text in texts: response = bedrock.invoke_model( modelId="amazon.titan-embed-text-v2:0", body=json.dumps({"inputText": text}) ) # Extract embedding from response. response_body = json.loads(response["body"].read()) embeddings.append(response_body["embedding"]) # Write embeddings into vector index with metadata. s3vectors.put_vectors( vectorBucketName="media-embeddings", indexName="movies", vectors=[ { "key": "Star Wars", "data": {"float32": embeddings[0]}, "metadata": {"source_text": texts[0], "genre":"scifi"} }, { "key": "Jurassic Park", "data": {"float32": embeddings[1]}, "metadata": {"source_text": texts[1], "genre":"scifi"} }, { "key": "Finding Nemo", "data": {"float32": embeddings[2]}, "metadata": {"source_text": texts[2], "genre":"family"} } ] )