“文档” 菜单
文档首页
/
MongoDB Manual
/ /

指定文本索引的语言

在此页面上

  • 指定text索引的默认语言
  • 为多种语言的集合创建text索引

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

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

要指定不同的语言,请在创建text索引时使用default_language选项。请参阅文本搜索语言,了解default_language的可用语言。

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

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

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

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

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

  • 嵌入式文档中的指定语言会覆盖包含文档中指定的语言或索引的默认语言。

有关支持的语言列表,请参阅文本Atlas Search语言。

例如,集合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索引使用该语言来解析词干和其他语言特征。

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

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

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

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

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

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

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

quotes collection的文档可以使用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" }
← 文本索引