Docs 菜单
Docs 主页
/ /

MongoDB搜索索引

MongoDB Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. MongoDB Search indexes specify the behavior of the search and which fields to index.

You can call the following methods on a collection to manage your MongoDB Search indexes:

  • createSearchIndex()

  • createSearchIndexes()

  • listSearchIndexes()

  • updateSearchIndex()

  • dropSearchIndex()

注意

The MongoDB Search index management methods run asynchronously and might return before confirming that they ran successfully. To determine the current status of the indexes, call the listSearchIndexes() method.

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

You can use the createSearchIndex() and the createSearchIndexes() methods to create one or more MongoDB Search indexes.

You can also use these methods to create MongoDB Vector Search Indexes. MongoDB Vector Search enables you to perform semantic searches on vector embeddings stored in MongoDB Atlas. To learn more about this feature, see the MongoDB Vector Search Overview.

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

val index = Document("mappings" -> Document("dynamic" -> true))
collection.createSearchIndex("<index name>", index)
.subscribe((result: String) => ())

以下代码示例展示了如何创建多个索引。与可为创建的索引分配默认名称的 createSearchIndex() 方法不同,使用 createSearchIndexes() 方法时,您必须为每个索引提供名称。

val indexOne = SearchIndexModel("<first index name>", Document("mappings" -> Document("dynamic" -> true, "fields" -> Document("field1" -> Document("type" -> "string")))))
val indexTwo = SearchIndexModel("<second index name>", Document("mappings" -> Document("dynamic" -> false, "fields" -> Document("field2" -> Document("type" -> "string")))))
collection.createSearchIndexes(List(indexOne, indexTwo))
.subscribe((result: String) => ())

To learn more about the syntax used to define MongoDB Search indexes, see the Review MongoDB Search Index Syntax guide in the Atlas manual.

You can use the listSearchIndexes() method to return all MongoDB Search indexes in a collection.

以下代码示例演示如何通过订阅 listSearchIndexes() 方法返回的 Observable 来打印集合中的搜索索引列表:

collection.listSearchIndexes()
.subscribe((result: Document) => println(result.toJson()))
{"id": "...", "name": "<index name 1>", "type": "search", "status": "READY", "queryable": true, ... }
{"id": "...", "name": "<index name 2>", "type": "search", "status": "READY", "queryable": true, ... }

You can use the updateSearchIndex() method to update a MongoDB Search index.

以下代码展示如何更新搜索索引:

val updateIndex = Document("mappings" -> Document("dynamic" -> false))
collection.updateSearchIndex("<index to update>", updateIndex)
.subscribe((result: Unit) => ())

You can use the dropSearchIndex() method to delete a MongoDB Search index.

以下代码展示了如何从集合中删除搜索索引:

collection.dropSearchIndex("<index name>")
.subscribe((result: Unit) => ())

要学习;了解有关MongoDB Search 的更多信息,请参阅MongoDB Search 文档。

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档:

后退

Multikey

在此页面上