Transformers(7) - トークナイザー

今回は、トークナイザーを使ってみます。

(Transformersのインストールは完了している想定となります。)

トークナイザー

トークナイザーは自然言語の入力テキストを深層学習モデルの入力データに変換する処理です。

深層学習モデルの入力データはテンソルと呼ばれる多次元配列になります。

トークナイザーの準備

AutoTokenizerクラスの作成時に‘bert-base-cased’を指定すると、BERTモデル用のトークナイザーとなります。

[Google Colaboratory]

1
2
3
4
from transformers import AutoTokenizer

# トークナイザーの準備
tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')

[実行結果]

1
2
3
4
5
6
7
8
Downloading: 100%
570/570 [00:00<00:00, 13.3kB/s]
Downloading: 100%
213k/213k [00:00<00:00, 563kB/s]
Downloading: 100%
436k/436k [00:00<00:00, 587kB/s]
Downloading: 100%
29.0/29.0 [00:00<00:00, 725B/s]

自然言語テキストをテンソルにエンコード

tokenizer.encodeを使うと、自然言語テキストをテンソルにエンコードすることができます。

[Google Colaboratory]

1
2
3
# 自然言語テキストをテンソルにエンコード
input = tokenizer.encode("Hello, I'm a single sentence!", return_tensors='pt', max_length=512, truncation=True)
print(input)

[実行結果]

1
tensor([[ 101, 8667,  117,  146,  112,  182,  170, 1423, 5650,  106,  102]])

テンソルを自然言語テキストにデコード

tokenizer.decodeを使うと、テンソルを自然言語テキストにデコードすることができます。

[Google Colaboratory]

1
2
# テンソルを自然言語テキストにデコード
print(tokenizer.decode(input.numpy()[0]))

[実行結果]

1
[CLS] Hello, I'm a single sentence! [SEP]

複数の自然言語テキストをテンソルにエンコード

tokenizer.encode_plusを使うと、複数の自然言語テキストをテンソルにエンコードすることができます。

[Google Colaboratory]

1
2
3
# 複数の自然言語テキストをテンソルにエンコード
inputs = tokenizer.encode_plus('This is a question', 'This is a context!', return_tensors='pt')
print(inputs)

戻り値の意味は次の通りです。

  • input_ids
    トークンIDの配列
  • token_type_ids
    複数の文章を判定するバイナリマスク
  • attention_mask
    パディング時に埋め込み文字かどうかを判定するバイナリマスク

[実行結果]

