UNPKG

fuzzy-search-lib

Version:

A flexible fuzzy search library supporting both MongoDB and PostgreSQL

65 lines 2.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MongoDBAdapter = void 0; const mongodb_1 = require("mongodb"); const helpers_1 = require("../utils/helpers"); const algorithms_1 = require("../algorithms"); class MongoDBAdapter { constructor(connectionString, dbName, collectionName) { this.client = null; this.db = null; this.collection = null; this.connectionString = connectionString; this.dbName = dbName; this.collectionName = collectionName; } async connect() { if (!this.client) { this.client = new mongodb_1.MongoClient(this.connectionString); await this.client.connect(); this.db = this.client.db(this.dbName); this.collection = this.db.collection(this.collectionName); } } async disconnect() { if (this.client) { await this.client.close(); this.client = null; this.db = null; this.collection = null; } } async search(query, options) { if (!this.collection) { throw new Error('Database not connected. Call connect() first.'); } // Default options const threshold = options.threshold ?? 0.5; const limit = options.limit ?? 10; const offset = options.offset ?? 0; const algorithm = options.algorithm ?? 'levenshtein'; // Get all documents (in a real implementation, you might want to filter this) const allDocuments = await this.collection.find({}).toArray(); // Calculate scores for each document const scoredDocuments = allDocuments.map(doc => { const score = (0, helpers_1.calculateMatchScore)(doc, query, options.fields, algorithms_1.algorithms[algorithm].calculate); return { item: doc, score }; }); // Filter by threshold and sort by score const filteredDocuments = scoredDocuments .filter(({ score }) => score >= threshold) .sort((a, b) => b.score - a.score); // Apply pagination const paginatedDocuments = filteredDocuments.slice(offset, offset + limit); return { items: paginatedDocuments.map(({ item }) => item), total: filteredDocuments.length, limit, offset, threshold, query }; } } exports.MongoDBAdapter = MongoDBAdapter; //# sourceMappingURL=mongodb.js.map