From 88dc8eddbb10e0ba6d8264820d822a7a6f80fbe3 Mon Sep 17 00:00:00 2001 From: fulleni Date: Sun, 20 Jul 2025 11:46:58 +0100 Subject: [PATCH] feat(database): add index creation to database seeding process This commit introduces a new step in the database seeding process to ensure that necessary text search indexes are created on the 'headlines', 'topics', and 'sources' collections. The `_ensureIndexes` method is added to the DatabaseSeedingService class and is called at the beginning of the `seedInitialData` method. The new indexes will enable efficient text searches on the 'title' field of headlines, the 'name' field of topics, and the 'name' field of sources. This enhancement is crucial for improving the performance of search operations within the application. --- .../services/database_seeding_service.dart | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/lib/src/services/database_seeding_service.dart b/lib/src/services/database_seeding_service.dart index 19379b8..cf91e5e 100644 --- a/lib/src/services/database_seeding_service.dart +++ b/lib/src/services/database_seeding_service.dart @@ -22,6 +22,8 @@ class DatabaseSeedingService { Future seedInitialData() async { _log.info('Starting database seeding process...'); + await _ensureIndexes(); + await _seedCollection( collectionName: 'countries', fixtureData: countriesFixturesData, @@ -115,4 +117,38 @@ class DatabaseSeedingService { rethrow; } } + + /// Ensures that the necessary indexes exist on the collections. + /// + /// This method is idempotent; it will only create indexes if they do not + /// already exist. It's crucial for enabling efficient text searches. + Future _ensureIndexes() async { + _log.info('Ensuring database indexes exist...'); + try { + // Text index for searching headlines by title + await _db.collection('headlines').createIndex( + keys: {'title': 'text'}, + name: 'headlines_text_index', + ); + + // Text index for searching topics by name + await _db.collection('topics').createIndex( + keys: {'name': 'text'}, + name: 'topics_text_index', + ); + + // Text index for searching sources by name + await _db.collection('sources').createIndex( + keys: {'name': 'text'}, + name: 'sources_text_index', + ); + + _log.info('Database indexes are set up correctly.'); + } on Exception catch (e, s) { + _log.severe('Failed to create database indexes.', e, s); + // We rethrow here because if indexes can't be created, + // critical features like search will fail. + rethrow; + } + } }