Docs Menu
Docs Home
/
MongoDBマニュアル
/ / /

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

項目一覧

  • このタスクについて
  • 始める前に
  • 手順
  • 単一フィールドのテキストインデックスの作成
  • 複合テキストインデックスの作成

注意

このページでは、自己管理型(Atlas以外)デプロイメントのテキスト クエリ機能について説明します。 MongoDB Atlasでホストされているデータに対して、 MongoDB は改良された全文クエリ ソリューションである Atlas Search とベクトル検索ソリューションである Atlas ベクトル検索 を提供します。

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

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

db.<collection>.createIndex(
{
<field1>: "text",
<field2>: "text",
...
}
)

次のドキュメントを使用して 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フィールドのテキスト検索クエリをサポートしています。 たとえば、次のクエリは、 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フィールドはテキストインデックスに含まれていないため、テキスト検索クエリ結果には影響しません。

注意

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

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

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

aboutインデックスは、keywords フィールドと フィールドに対するテキスト検索クエリをサポートしています。たとえば、次のクエリは、food フィールドまたはabout keywordsフィールドのいずれかに string が出現するドキュメントを返します。

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