Spaces:
Running
Running
Upload pages/api/search.js with huggingface_hub
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import { getDb, initializeData } from '../../lib/database'
export default function handler(req, res) { if (req.method !== 'GET') { return res.status(405).json({ error: 'Method not allowed' }) }
const { q } = req.query const query = q || ''
try { // Ensure DB is initialized initializeData() const db = getDb()
const startTime = performance.now() let results = [] let total = 0
if (query.trim()) { // Use FTS5 search with bm25 ranking // We search in title and content, weighting title higher const stmt = db.prepare(` SELECT r.id, r.title, r.content, r.tags, r.date, r.source_url, r.metadata, bm25(documents, 1.0, 0.5) as score, snippet(documents, 0, '<mark>', '</mark>', '...', 32) as snippet FROM documents JOIN documents_raw r ON documents.rowid = r.id WHERE documents MATCH ? ORDER BY score LIMIT 20 `) results = stmt.all(query) total = results.length } else { // If no query, return recent items const stmt = db.prepare(` SELECT id, title, content, tags, date, source_url, metadata FROM documents_raw ORDER BY date DESC LIMIT 10 `) results = stmt.all() total = results.length }
const endTime = performance.now() res.status(200).json({ results, total, time: (endTime - startTime).toFixed(2) })
} catch (error) { console.error('Search error:', error) res.status(500).json({ error: 'Search failed', details: error.message }) }}pages/api/search.jsAdded+68