

# 将向量插入向量索引
<a name="s3-vectors-index-create"></a>

可以使用 [PutVectors](https://docs.aws.amazon.com/AmazonS3/latest/API/API_S3VectorBuckets_PutVectors.html) API 操作将向量添加到向量索引。每个向量都由一个键组成，该键唯一标识向量索引中的每个向量。如果您放置的向量具有索引中已存在的键，则此向量将完全覆盖现有向量，这使得前一个向量变得不再可搜索。为了最大限度地提高写入吞吐量并针对成本进行优化，建议您大批量插入向量，直至达到 `PutVectors` 的最大批量大小。但是，对于需要使用较小批量的工作负载（例如实时传入的向量数据必须立即可供搜索），您可以通过使用更高的并发 `PutVectors` 请求数（不超过每秒允许的最大请求数限制）来实现更高的写入吞吐量。有关 `PutVectors` 的最大批量大小（即每次 `PutVectors` API 调用的向量数限制）的更多信息，请参阅[限制和局限性](s3-vectors-limitations.md)。此外，可以将元数据（例如年份、作者、流派、地点）作为键值对附加到每个向量。默认情况下，附加到向量的所有元数据键都是可筛选的，并且可以在相似性查询中用作筛选条件。只有在创建向量索引期间指定为不可筛选的元数据键才被排除在筛选之外。S3 向量索引支持字符串、数字、布尔值和列表类型的元数据。有关每个向量的总元数据大小限制和每个向量的可筛选元数据大小限制的更多信息，请参阅[限制和局限性](s3-vectors-limitations.md)。如果元数据大小超过这些限制，`PutVectors` API 操作将返回 `400 Bad Request` 错误。

在使用 `PutVectors` API 操作将向量数据添加到向量索引之前，需要将原始数据转换为向量嵌入，向量嵌入是内容的数字表示形式，即浮点数数组。向量嵌入捕获内容的语义，一旦通过 `PutVectors` 操作将它们存储在向量索引中，就可以进行相似性搜索。可以使用不同的方法生成向量嵌入，具体取决于数据类型和使用案例。这些方法包括使用机器学习框架、专门的嵌入库或诸如 Amazon Bedrock 之类的 AWS 服务。例如，如果您使用的是 Amazon Bedrock，则可以使用 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) API 操作和首选的嵌入模型来生成嵌入。

此外，Amazon Bedrock 知识库提供一个完全托管式的端到端 RAG 工作流程，其中 Amazon Bedrock 自动从 S3 数据来源获取数据、将内容转换为文本块、生成嵌入并将其存储在向量索引中。然后，可以查询知识库，并根据从源数据中检索的分块生成响应。

此外，开源 Amazon S3 Vectors Embed CLI 工具提供了一种从命令行生成嵌入和执行语义搜索的简化方法。此开源工具可使用 Amazon Bedrock 基础模型自动生成向量嵌入，并在 S3 向量索引中自动执行语义搜索操作。有关该工具的更多信息，请参阅[使用 `s3vectors-embed-cli` 创建向量嵌入并执行语义搜索](s3-vectors-cli.md)。

**注意**  
将向量数据插入向量索引时，必须以 `float32`（32 位浮点）值提供向量数据。如果将更高精度的值传递给 AWS SDK，S3 Vectors 会在存储这些值之前将它们转换为 32 位浮点，并且 [GetVectors](https://docs.aws.amazon.com/AmazonS3/latest/API/API_S3VectorBuckets_GetVectors.html)、[ListVectors](https://docs.aws.amazon.com/AmazonS3/latest/API/API_S3VectorBuckets_ListVectors.html) 和 [QueryVectors](https://docs.aws.amazon.com/AmazonS3/latest/API/API_S3VectorBuckets_QueryVectors.html) 操作会返回 `float32` 值。不同的 AWS SDK 可能具有不同的默认数值类型，因此，无论使用哪个 SDK，都要确保向量正确地格式化为 `float32` 值。例如，在 Python 中，使用 `numpy.float32` 或显式强制转换值。

## 使用 AWS SDK
<a name="s3-vectors-create-sdk"></a>

------
#### [ 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"}
        }
    ]
)
```

------