1
2
3
{'input_ids': tensor([[ 101, 1188, 1110,  170, 2304,  102, 1188, 1110,  170, 5618,  106,  102]]), 
'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]]),
'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}

テンソルを複数の自然言語テキストにデコード

tokenizer.decodeを使うと、テンソルを複数の自然言語テキストにデコードすることができます。

[Google Colaboratory]

1
2
# テンソルを複数の自然言語テキストにデコード
print(tokenizer.decode(inputs['input_ids'].numpy()[0]))

[実行結果]

1
[CLS] This is a question [SEP] This is a context! [SEP]

BERTのスペシャルトークンとしては、次のようなものがあります。

  • [CLS]
    文頭に埋め込むトークン(classification)
  • [SEP]
    文と文の間に埋め込むトークン(separator)
  • [PAD]
    指定された長さに満たさない文を埋めるトークン(padding)
  • [MASK]
    マスクしたトークン(mask)

Transformers(6) - 言語モデル(マスクした単語の予測)

今回は、言語モデルを試してみます。

(Transformersのインストールは完了している想定となります。)

言語モデル

言語モデルは、テキストの自然な単語の並びを予測する処理です。

Transformersライブラリでは、言語モデルを事前に学習しておりその事前学習済みモデルを使ってチューニングを行います。

言語モデルの学習方法には下記のようなものがあります。

  • MLM(Masked Language Modeling)
  • CLM(Causal Language Modeling)

MLM(マスクした単語の予測)

MLMでは、文章内のマスクした単語の予測を学習する手法です。

サンプルコードは次の通りです。

タスク名に‘fill-mask’を指定し、言語モデル(MLM)のパイプラインを作成します。

文章内の予測したい箇所に{nlp.tokenizer.mask_token}を設定するとその位置の単語を予測することができます。

[Google Colaboratory]

1
2
3
4
5
6
7
from transformers import pipeline

# MLMのパイプラインの準備
nlp = pipeline('fill-mask')

# マスク位置の単語を予測
print(nlp(f'Once upon a time there was a young lady and an old {nlp.tokenizer.mask_token}.'))

単語の予測結果として次の情報が出力されます。

  • sequence
    予測した単語を埋め込んだ文章
  • score
    スコア
  • token_str
    予測した単語

[実行結果]

1
2
3
4
5
[{'sequence': 'Once upon a time there was a young lady and an old gentleman.', 'score': 0.49178990721702576, 'token': 22164, 'token_str': ' gentleman'}, 
{'sequence': 'Once upon a time there was a young lady and an old man.', 'score': 0.2817203998565674, 'token': 313, 'token_str': ' man'},
{'sequence': 'Once upon a time there was a young lady and an old boy.', 'score': 0.08439457416534424, 'token': 2143, 'token_str': ' boy'},
{'sequence': 'Once upon a time there was a young lady and an old lady.', 'score': 0.06599652022123337, 'token': 6429, 'token_str': ' lady'},
{'sequence': 'Once upon a time there was a young lady and an old woman.', 'score': 0.01124062854796648, 'token': 693, 'token_str': ' woman'}]

5つの単語が予測されました。

  • スコア 49 [gentleman]
    「a young lady」に対して「an old gentleman」は自然な予測だと思います。
  • スコア 28 [man]
    「a young lady」に対して「an old man」も自然な予測ではないでしょうか。
  • スコア 8 [boy]
    「an old boy」は単語として不自然な感じがします。
  • スコア 6 [lady]
    「a young lady」に対して「an old lady」も老若の女性ということで自然ですね。
  • スコア 1 [woman]
    「a young lady」に対して「an old woman」も特に問題なさそうです。

この程度の文章であれば、問題なくマスクした単語の予測ができることを確認できました。


次回は、トークナイザーを使ってみます。

Transformers(5) - テキスト生成

今回は、テキスト生成を行います。

(Transformersのインストールは完了している想定となります。)

テキスト生成

テキスト生成は、入力されたテキストに続くもっともらしいテキストを自動生成する処理です。

ソースとしては、まずタスク名に‘text-generation’を指定したパイプラインを作成します。

パイプラインには次の3つを引数として渡し、テキスト生成処理を行います。

  • 第1引数
    入力するテキスト
  • max_length
    生成するテキストの最大語数
  • min_length
    生成するテキストの最小語数

[Google Colaboratory]

1
2
3
4
5
6
7
8
9
10
from transformers import pipeline

# テキスト生成のパイプライン
text_generator = pipeline('text-generation')

# 入力テキスト
text = 'Once upon a time there was an old man and an old woman.'

# テキスト生成
print(text_generator(text, max_length=100, min_length=50))

実行結果は下記の通りです。

[実行結果]

1
2
3
4
Some weights of GPT2Model were not initialized from the model checkpoint at gpt2 and are newly initialized: ['h.0.attn.masked_bias', 'h.1.attn.masked_bias', 'h.2.attn.masked_bias', 'h.3.attn.masked_bias', 'h.4.attn.masked_bias', 'h.5.attn.masked_bias', 'h.6.attn.masked_bias', 'h.7.attn.masked_bias', 'h.8.attn.masked_bias', 'h.9.attn.masked_bias', 'h.10.attn.masked_bias', 'h.11.attn.masked_bias']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
[{'generated_text': 'Once upon a time there was an old man and an old woman. One was a very good maid on whom the women worked while the young men worked in the yard.\n\nThis time in the middle of the night, the young maid ran off the edge of the street, followed by several other girls, and as they approached the old maid came the other to speak to this man. He gave her a call and said he had come for someone. The young maid took the call, and found'}]

生成されたテキストを訳すとだいたい次のような感じです。

Once upon a time there was an old man and an old woman.
昔々、おじいさんとおばあさんがいました。

One was a very good maid on whom the women worked while the young men worked in the yard.
一人は、若い男性が庭で働いている間、女性が働いていたとても良いメイドでした。

This time in the middle of the night, the young maid ran off the edge of the street, followed by several other girls, and as they approached the old maid came the other to speak to this man.
今回は真夜中に、若いメイドが通りの端から逃げ出し、他の何人かの女の子が続き、彼らが近づくと、古いメイドがこの男と話すためにもう一人来ました。

He gave her a call and said he had come for someone. The young maid took the call, and found
彼は彼女に電話をかけ、誰かのために来たと言いました。若いメイドが電話に出て、見つけました。

テキストが生成されるにはされたのですが、なんだか謎が謎をよぶ展開になってます。。。😅

次回は、言語モデルを試してみます。

Transformers(4) - 要約

今回は、Transformersを使って要約を行います。

(Transformersのインストールは完了している想定となります。)

要約

要約は、長い文章(本文)を短い文章に変換する処理です。

ソースとしては、まずタスク名に‘summarization’を指定したパイプラインを作成します。

パイプラインには次の3つを引数として渡し、要約処理を行います。

  • 第1引数
    要約対象の本文を指定します。
  • max_length
    要約の最大語数
  • min_length
    要約の最小語数

[Google Colaboratory]

1
2
3
4
5
6
7
8
9
10
from transformers import pipeline

# 要約のパイプラインの準備
summarizer = pipeline('summarization')

# テキスト
text = 'Huggingface Transformers is a deep learning framework provided by Huggingface that specializes in natural language processing. It supports both TensorFlow and PyTorch. You can use deep learning to solve natural language processing tasks such as text classification, question answering, and summary.'

# 推論
print(summarizer(text, max_length=20, min_length=10))

実行結果は下記の通りです。

[実行結果]

1
[{'summary_text': ' Huggingface Transformers is a deep learning framework that specializes in natural language processing . It'}]

結果は「Transformersは、自然言語処理に特化したディープラーニングのフレームワークです。」と、的確な要約文になっています。

次回は、テキスト生成を行います。

Transformers(3) - 質疑応答

今回は、Transformersを使って質疑応答を行います。

(Transformersのインストールは完了している想定となります。)

質疑応答

質疑応答では、コンテキスト質問からコンテキスト内に含まれる応答を抽出します。

ソースとしては、タスク名に‘question-answering’を指定したパイプラインを作成し、コンテキストと質問を渡して応答を推論します。

[Google Colaboratory]

1
2
3
4
5
6
7
8
9
10
11
12
13
from transformers import pipeline

# 質疑応答のパイプラインの準備
nlp = pipeline('question-answering')

# コンテキスト
context = 'Huggingface Transformers is a deep learning framework provided by Huggingface that specializes in natural language processing. It supports both TensorFlow and PyTorch. You can use deep learning to solve natural language processing tasks such as text classification, question answering, and summary.'

# 質問
question = 'What is a natural language processing task?'

# 推論
print(nlp(question=question, context=context))

実行結果は下記の通りです。

[実行結果]

1
{'score': 0.6564476490020752, 'start': 245, 'end': 297, 'answer': 'text classification, question answering, and summary'}

スコア65で、テキスト分類、質疑応答、要約という結果になりました。

正しい応答になっていると思います。


次回は、要約を行います。

Transformers(2) - インストール/テキスト分類

今回は、Transformersのインストールとテキスト分類を行います。

Transformersのインストール

Transformersのインストールを行うためには次のコマンドを実行します。

実行環境としてはGoogle Colaboratoryを想定しています。

[Google Colaboratory]

1
!pip install transformers[ja]==4.4.2

次のような実行結果が表示されればインストールは成功しています。

[実行結果]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Collecting transformers[ja]==4.4.2
Downloading transformers-4.4.2-py3-none-any.whl (2.0 MB)
|████████████████████████████████| 2.0 MB 13.1 MB/s
Requirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers[ja]==4.4.2) (3.0.12)
Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from transformers[ja]==4.4.2) (21.0)
Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers[ja]==4.4.2) (2019.12.20)
Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from transformers[ja]==4.4.2) (4.8.1)
Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from transformers[ja]==4.4.2) (1.19.5)
Collecting tokenizers<0.11,>=0.10.1
Downloading tokenizers-0.10.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (3.3 MB)
|████████████████████████████████| 3.3 MB 56.6 MB/s
Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers[ja]==4.4.2) (4.62.2)
Collecting sacremoses
Downloading sacremoses-0.0.45-py3-none-any.whl (895 kB)
|████████████████████████████████| 895 kB 55.7 MB/s
Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from transformers[ja]==4.4.2) (2.23.0)
Collecting fugashi>=1.0
Downloading fugashi-1.1.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl (490 kB)
|████████████████████████████████| 490 kB 60.5 MB/s
Collecting ipadic<2.0,>=1.0.0
Downloading ipadic-1.0.0.tar.gz (13.4 MB)
|████████████████████████████████| 13.4 MB 212 kB/s
Collecting unidic>=1.0.2
Downloading unidic-1.0.3.tar.gz (5.1 kB)
Collecting unidic-lite>=1.0.7
Downloading unidic-lite-1.0.8.tar.gz (47.4 MB)
|████████████████████████████████| 47.4 MB 79 kB/s
Requirement already satisfied: wasabi<1.0.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from unidic>=1.0.2->transformers[ja]==4.4.2) (0.8.2)
Requirement already satisfied: plac<2.0.0,>=1.1.3 in /usr/local/lib/python3.7/dist-packages (from unidic>=1.0.2->transformers[ja]==4.4.2) (1.1.3)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->transformers[ja]==4.4.2) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->transformers[ja]==4.4.2) (1.24.3)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->transformers[ja]==4.4.2) (2021.5.30)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->transformers[ja]==4.4.2) (2.10)
Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers[ja]==4.4.2) (3.7.4.3)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers[ja]==4.4.2) (3.5.0)
Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->transformers[ja]==4.4.2) (2.4.7)
Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers[ja]==4.4.2) (1.15.0)
Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers[ja]==4.4.2) (1.0.1)
Requirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers[ja]==4.4.2) (7.1.2)
Building wheels for collected packages: ipadic, unidic, unidic-lite
Building wheel for ipadic (setup.py) ... done
Created wheel for ipadic: filename=ipadic-1.0.0-py3-none-any.whl size=13556723 sha256=868f02ff1674a53b19d8180bdf7a9473a57ab3be9cb1551291fdcb03bfb98bc5
Stored in directory: /root/.cache/pip/wheels/33/8b/99/cf0d27191876637cd3639a560f93aa982d7855ce826c94348b
Building wheel for unidic (setup.py) ... done
Created wheel for unidic: filename=unidic-1.0.3-py3-none-any.whl size=5506 sha256=8977d77c05cd5ec120e9f048171cc7fe4804c6191cb8c3dc209a1eae232c6aa8
Stored in directory: /root/.cache/pip/wheels/23/30/0b/128289fb595ef4117d2976ffdbef5069ef83be813e88caa0a6
Building wheel for unidic-lite (setup.py) ... done
Created wheel for unidic-lite: filename=unidic_lite-1.0.8-py3-none-any.whl size=47658836 sha256=05af03831b7babce0692a95538db2a5616e083838fd8a98d6336cdf8e6f9a009
Stored in directory: /root/.cache/pip/wheels/de/69/b1/112140b599f2b13f609d485a99e357ba68df194d2079c5b1a2
Successfully built ipadic unidic unidic-lite
Installing collected packages: tokenizers, sacremoses, unidic-lite, unidic, transformers, ipadic, fugashi
Successfully installed fugashi-1.1.1 ipadic-1.0.0 sacremoses-0.0.45 tokenizers-0.10.3 transformers-4.4.2 unidic-1.0.3 unidic-lite-1.0.8

