diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs index 0067f885c..5fa08da70 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs @@ -14,6 +14,7 @@ public MongoDbContext(BotSharpDatabaseSettings dbSettings) _mongoClient = new MongoClient(mongoDbConnectionString); _mongoDbDatabaseName = GetDatabaseName(mongoDbConnectionString); _collectionPrefix = dbSettings.TablePrefix.IfNullOrEmptyAs("BotSharp"); + //CreateIndex(); } private string GetDatabaseName(string mongoDbConnectionString) @@ -28,14 +29,52 @@ private string GetDatabaseName(string mongoDbConnectionString) private IMongoDatabase Database { get { return _mongoClient.GetDatabase(_mongoDbDatabaseName); } } + private IMongoCollection CreateConversationIndex() + { + var collection = Database.GetCollection($"{_collectionPrefix}_Conversations"); + var indexes = collection.Indexes.List().ToList(); + var createTimeIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("CreatedTime")); + if (createTimeIndex == null) + { + var indexDef = Builders.IndexKeys.Descending(x => x.CreatedTime); + collection.Indexes.CreateOne(new CreateIndexModel(indexDef)); + } + + return collection; + } + + private IMongoCollection CreateAgentTaskIndex() + { + var collection = Database.GetCollection($"{_collectionPrefix}_AgentTasks"); + var indexes = collection.Indexes.List().ToList(); + var createTimeIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("CreatedTime")); + if (createTimeIndex == null) + { + var indexDef = Builders.IndexKeys.Descending(x => x.CreatedTime); + collection.Indexes.CreateOne(new CreateIndexModel(indexDef)); + } + + return collection; + } + public IMongoCollection Agents => Database.GetCollection($"{_collectionPrefix}_Agents"); public IMongoCollection AgentTasks - => Database.GetCollection($"{_collectionPrefix}_AgentTasks"); + { + get + { + return CreateAgentTaskIndex(); + } + } public IMongoCollection Conversations - => Database.GetCollection($"{_collectionPrefix}_Conversations"); + { + get + { + return CreateConversationIndex(); + } + } public IMongoCollection ConversationDialogs => Database.GetCollection($"{_collectionPrefix}_ConversationDialogs");