feat(collections/search): Improve text index creation and search fallback mechanisms in collections and document search methods

This commit is contained in:
2025-04-18 11:25:39 +00:00
parent 558f83a3d9
commit b5a9449d5e
4 changed files with 46 additions and 45 deletions

View File

@@ -1,7 +1,7 @@
import * as plugins from './plugins.js';
import { SmartdataDb } from './classes.db.js';
import { SmartdataDbCursor } from './classes.cursor.js';
import { SmartDataDbDoc, type IIndexOptions } from './classes.doc.js';
import { SmartDataDbDoc, type IIndexOptions, getSearchableFields } from './classes.doc.js';
import { SmartdataDbWatcher } from './classes.watcher.js';
import { CollectionFactory } from './classes.collectionfactory.js';
@@ -128,6 +128,8 @@ export class SmartdataCollection<T> {
public smartdataDb: SmartdataDb;
public uniqueIndexes: string[] = [];
public regularIndexes: Array<{field: string, options: IIndexOptions}> = [];
// flag to ensure text index is created only once
private textIndexCreated: boolean = false;
constructor(classNameArg: string, smartDataDbArg: SmartdataDb) {
// tell the collection where it belongs
@@ -153,6 +155,14 @@ export class SmartdataCollection<T> {
console.log(`Successfully initiated Collection ${this.collectionName}`);
}
this.mongoDbCollection = this.smartdataDb.mongoDb.collection(this.collectionName);
// Auto-create a compound text index on all searchable fields
const searchableFields = getSearchableFields(this.collectionName);
if (searchableFields.length > 0 && !this.textIndexCreated) {
const indexSpec: { [key: string]: string } = {};
searchableFields.forEach(f => { indexSpec[f] = 'text'; });
await this.mongoDbCollection.createIndex(indexSpec, { name: 'smartdata_text_index' });
this.textIndexCreated = true;
}
}
}