テキスト分類

テキスト分類は、テキストを事前に定義されたカテゴリに分類する処理となります。

今回は文章を「ポジティブ」か「ネガティブ」かに分類してみます。

タスク名に‘sentiment-analysis’を指定したパイプラインを作成し、そのパイプラインに任意の文章を渡します。

[Google Colaboratory]

1
2
3
4
5
6
7
8
9
10
from transformers import pipeline

# テキスト分類のパイプラインを準備
nlp = pipeline('sentiment-analysis')

# テキスト
text = 'This movie was very interesting.'

# 推論
print(nlp(text))

[実行結果]

1
2
3
4
5
6
7
8
9
Downloading: 100%
629/629 [00:00<00:00, 10.1kB/s]
Downloading: 100%
268M/268M [00:06<00:00, 45.4MB/s]
Downloading: 100%
232k/232k [00:00<00:00, 266kB/s]
Downloading: 100%
48.0/48.0 [00:00<00:00, 850B/s]
[{'label': 'POSITIVE', 'score': 0.9997621178627014}]

スコア99以上で‘POSITIVE’な文章であると判断できました。


少し文章を変更して再度テキスト分類を行います。

[Google Colaboratory]

1
2
3
4
5
6
7
8
9
10
from transformers import pipeline

# テキスト分類のパイプラインを準備
nlp = pipeline('sentiment-analysis')

