MongoDB getIndex /修改TTL索引

时间:2015-07-16 13:51:44

标签: java mongodb

我使用的是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); 

3 个答案:

答案 0 :(得分:2)

您无法更新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);

答案 1 :(得分:2)

根据mongoDB docs,修改现有索引的唯一方法是删除它并再次创建。

如果您希望在不循环列表的情况下获取特定索引,可以在findOne集合上使用system.indexes

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

如果不存在这样的索引,那么您将获得null,否则您将能够阅读expireAfterSeconds属性 - 秒,而不是几天。

答案 2 :(得分:0)

根据MongoDB docs,您可以在Mongo shell中运行命令,如下所述:v2.2:

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

翻译它以使用MongoDB Java driver,您得到:

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

在测试集合中似乎对我工作正常。

相关问题