簡體   English   中英

MongoDB getIndex /修改TTL索引

[英]MongoDB getIndex / amend TTL Index

我正在使用MongoDB和Java。 我有Mongo 3.0.1 Java驅動程序。 我創建了一個集合,該集合上有一個帶有expireAfter屬性的TTL索引。 如果我嘗試修改該值,則代碼將出現錯誤:

'exception: Index with name: created_1 already exists with different options'

因此,在決定是否刪除索引並為其創建新版本之前,我想檢查索引是否存在,並檢查索引的expireAfter屬性。

MongoCollection對象只有listIndexes方法,該方法返回一個集合。 獲取索引並檢查expireAfter屬性的最佳方法是什么?

這是首先創建索引的代碼。 當我更改EXPIRATION_DAYS常量的值並重新運行代碼時,將發生問題:

private static final Long EXPIRATION_DAYS = Long.valueOf(10);

....

final IndexOptions options = new IndexOptions();
options.expireAfter(EXPIRATION_DAYS, TimeUnit.DAYS);
database.getCollection(errors).createIndex(new BasicDBObject("created", 1), options); 

您無法在MongoDB中更新索引。 您必須先刪除現有索引,然后使用其他選項重新創建它。

我建議您使用特定名稱創建索引。 這樣,您可以遍歷現有索引並刪除有問題的索引,然后再重新創建它。

private static final Long EXPIRATION_DAYS = Long.valueOf(10);
private static final String INDEX_NAME = "myIndex";

[...]

MongoCollection<Document> errorsCollection = database.getCollection(errors);
ListIndexesIterable<Document> indexes = errorsCollection.listIndexes();
for (Document index : indexes) {
    if (index.getString("name").equals(INDEX_NAME) && index.getLong("expireAfterSeconds") != TimeUnit.SECONDS.convert(EXPIRATION_DAYS, TimeUnit.DAYS)) {
        errorsCollection.dropIndex(INDEX_NAME);
    }
}

IndexOptions options = new IndexOptions()
    .name(INDEX_NAME)
    .expireAfter(EXPIRATION_DAYS, TimeUnit.DAYS);
errorsCollection.createIndex(new Document("created", 1), options);

根據mongoDB文檔 ,修改現有索引的唯一方法是刪除索引並重新創建。

如果要獲取特定索引而不遍歷列表,可以在system.indexes集合上使用findOne

DBObject index = database.getCollection("system.indexes")
                         .findOne(new BasicDBObject("name", "created_1"));

如果不存在這樣的索引,那么您將獲得null否則您將能夠讀取expireAfterSeconds屬性-秒,而不是天。

根據MongoDB文檔 ,自v2.2起,您已經能夠在Mongo shell中運行以下命令:

db.runCommand({collMod: "<collection-name>",
               index : { keyPattern: { "<indexed-field>": 1 },
                         expireAfterSeconds: <new-value> }})

轉換為使用MongoDB Java驅動程序 ,您將獲得:

Document collModCmd =
  Document.parse("{collMod: '<collection-name>', " +
                 " index : { keyPattern: {'<indexed-field>': 1}, " +
                 "           expireAfterSeconds: <new-value> }}");
Document commandResult = db.runCommand(collModCmd);

似乎對我的測試收集工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM