Skip to content

Commit 88dc8ed

Browse files
committed
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.
1 parent f7ff77b commit 88dc8ed

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

lib/src/services/database_seeding_service.dart

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)