@@ -22,6 +22,8 @@ class DatabaseSeedingService {
22
22
Future <void > seedInitialData () async {
23
23
_log.info ('Starting database seeding process...' );
24
24
25
+ await _ensureIndexes ();
26
+
25
27
await _seedCollection <Country >(
26
28
collectionName: 'countries' ,
27
29
fixtureData: countriesFixturesData,
@@ -115,4 +117,38 @@ class DatabaseSeedingService {
115
117
rethrow ;
116
118
}
117
119
}
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
+ }
118
154
}
0 commit comments