# テキスト
text = 'This movie was very silly.'

# 推論
print(nlp(text))

[実行結果]

1
[{'label': 'NEGATIVE', 'score': 0.9983341693878174}]

スコア99以上で‘NEGATIVE’な文章であると判断できました。

次回は、質問応答を行います。

Transformers(1) - 概要

Transformersは、世界中で使われているデファクトスタンダードな自然言語処理の深層学習フレームワークです。

このフレームワークを使うことで、最先端の自然言語処理を体験することができます。

Transformersの概要

Transformersは、PyTorchTensorflowの両方に対応していて、深層学習を使って下記のような自然言語処理を行うことができます。

  • テキスト分類
  • 質疑応答
  • 要約
  • テキスト生成
  • 言語モデル

モデルアーキテクチャ

次のような最先端のモデルアーキテクチャを提供しています。

  • BERT
  • GPT-2
  • T5

事前学習モデル

様々な事前学習モデルが提供されており、最先端の自然言語処理アルゴリズムを容易に試すことができます。

提供されている事前学習モデルは以下のサイトで確認できます。

提供されている事前学習モデル - https://huggingface.co/transformers/pretrained_models.html


またコミュニティで提供されている学習済みモデルもあります。

The All community building the future - https://huggingface.co/models


次回は、Transformersのインストールとテキスト分類を行います。

