指定文本索引的语言

在本页面

本教程介绍了指定与文本索引关联的默认语言以及为包含不同语言文档的集合创建文本索引的方法。

指定文本索引的默认语言

与索引数据相关联的默认语言确定了解析词根(即词干)并忽略停用词的规则。索引数据的默认语言是english

若要指定其他语言,请在创建text索引时使用default_language选项。有关default_language可用的语言,请参见Literals 搜寻语言

以下示例为quotes集合在content字段上创建text索引,并将default_language设置为spanish

db.quotes.createIndex(
   { content : "text" },
   { default_language: "spanish" }
)

为多种语言的集合创建文本索引

在文档中指定索引语言

如果集合包含使用不同语言的文档或嵌入式文档,请在文档或嵌入式文档中包含名为language的字段,并将该文档或嵌入式文档的语言指定为其值。

构建text索引时,MongoDB 将为该文档或嵌入式文档使用指定的语言:

  • 文档中指定的语言将覆盖text索引的默认语言。

  • 嵌入式文档中指定的语言将覆盖附件文档中指定的语言或索引的默认语言。

有关支持的语言列表,请参见Literals 搜寻语言

例如,集合quotes包含多语言文档,根据需要在文档和/或嵌入式文档中包含language字段:

{
   _id: 1,
   language: "portuguese",
   original: "A sorte protege os audazes.",
   translation:
     [
        {
           language: "english",
           quote: "Fortune favors the bold."
        },
        {
           language: "spanish",
           quote: "La suerte protege a los audaces."
        }
    ]
}
{
   _id: 2,
   language: "spanish",
   original: "Nada hay más surrealista que la realidad.",
   translation:
      [
        {
          language: "english",
          quote: "There is nothing more surreal than reality."
        },
        {
          language: "french",
          quote: "Il n'y a rien de plus surréaliste que la réalité."
        }
      ]
}
{
   _id: 3,
   original: "is this a dagger which I see before me.",
   translation:
   {
      language: "spanish",
      quote: "Es este un puñal que veo delante de mí."
   }
}

如果您使用默认语言英语在quote字段上创建text索引。

db.quotes.createIndex( { original: "text", "translation.quote": "text" } )

然后,对于包含language字段的文档和嵌入文档,text索引使用该语言来解析词干和其他语言 Feature。

对于不包含language字段的嵌入式文档,

  • 如果随附的文档包含language字段,则索引将针对嵌入式文档使用文档的语言。

  • 否则,索引将为嵌入文档使用默认语言。

对于不包含language字段的文档,索引使用默认语言,即英语。

使用任何字段指定文档的语言

要使用名称不是language的字段,请在创建索引时包含language_override选项。

例如,给出以下命令以使用idioma而不是language作为字段名:

db.quotes.createIndex( { quote : "text" },
                       { language_override: "idioma" } )

quotes集合的文档可以在idioma字段中指定一种语言:

{ _id: 1, idioma: "portuguese", quote: "A sorte protege os audazes" }
{ _id: 2, idioma: "spanish", quote: "Nada hay más surrealista que la realidad." }
{ _id: 3, idioma: "english", quote: "is this a dagger which I see before me" }