gpt4 book ai didi

MongoDB - 文本字段索引和文本索引之间的区别?

转载 作者:IT老高 更新时间:2023-10-28 13:05:00 27 4
gpt4 key购买 nike

对于包含字符串(例如,州或省名称)的 MongoDB 字段,在字符串类型字段上创建索引之间有什么(如果有)区别:

db.ensureIndex( { field: 1 } )

并在该字段上创建文本索引:

db.ensureIndex( { field: "text" }

在这两种情况下,field 都是 string 类型。

我正在寻找一种方法来对包含单个单词(可能更多)的文本字段进行不区分大小写的搜索。作为 Mongo 的新手,我无法区分使用上述两种索引方法,甚至是 $regex 搜索之类的方法。

最佳答案

这两个索引选项非常不同。

  • 当您在字符串字段上创建常规索引时,它会索引字符串中的整个值。对单个单词字符串最有用(如登录用户名)您可以完全匹配的位置。

  • 另一方面,文本索引将标记和阻止场。所以它会将字符串分解为单个单词或标记,并将进一步将它们简化为它们的词干,以便变体相同单词的匹配(“talk”匹配“talks”、“talked”和例如“talking”,因为“talk”是所有三个词的词干)。大多对于真正的文本(句子、段落等)很有用。

    Text Search

    Text search supports the search of string content in documents of a collection. MongoDB provides the $text operator to perform text search in queries and in aggregation pipelines.

    The text search process:

    tokenizes and stems the search term(s) during both the index creation and the text command execution.
    assigns a score to each document that contains the search term in the indexed fields. The score determines the relevance of a document to a given search query.

    The $text operator can search for words and phrases. The query matches on the complete stemmed words. For example, if a document field contains the word blueberry, a search on the term blue will not match the document. However, a search on either blueberry or blueberries will match.

  • $regex 搜索可以与字符串字段的常规索引一起使用,以提供一些模式匹配和通配符搜索。不是很糟糕索引的有效用户,但它会尽可能使用索引:

    If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.

http://docs.mongodb.org/manual/core/index-text/

http://docs.mongodb.org/manual/reference/operator/query/regex/

关于MongoDB - 文本字段索引和文本索引之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24316117/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com