gpt4 book ai didi

java - MongoDB getIndex/修改TTL索引

转载 作者:行者123 更新时间:2023-11-29 03:07:20 24 4
gpt4 key购买 nike

我正在使用 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);

关于java - MongoDB getIndex/修改TTL索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31456202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com