Litote / kmongo

[deprecated] KMongo - a Kotlin toolkit for Mongo
https://litote.org/kmongo/
Apache License 2.0
781 stars 74 forks source link

Help needed on creating a geo2dsphere index #347

Closed hamza-maqsood closed 2 years ago

hamza-maqsood commented 2 years ago

I couldn't find any documentation on geo2dsphere index on this link.

Right now, I am trying to create the index as follows

this is my model class

data class UserLocation(
    val userId: String,
    val location: Point // comes from com.mongodb.client.model.geojson.Point
)

And then in the repository impl, I am creating the index as follows

class LocationRepositoryImpl(
    db: CoroutineDatabase
) : LocationRepository {

    private val userLocations = db.getCollection<UserLocation>().apply {
        GlobalScope.launch {
            ensureIndex(Indexes.geo2dsphere("location"))
        }
    }

   // methods
   ....
}

Now my questions is, do I need to call this ensureIndex or createIndex method every time the collection is initialized, or what's the correct way to do it?

zigzago commented 2 years ago

ensureIndex or createIndex do not create index if it does exist (but the existence of the index is checked on server side). So yes you can write this code, especially if you use DI and if LocationRepositoryImpl is a singleton.

By the way, the use of GlobalScope is not recommended, it would be better to setup all your collections in a suspend function, called at application startup.

HTH

hamza-maqsood commented 2 years ago

yeah I thought about GlobalScope and I put it just to test this. Actually I am thinking of doing something like this:

 override suspend fun provideUserLocationCollection(): CoroutineCollection<UserLocation> {
             val collection: CoroutineCollection<UserLocation> = db.getCollection<UserLocation>()
             collection.ensureIndex(Indexes.geo2dsphere("location"))
             return collection
        }
hamza-maqsood commented 2 years ago

thanks that helps, and yes, LocationRepositoryImpl is a singleton and comes from DI