MongoDB(42) - テキストインデックスの作成/TTLインデックスの作成

テキストインデックスの作成とTTLインデックスの作成を行います。

テキストインデックスの作成

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

テキストインデックスを作成する場合は、“text”を指定します。

[Mongoシェル]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// テキストインデックスを作成
> db.test.createIndex({name:"text"})
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : false,
"ok" : 1
}

// インデックスの確認
> db.test.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "name_text",
"weights" : {
"name" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
]

“name_text”というテキストインデックスを作成することができました。

TTLインデックスの作成

TTLインデックスを作成するためにはexpireAfterSecondsに秒数を指定します。

TTLインデックスに指定できるのは、Date型またはDate型を含む配列のフィールドです。

expireAfterSecondsで指定した秒数が経過したドキュメントを自動で削除することができます。

[Mongoシェル]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Dateフィールドを持つドキュメント作成
> db.ttltest.insert({time : ISODate("2021-06-09T10:20:05Z") } )
WriteResult({ "nInserted" : 1 })

// 作成したドキュメント確認
> db.ttltest.find()
{ "_id" : ObjectId("614bb5956e9eb9350501ee38"), "time" : ISODate("2021-06-09T10:20:05Z") }

// TTLインデックス作成
> db.ttltest.createIndex({time:1}, {expireAfterSeconds:60})
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : false,
"ok" : 1
}

// 作成したTTLインデックスの確認
> db.ttltest.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"time" : 1
},
"name" : "time_1",
"expireAfterSeconds" : 60
}
]

// 60秒後にデータが自動削除されることを確認
> db.ttltest.find()

ttltestコレクションのtimeフィールドに、60秒でドキュメントが削除されるようにTTLインデックスを作成しました。

これでドキュメントが60秒経過後に自動的に削除されるようになります。

MongoDB(41) - インデックスの再構築

インデックスの再構築を行うと、コレクションにあるすべてのインデックスを一旦削除してインデックスを作り直します。

インデックスを再構築する理由は次の通りです。

  • データの追加や削除を行っていくうちに発生するインデックスの無駄を解消する。
  • ディスクの使用量を少なくする。

インデックスの再構築

インデックスの再構築にはreIndex()を使用します。

[Mongoシェル]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> db.group.reIndex()
{
"nIndexesWas" : 1,
"nIndexes" : 1,
"indexes" : [
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
],
"ok" : 1
}

groupコレクションに対してインデックスの再構築を行うことができました。


次回は、テキストインデックスの作成とTTLインデックスの作成を行います。

MongoDB(40) - インデックスの削除

今回は、インデックスの削除を行います。

インデックスの削除

インデックスの削除にはdropIndexを使用します。

第1引数にはインデックス名を指名します。

(インデックス名はgetIndexesで取得できるnameフィールドの値です。)

[Mongoシェル]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
> db.position.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"name" : 1
},
"name" : "name_1"
}
]

> db.position.dropIndexes("name_1")
{ "nIndexesWas" : 2, "ok" : 1 }

> db.position.getIndexes()
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]

positionコレクションのname_1インデックスを削除することができました。

次回は、インデックスの再構築を行います。