kmongo icon indicating copy to clipboard operation
kmongo copied to clipboard

Ensure Index Behaviour

Open netag opened this issue 5 years ago • 3 comments

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:

  1. ensureIndex has 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?

  2. 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.

netag avatar Jun 16 '20 10:06 netag

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.

zigzago avatar Jun 16 '20 22:06 zigzago

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.

netag avatar Jun 17 '20 16:06 netag

createOrRebuildIndex looks good to me. A PR would be welcome :)

zigzago avatar Jun 17 '20 19:06 zigzago