kmongo
kmongo copied to clipboard
Ensure Index Behaviour
Hi all
I'm having some trouble understanding the reasoning behind the implementation of ensureIndex.
fun <T> MongoCollection<T>.ensureIndex(keys: Bson, indexOptions: IndexOptions = IndexOptions()): String {
return try {
createIndex(keys, indexOptions)
} catch (e: MongoCommandException) {
//there is an exception if the parameters of an existing index are changed.
//then drop the index and create a new one
try {
dropIndex(keys)
} catch (e2: Exception) {
//ignore
}
createIndex(keys, indexOptions)
}
}
my questions:
-
ensureIndexhas been deprecated since mongo-server-version 3.0.0.. Kmongo is using java-driver 4.0, why should it expose this behaviour if it's no longer supported? -
The spec definition exists for version 2.6, and it clearly specifies that
ensureIndex will not rebuild the existing index with the new options. Why is kmongo dropping the old index? I believe alerting a user on an error is a better behaviour here. I would hate to role a version to production and get some of my indices rebuilt without me intending to do so.
You are right, the KMongo ensureIndex extension has not the same goal than old mongo method ensureIndex.
So it does not follow the mongo spec. In fact, it was designed without knowledge of this mongo method.
The behaviour is documented. It avoids index creation runtime error, when you change the TTL of an index for example. Of course, it is not suitable for all use cases.
Should it be renamed? May be. If you suggest a better name, I would deprecate ensureIndex.
Also, I think that a createIndex extension with vararg KProperty<*> parameter, and a createUniqueIndex extension should be added.
if we renamed it to createOrRebuild ? or something along the lines, giving more info to the user besides documentation?
another option is to let the user provide an optional "callback" on how to deal with exceptions happening during the create process.
i am more than willing to have a go on such pr, including the extensions you mentioned.
createOrRebuildIndex looks good to me. A PR would be welcome :)