Docs Menu
Docs Home
/ /

自己管理型配置でのテキストインデックスの作成

注意

MongoDBは、改良された全文検索ソリューションであるMongoDB Search、およびベクトル検索ソリューションであるMongoDB Vector Searchを提供します。テキスト インデックスの代わりに、MongoDB Search インデックス または MongoDB Vector Search インデックス を使用することをお勧めします。

テキストインデックスは、string コンテンツを含むフィールドでの $text クエリをサポートします。インデックスを使用すると、string コンテンツ内の特定の単語または複数単語の string を検索するときのパフォーマンスが向上します。

テキストインデックスを作成するには、db.collection.createIndex() メソッドを使用します。string または複数の string 配列を含むフィールドをインデックスには、インデックスキーとして string "text" を指定します。

db.<collection>.createIndex(
{
<field1>: "text",
<field2>: "text",
...
}
)
  • コレクションには最大 1 つのテキスト インデックスを含めることができます。

    MongoDB Search (MongoDBで利用可能)は、単一のコレクションに対して複数の全文検索インデックスをサポートします。詳しくは、MongoDB Search のドキュメントを参照してください。

  • 1 つのテキストインデックスで複数のフィールドにインデックスを付けることができます。 テキスト インデックスには最大32フィールドを含めることができます。 例については、「複合テキスト インデックスの作成 」を参照してください。

次のドキュメントを使用して blog コレクションを作成します。

db.blog.insertMany( [
{
_id: 1,
content: "This morning I had a cup of coffee.",
about: "beverage",
keywords: [ "coffee" ]
},
{
_id: 2,
content: "Who likes chocolate ice cream for dessert?",
about: "food",
keywords: [ "poll" ]
},
{
_id: 3,
content: "My favorite flavors are strawberry and coffee",
about: "ice cream",
keywords: [ "food", "dessert" ]
}
] )

次の例は、次の方法を示しています。

contentフィールドに テキスト インデックス を作成します。

db.blog.createIndex( { "content": "text" } )

インデックスは、contentフィールドに対する $text クエリをサポートしています。例、次のクエリは、contentフィールドに string coffee が含まれるドキュメントを返します。

db.blog.find(
{
$text: { $search: "coffee" }
}
)

出力:

[
{
_id: 1,
content: 'This morning I had a cup of coffee.',
about: 'beverage',
keywords: [ 'coffee' ]
},
{
_id: 3,
content: 'My favorite flavors are strawberry and coffee',
about: 'ice cream',
keywords: [ 'food', 'dessert' ]
}
]

{ "content": "text" }インデックスにはcontentフィールドのみが含まれ、インデックスがないフィールドとの一致は返されません。 たとえば、次のクエリは、 blogコレクションで string foodを検索します。

db.blog.find(
{
$text: { $search: "food" }
}
)

上記のクエリではドキュメントは返されません。string food はドキュメント _id: 2_id: 3 に表示されますが、それぞれ about フィールドと keywords フィールドに表示されます。about フィールドと keywords フィールドは テキストインデックスに含まれていないため、$text クエリ結果には影響しません。

注意

この例のインデックスを作成する前に、 blogコレクションの既存のテキスト インデックスをすべて削除する必要があります。

コレクションの フィールドと フィールドに複合テキスト インデックスを作成します。aboutkeywordsblog

db.blog.createIndex(
{
"about": "text",
"keywords": "text"
}
)

インデックスは、about フィールドと keywords フィールドに対する $text クエリをサポートしています。例、次のクエリは、aboutまたはkeywordsのいずれかのフィールドに文字列 food が表示されるドキュメントを返します。

db.blog.find(
{
$text: { $search: "food" }
}
)

出力:

[
{
_id: 3,
content: 'My favorite flavors are strawberry and coffee',
about: 'ice cream',
keywords: [ 'food', 'dessert' ]
},
{
_id: 2,
content: 'Who likes chocolate ice cream for dessert?',
about: 'food',
keywords: [ 'poll' ]
}
]

戻る

Text Indexes

項目一覧