

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用向量搜索集合
<a name="serverless-vector-search"></a>

使用 OpenSearch Serverless 中的*矢量搜索*集合类型，您可以执行可扩展、高性能的相似度搜索。无需管理底层矢量数据库基础架构，即可构建现代机器学习 (ML) 增强搜索体验和生成式人工智能 (AI) 应用程序。

向量搜索集合的用例包括图像搜索、文档搜索、音乐检索、产品推荐、视频搜索、基于位置的搜索、欺诈检测和异常检测。

 OpenSearch Serverless 的矢量引擎在中使用 [k 最近邻 (k-nn) 搜索功能](https://opensearch.org/docs/latest/search-plugins/knn/index/)。 OpenSearch您可以通过无服务器环境的简单性获得相同的功能。该引擎支持 [k-nn 插件 API。](https://opensearch.org/docs/latest/search-plugins/knn/api/)通过这些操作，您可以使用全文搜索、高级筛选、聚合、地理空间查询和嵌套查询来加快数据检索速度并增强搜索结果。

向量引擎提供距离指标，例如欧几里得距离、余弦相似度和点积相似度，并且可以容纳 16,000 个维度。您可以存储具有各种元数据数据类型的字段，例如数字、布尔值、日期、关键字和地理点。您还可以存储带有描述性信息的文本字段，以便为存储的向量添加更多上下文。将数据类型放在一起可以降低复杂性、提高可维护性，并避免数据重复、版本兼容性挑战和许可问题。

## NextGen 矢量搜索集合
<a name="serverless-vector-nextgen-features"></a>

NextGen 矢量搜索可根据工作负载按需扩展，以优化成本和性能之间的平衡。只有为活动搜索请求提供服务所需的数据块才会加载到内存中，工作人员会根据所需的内存和 CPU 资源进行动态扩展。当馆藏处于空闲状态且没有持续请求时，索引和搜索都将缩放为零，从而节省额外的成本。默认情况下， NextGen包括内置优化，可提高召回率，同时降低成本和延迟。
+ **自定义文档 ID** — NextGen 馆藏中支持自定义文档 ID，使客户可以更轻松地使用用户提供的 ID 执行更新或索引文档。
+ **32 倍压缩索引** — 默认情况下，所有索引均使用高级 32 倍压缩技术创建。您可以覆盖默认压缩级别并选择任何支持的压缩级别：1x、2x、8x、16x 或 32x（默认）。
+ **索引构建加速**-默认情况下启用 GPU 加速，以帮助更快、更高效地构建大规模矢量索引。它减少了将数据索引到向量索引所需的时间，从而提供了高吞吐量的索引体验并节省了成本。只有在索引构建操作期间需要时才会配置 GPU 资源。您可以使用该设置按索引控制 GPU 的使用情况`index.knn.remote_index_build.enabled`。有关更多信息，请参阅 [用于向量索引的 GPU 加速](gpu-acceleration-vector-index.md)。
+ **简化的 API**- NextGen 矢量搜索集合不需要索引映射中的`engine`和`mode`参数。系统会在内部自动确定最佳配置，从而降低索引创建的复杂性。
+ **优化的搜索响应**-默认情况下， NextGen 矢量集合中的搜索响应会从结果中排除原始向量。这减少了端到端的搜索延迟和响应有效载荷的大小。要在搜索响应中包含向量，请参阅[使用矢量检索完整文档](#serverless-vector-index-full-source)。
+ NextGen 矢量集合的先写后读延迟 (`refresh_interval`) 为 10 秒。

## 开始使用向量搜索集合
<a name="serverless-vector-tutorial"></a>

在本教程中，您将完成以下步骤来实时存储、搜索和检索向量嵌入：

1. [配置权限](#serverless-vector-permissions)

1. [创建集合](#serverless-vector-create)

1. [上传和搜索数据](#serverless-vector-index)

1. [删除集合](#serverless-vector-delete)

### 步骤 1：配置权限
<a name="serverless-vector-permissions"></a>

要完成本教程（以及一般使用 OpenSearch 无服务器），您必须拥有正确的 AWS Identity and Access Management (IAM) 权限。在本教程中，您将创建一个集合、上传和搜索数据，然后删除该集合。

您的用户或角色必须已经附加[基于身份的策略](security-iam-serverless.md#security-iam-serverless-id-based-policies)，并且具有以下最低权限：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "aoss:CreateCollection",
        "aoss:ListCollections",
        "aoss:BatchGetCollection",
        "aoss:DeleteCollection",
        "aoss:CreateAccessPolicy",
        "aoss:ListAccessPolicies",
        "aoss:UpdateAccessPolicy",
        "aoss:CreateSecurityPolicy",
        "iam:ListUsers",
        "iam:ListRoles"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}
```

------

有关 OpenSearch 无服务器 IAM 权限的更多信息，请参阅[适用于 Amazon OpenSearch Serverless 的身份和访问管理](security-iam-serverless.md)。

### 步骤 2：创建集合
<a name="serverless-vector-create"></a>

要创建新集合，请遵循统一的集合创建流程（NextGen Express Create），该流程会自动配置加密、网络和数据访问策略。有关说明，请参阅[创建 NextGen 收藏夹（快速创建）](serverless-create.md#serverless-create-nextgen-easy)。

在本教程的其余部分中，示例集合被命名为`housing` NextGen 矢量搜索集合。

**注意**  
如果您选择创建 Classic 矢量集合，请参阅，了解特定[使用经典矢量集合](#serverless-vector-classic)于 Classic 集合的步骤。

### 步骤 3：上传并搜索数据
<a name="serverless-vector-index"></a>

*索引*是具有通用数据架构的文档集合，它为您提供了一种存储、搜索和检索向量嵌入和其他字段的方法。[您可以使用 OpenSearch 仪表板中的[开发工具控制台或 Po [stm](https://www.postman.com/downloads/) an 或 awscurl 等 HTTP 工具](https://opensearch.org/docs/latest/dashboards/dev-tools/index-dev/)，创建数据并将其上传到 OpenSearch 无服务器集合中的索引。](https://github.com/okigan/awscurl)本教程使用的是 Dev Tools。有关使用 Python 软件开发工具包进行编程访问的信息，请参阅[将数据提取到 Ama OpenSearch zon 无服务器集合中](serverless-clients.md)。

**索引和搜索住房馆藏中的数据**

1. 要为您的新集合创建索引，请在[开发工具](https://opensearch.org/docs/latest/dashboards/dev-tools/index-dev/)控制台中发送以下请求。默认情况下，这将创建具有欧几里得距离和 32 倍压缩的索引。

   ```
   PUT housing-index
   {
     "settings": {
       "index.knn": true
     },
     "mappings": {
       "properties": {
         "housing-vector": {
           "type": "knn_vector",
           "dimension": 3,
           "space_type": "l2"
         },
         "title": {
           "type": "text"
         },
         "price": {
           "type": "long"
         },
         "location": {
           "type": "geo_point"
         }
       }
     }
   }
   ```

1. 要使用不同的压缩级别，请在字段映射`compression_level`中进行设置。以下示例创建了一个`compression_level`设置为 1x 的索引。

   ```
   PUT housing-index-1x
   {
     "settings": {
       "index.knn": true
     },
     "mappings": {
       "properties": {
         "housing-vector": {
           "type": "knn_vector",
           "dimension": 3,
           "compression_level": "1x",
           "space_type": "l2"
         },
         "title": {
           "type": "text"
         },
         "price": {
           "type": "long"
         },
         "location": {
           "type": "geo_point"
         }
       }
     }
   }
   ```

   支持的压缩级别为 1 倍、2 倍、8 倍、16 倍和 32 倍。

1. 要将文档编入索引`housing-index`，您可以使用系统生成的 ID (POST) 或用户提供的 ID (PUT)。

   ```
   # System-generated document ID
   POST housing-index/_doc
   {
     "housing-vector": [10, 20, 30],
     "title": "2 bedroom in downtown Seattle",
     "price": "2800",
     "location": "47.71, 122.00"
   }
   
   # User-provided document ID
   PUT housing-index/_doc/100
   {
     "housing-vector": [10, 20, 30],
     "title": "2 bedroom in downtown Seattle",
     "price": "2800",
     "location": "47.71, 122.00"
   }
   ```

1. 要搜索与索引中的属性相似的属性，请发送以下查询。默认情况下，搜索响应会从中排除原始向量，`_source`以减少延迟和有效载荷大小。

   ```
   GET housing-index/_search
   {
     "size": 5,
     "query": {
       "knn": {
         "housing-vector": {
           "vector": [10, 20, 30],
           "k": 2
         }
       }
     }
   }
   ```

   响应将该`housing-vector`字段排除在外`_source`：

   ```
   {
     "took": 10,
     "timed_out": false,
     "_shards": {
       "total": 0,
       "successful": 0,
       "skipped": 0,
       "failed": 0
     },
     "hits": {
       "total": {
         "value": 1,
         "relation": "eq"
       },
       "max_score": 1,
       "hits": [
         {
           "_index": "housing-index",
           "_id": "100",
           "_score": 1,
           "_source": {
             "price": "2800",
             "location": "47.71, 122.00",
             "title": "2 bedroom in downtown Seattle"
           }
         }
       ]
     }
   }
   ```

#### 使用矢量检索完整文档
<a name="serverless-vector-index-full-source"></a>

要覆盖默认行为，请在搜索请求`true`中`_source`将其设置为。您也可以使用的`includes`/`excludes`选项`_source`来检索特定字段。

```
GET housing-index/_search
{
  "size": 5,
  "_source": true,
  "query": {
    "knn": {
      "housing-vector": {
        "vector": [10, 20, 30],
        "k": 2
      }
    }
  }
}
```

现在，响应中包含以下`housing-vector`字段`_source`：

```
{
  "took": 10,
  "timed_out": false,
  "_shards": {
    "total": 0,
    "successful": 0,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "housing-index",
        "_id": "100",
        "_score": 1,
        "_source": {
          "housing-vector": [10, 20, 30],
          "price": "2800",
          "location": "47.71, 122.00",
          "title": "2 bedroom in downtown Seattle"
        }
      }
    ]
  }
}
```

### 步骤 4：删除集合
<a name="serverless-vector-delete"></a>

由于*房屋*收藏仅用于测试目的，因此请在完成实验后将其删除。

**删除 OpenSearch 无服务器集合**

1. 打开亚马逊 OpenSearch 服务控制台。

1. 在左侧导航窗格中，选择**收藏**，然后选择**房屋**收藏。

1. 选择**删除**，然后确认删除。

## 经过筛选的搜索
<a name="serverless-vector-filter"></a>

您可以使用筛选条件来优化语义搜索结果。要创建索引并对文档执行经过筛选的搜索，请使用以下说明替换上一个教程中的[上传和搜索数据](#serverless-vector-index)。其他步骤保持不变。有关筛选条件的更多信息，请参阅[使用筛选条件进行 k-NN 搜索](https://opensearch.org/docs/latest/search-plugins/knn/filter-search-knn/)。

**索引和搜索住房馆藏中的数据**

1. 要为您的集合创建单个索引，请在 [Dev Tools](https://opensearch.org/docs/latest/dashboards/dev-tools/index-dev/) 控制台中发送以下请求：

   ```
   PUT housing-index-filtered
   {
     "settings": {
       "index.knn": true
     },
     "mappings": {
       "properties": {
         "housing-vector": {
           "type": "knn_vector",
           "dimension": 3,
           "space_type": "l2",
           "method": {
             "name": "hnsw"
           }
         },
         "title": {
           "type": "text"
         },
         "price": {
           "type": "long"
         },
         "location": {
           "type": "geo_point"
         }
       }
     }
   }
   ```

1. 要将单个文档索引到 *housing-index-filtered* 中，请发送以下请求：

   ```
   POST housing-index-filtered/_doc
   {
     "housing-vector": [
       10,
       20,
       30
     ],
     "title": "2 bedroom in downtown Seattle",
     "price": "2800",
     "location": "47.71, 122.00"
   }
   ```

1. 要搜索西雅图给定价格和给定距离范围内的公寓数据，请发送以下请求：

   ```
   GET housing-index-filtered/_search
   {
     "size": 5,
     "query": {
       "knn": {
         "housing-vector": {
           "vector": [
             0.1,
             0.2,
             0.3
           ],
           "k": 5,
           "filter": {
             "bool": {
               "must": [
                 {
                   "query_string": {
                     "query": "Find me 2 bedroom apartment in Seattle under $3000 ",
                     "fields": [
                       "title"
                     ]
                   }
                 },
                 {
                   "range": {
                     "price": {
                       "lte": 3000
                     }
                   }
                 },
                 {
                   "geo_distance": {
                     "distance": "100miles",
                     "location": {
                       "lat": 48,
                       "lon": 121
                     }
                   }
                 }
               ]
             }
           }
         }
       }
     }
   }
   ```

## 限制
<a name="serverless-vector-limitations"></a>
+ 使用 32 倍压缩的 NextGen 矢量索引不支持径向搜索。

## 使用经典矢量集合
<a name="serverless-vector-classic"></a>

经典矢量集合是 OpenSearch 无服务器矢量搜索的原始一代。如果您已有 Classic 矢量集合，请使用本节中的步骤。对于新集合，我们建议 NextGen — 请参见[创建集合](serverless-create.md)创建 NextGen矢量集合。

**注意**  
Amazon OpenSearch Serverless Classic 集合支持 Faiss 16 位标量量化，可在 32 位浮动向量和 16 位向量之间进行转换。如需了解更多信息，请参阅 [Faiss 16 位标量量化](https://opensearch.org/docs/latest/search-plugins/knn/knn-vector-quantization/#faiss-16-bit-scalar-quantization)。您还可以使用二进制向量降低内存成本。有关更多信息，请参阅[二进制向量](https://opensearch.org/docs/latest/field-types/supported-field-types/knn-vector#binary-vectors)。
Amazon OpenSearch Serverless Classic 集合支持基于磁盘的矢量搜索，这可以显著降低低内存环境中矢量工作负载的运营成本。有关更多信息，请参阅[Disk-based 矢量搜索](https://docs.opensearch.org/2.19/vector-search/optimizing-storage/disk-based-vector-search/)。

### 上传和搜索数据（经典）
<a name="serverless-vector-classic-index"></a>

以下示例适用于经典矢量集合，这些集合默认使用`nmslib`引擎，并在搜索响应中包含原始向量。

**对经典房屋集合中的数据进行索引和搜索**

1. 要为您的 Classic 集合创建索引，请在[开发工具](https://opensearch.org/docs/latest/dashboards/dev-tools/index-dev/)控制台中发送以下请求。默认情况下，这将使用引`nmslib`擎和欧几里得距离创建索引。

   ```
   PUT housing-index
   {
      "settings": {
         "index.knn": true
      },
      "mappings": {
         "properties": {
            "housing-vector": {
               "type": "knn_vector",
               "dimension": 3
            },
            "title": {
               "type": "text"
            },
            "price": {
               "type": "long"
            },
            "location": {
               "type": "geo_point"
            }
         }
      }
   }
   ```

1. 要将单个文档索引到 *housing-index* 中，请发送以下请求：

   ```
   POST housing-index/_doc
   {
     "housing-vector": [
       10,
       20,
       30
     ],
     "title": "2 bedroom in downtown Seattle",
     "price": "2800",
     "location": "47.71, 122.00"
   }
   ```

1. 要搜索与索引中的属性相似的属性，请发送以下查询：

   ```
   GET housing-index/_search
   {
       "size": 5,
       "query": {
           "knn": {
               "housing-vector": {
                   "vector": [
                       10,
                       20,
                       30
                   ],
                   "k": 5
               }
           }
       }
   }
   ```

### 筛选搜索（经典）
<a name="serverless-vector-classic-filter"></a>

要创建索引并执行筛选搜索，请使用以下示例。有关筛选条件的更多信息，请参阅[使用筛选条件进行 k-NN 搜索](https://opensearch.org/docs/latest/search-plugins/knn/filter-search-knn/)。

**对经典房屋收藏进行索引和筛选搜索**

1. 要为您的集合创建单个索引，请在 [Dev Tools](https://opensearch.org/docs/latest/dashboards/dev-tools/index-dev/) 控制台中发送以下请求：

   ```
   PUT housing-index-filtered
   {
     "settings": {
       "index.knn": true
     },
     "mappings": {
       "properties": {
         "housing-vector": {
           "type": "knn_vector",
           "dimension": 3,
           "method": {
             "engine": "faiss",
             "name": "hnsw"
           }
         },
         "title": {
           "type": "text"
         },
         "price": {
           "type": "long"
         },
         "location": {
           "type": "geo_point"
         }
       }
     }
   }
   ```

1. 要将单个文档索引到 *housing-index-filtered* 中，请发送以下请求：

   ```
   POST housing-index-filtered/_doc
   {
     "housing-vector": [
       10,
       20,
       30
     ],
     "title": "2 bedroom in downtown Seattle",
     "price": "2800",
     "location": "47.71, 122.00"
   }
   ```

1. 要搜索西雅图给定价格和给定距离范围内的公寓数据，请发送以下请求：

   ```
   GET housing-index-filtered/_search
   {
     "size": 5,
     "query": {
       "knn": {
         "housing-vector": {
           "vector": [
             0.1,
             0.2,
             0.3
           ],
           "k": 5,
           "filter": {
             "bool": {
               "must": [
                 {
                   "query_string": {
                     "query": "Find me 2 bedroom apartment in Seattle under $3000 ",
                     "fields": [
                       "title"
                     ]
                   }
                 },
                 {
                   "range": {
                     "price": {
                       "lte": 3000
                     }
                   }
                 },
                 {
                   "geo_distance": {
                     "distance": "100miles",
                     "location": {
                       "lat": 48,
                       "lon": 121
                     }
                   }
                 }
               ]
             }
           }
         }
       }
     }
   }
   ```

### 限制（经典）
<a name="serverless-vector-classic-limitations"></a>

经典矢量集合有以下限制：
+ 向量搜索集合不支持 Apache Lucene ANN 引擎。
+ 矢量搜索集合仅支持 Faiss 的 HNSW 算法。他们不支持试管婴儿或IVFQ。
+ 向量搜索集合不支持预热、统计数据和模型训练 API 操作。
+ 向量搜索集合不支持内联脚本或存储脚本。
+ 矢量搜索集合中 AWS 管理控制台 没有索引计数信息。
+ 向量搜索集合上索引的刷新间隔为 60 秒。

### Billion-scale 工作负载
<a name="serverless-vector-billion"></a>

经典矢量搜索集合支持包含数十亿个向量的工作负载。您无需出于扩展目的重新编制索引，因为 auto scaling 会为您执行此操作。如果您有数百万个（或更多）具有大量维度的向量，并且需要超过 200 个 OCU，请联系 Su [AWS pp](https://aws.amazon.com/premiumsupport/) ort 以提高您账户的最大 OpenSearch 计算单位 (OCU)。

## 后续步骤
<a name="serverless-vector-next"></a>

现在您已经知道如何创建矢量搜索集合和索引数据，可以尝试以下练习：
+ 使用 OpenSearch Python 客户端处理矢量搜索集合。请参阅本教程[GitHub](https://github.com/opensearch-project/opensearch-py/blob/main/guides/plugins/knn.md)。
+ 使用 OpenSearch Java 客户端处理矢量搜索集合。请参阅本教程[GitHub](https://github.com/opensearch-project/opensearch-java/blob/main/guides/plugins/knn.md)。
+ 设置 LangChain 为 OpenSearch 用作矢量存储。 LangChain 是一个开源框架，用于开发由语言模型支持的应用程序。有关详情，请参阅 [LangChain 文档](https://python.langchain.com/docs/integrations/vectorstores/opensearch)。