@@ -22,6 +22,8 @@ class DatabaseSeedingService {
2222 Future <void > seedInitialData () async {
2323 _log.info ('Starting database seeding process...' );
2424
25+ await _ensureIndexes ();
26+
2527 await _seedCollection <Country >(
2628 collectionName: 'countries' ,
2729 fixtureData: countriesFixturesData,
@@ -115,4 +117,38 @@ class DatabaseSeedingService {
115117 rethrow ;
116118 }
117119 }
120+
121+ /// Ensures that the necessary indexes exist on the collections.
122+ ///
123+ /// This method is idempotent; it will only create indexes if they do not
124+ /// already exist. It's crucial for enabling efficient text searches.
125+ Future <void > _ensureIndexes () async {
126+ _log.info ('Ensuring database indexes exist...' );
127+ try {
128+ // Text index for searching headlines by title
129+ await _db.collection ('headlines' ).createIndex (
130+ keys: {'title' : 'text' },
131+ name: 'headlines_text_index' ,
132+ );
133+
134+ // Text index for searching topics by name
135+ await _db.collection ('topics' ).createIndex (
136+ keys: {'name' : 'text' },
137+ name: 'topics_text_index' ,
138+ );
139+
140+ // Text index for searching sources by name
141+ await _db.collection ('sources' ).createIndex (
142+ keys: {'name' : 'text' },
143+ name: 'sources_text_index' ,
144+ );
145+
146+ _log.info ('Database indexes are set up correctly.' );
147+ } on Exception catch (e, s) {
148+ _log.severe ('Failed to create database indexes.' , e, s);
149+ // We rethrow here because if indexes can't be created,
150+ // critical features like search will fail.
151+ rethrow ;
152+ }
153+ }
118154}
0 commit comments