Docs 菜单

Atlas Search 索引

在本指南中,您可以了解如何使用 PHP 库以编程方式管理 Atlas Search 和 Atlas Vector Search 索引。

Atlas Search功能使您能够对MongoDB Atlas上托管的集合执行全文搜索。要学习;了解有关Atlas Search 的更多信息,请参阅Atlas Search概述。

Atlas Vector Search 使您能够对存储在 MongoDB Atlas 中的向量嵌入执行语义搜索。要了解有关 Atlas Vector Search 的更多信息,请参阅 Atlas Vector Search 概述。

您可以在 MongoDB\Collection 实例上使用以下方法来管理 Atlas Search 和 Vector Search 索引:

  • MongoDB\Collection::createSearchIndex()

  • MongoDB\Collection::createSearchIndexes()

  • MongoDB\Collection::listSearchIndexes()

  • MongoDB\Collection::updateSearchIndex()

  • MongoDB\Collection::dropSearchIndex()

注意

Atlas Search 和 Vector Search 索引管理是异步进行的

MongoDB PHP 库异步管理 Atlas Search 和 Vector Search 搜索索引。以下各节描述的库方法会立即返回服务器响应,但对搜索索引的更改在后台进行,可能需要一段时间才能完成。

以下各节将提供代码示例,演示如何使用上述每种方法。

您可以使用 createSearchIndex() 方法在集合上创建单个 Atlas Search 或 Vector Search 索引,也可以使用 createSearchIndexes() 方法同时创建多个索引。

以下代码示例展示了如何创建单个 Atlas Search 索引:

$searchIndexName = $collection->createSearchIndex(
['mappings' => ['dynamic' => true]],
['name' => 'mySearchIdx']
);

以下代码示例展示了如何创建单个 Atlas Vector Search 索引:

$vectorSearchIndexName = $collection->createSearchIndex(
[
'fields' => [[
'type' => 'vector',
'path' => 'plot_embedding',
'numDimensions' => 1536,
'similarity' => 'dotProduct'
]]
],
['name' => 'myVSidx', 'type' => 'vectorSearch']
);

以下代码示例展示了如何在一次调用中创建 Atlas Search 和 Vector Search 索引:

$indexNames = $collection->createSearchIndexes(
[
[
'name' => 'SearchIdx',
'definition' => ['mappings' => ['dynamic' => true]],
],
[
'name' => 'VSidx',
'type' => 'vectorSearch',
'definition' => [
'fields' => [[
'type' => 'vector',
'path' => 'plot_embedding',
'numDimensions' => 1536,
'similarity' => 'dotProduct'
]]
],
],
]
);

创建 Atlas Search 或 Atlas Vector Search 索引后,您可以对文档执行相应的查询类型。要了解更多信息,请参阅以下指南:

您可以使用 listSearchIndexes() 方法返回集合上的 Atlas Search 和 Vector Search 索引数组:

foreach ($collection->listSearchIndexes() as $indexInfo) {
echo json_encode($indexInfo), PHP_EOL;
}

您可以使用 updateSearchIndex() 方法更新Atlas Search或 Vector Search索引。您可以使用此方法更改现有索引的名称或配置。

以下代码展示了如何更新搜索索引,以对 title 字段使用简单分析器:

$collection->updateSearchIndex(
'mySearchIdx',
['mappings' => [
'dynamic' => false,
'fields' => [
'title' => [
'type' => 'string',
'analyzer' => 'lucene.simple'
]
]
]]
);

您可以使用 dropSearchIndex() 方法从集合中删除 Atlas Search 或 Vector Search 索引。

以下代码显示如何删除名为 mySearchIdx 的 Atlas Search 索引:

$collection->dropSearchIndex('mySearchIdx');

要查看演示如何管理索引的可运行示例,请参阅使用索引优化查询。

要查看如何使用 Atlas Search 功能的教程,请参阅 Atlas 文档中的 Atlas Search 入门

要进一步了解本指南所讨论的任何方法,请参阅以下 API 文档: