|
1
|
import { Logger, SearchTypes } from "@medusajs/framework/types" |
|
2
|
import { |
|
3
|
AbstractSearchProviderService, |
|
4
|
MedusaError, |
|
5
|
promiseAll, |
|
6
|
} from "@medusajs/framework/utils" |
|
7
|
import { |
|
8
|
assertIndexSupported, |
|
9
|
assertQuerySupported, |
|
10
|
bm25IndexName, |
|
11
|
buildFacetQuery, |
|
12
|
buildIndexPlan, |
|
13
|
CATALOG_TABLE, |
|
14
|
extractPrimaryKeyFilter, |
|
15
|
IndexPlan, |
|
16
|
keywordTsQuerySql, |
|
17
|
mapFacetResult, |
|
18
|
normalizeFacetRequests, |
|
19
|
PostgresSearchEngine, |
|
20
|
PostgresSearchEmbedder, |
|
21
|
PostgresSearchProviderOptions, |
|
22
|
PostgresVectorDistance, |
|
23
|
projectDocument, |
|
24
|
projectIndexedDocument, |
|
25
|
resolveVectorField, |
|
26
|
sameSchema, |
|
27
|
sourceTextForEmbed, |
|
28
|
SqlFragment, |
|
29
|
tableNameForIndex, |
|
30
|
textSearchConfigName, |
|
31
|
toWhereClause, |
|
32
|
vectorColumnName, |
|
33
|
vectorDistanceOperator, |
|
34
|
vectorOpClass, |
|
35
|
weightLabel, |
|
36
|
wordSimilarityCall, |
|
37
|
} from "../utils" |
|
38
|
|
|
39
|
type DbManager = { |
|
40
|
execute: (sql: string, params?: unknown[]) => Promise<any[]> |
|
41
|
transactional?: <T>(cb: (manager: DbManager) => Promise<T>) => Promise<T> |
|
42
|
} |
|
43
|
|
|
44
|
type InjectedDependencies = { |
|
45
|
manager: DbManager |
|
46
|
logger?: Logger |
|
47
|
} |
|
48
|
|
|
49
|
type CatalogRow = { |
|
50
|
name: string |
|
51
|
table_name: string |
|
52
|
schema_hash: string |
|
53
|
plan: unknown |
|
54
|
document_count: number | string |
|
55
|
created_at: Date | string |
|
56
|
updated_at: Date | string |
|
57
|
} |
|
58
|
|
|
59
|
type StoredIndex = { |
|
60
|
name: string |
|
61
|
table_name: string |
|
62
|
schema_hash: string |
|
63
|
plan: IndexPlan |
|
64
|
document_count: number |
|
65
|
created_at: Date | string |
|
66
|
updated_at: Date | string |
|
67
|
} |
|
68
|
|
|
69
|
/** |
|
70
|
* Pieces of a search query that push their own placeholders. Each builder is |
|
71
|
* called once per statement in SQL text order, appending to the shared params |
|
72
|
* array, so hits and count queries stay positionally consistent. |
|
73
|
*/ |
|
74
|
type QueryParts = { |
|
75
|
table: string |
|
76
|
/** SELECT-list relevance expression. */ |
|
77
|
rankSql: (params: unknown[]) => string |
|
78
|
/** WHERE conditions (match predicate + filters). */ |
|
79
|
conditionsSql: (params: unknown[]) => string[] |
|
80
|
/** Param-free ORDER BY, valid against the selected columns. */ |
|
81
|
orderSql: string |
|
82
|
/** |
|
83
|
* Parameterized ORDER BY for the un-wrapped hits query only — lets the |
|
84
|
* vector path order by `col <=> ?` directly so the ANN index can serve it. |
|
85
|
*/ |
|
86
|
fastOrderSql?: (params: unknown[]) => string |
|
87
|
minScore?: number |
|
88
|
/** `indexed#>>...` expression to deduplicate on (one hit per value). */ |
|
89
|
distinctExpr?: string |
|
90
|
count: boolean |
|
91
|
take: number |
|
92
|
skip: number |
|
93
|
/** Runs on the same manager before the hits query (e.g. BM25 set_config). */ |
|
94
|
prelude?: (manager: DbManager) => Promise<void> |
|
95
|
} |
|
96
|
|
|
97
|
/** How many documents to write per multi-row upsert statement. */ |
|
98
|
const UPSERT_CHUNK_SIZE = 200 |
|
99
|
|
|
100
|
/** |
|
101
|
* PostgreSQL search provider with two engines: |
|
102
|
* |
|
103
|
* - `native` (default) — portable GIN + `ts_rank` + `pg_trgm` |
|
104
|
* - `lakebase` — Lakebase Search (`lakebase_bm25` + `lakebase_ann`) |
|
105
|
* |
|
106
|
* Medusa Cloud uses `engine: "lakebase"`. Local / self-hosted stick to native. |
|
107
|
*/ |
|
108
|
export class PostgresSearchService extends AbstractSearchProviderService { |
|
109
|
static identifier = "search-postgres" |
|
110
|
|
|
111
|
protected readonly manager_: DbManager |
|
112
|
protected readonly logger_?: Logger |
|
113
|
protected readonly language_: string |
|
114
|
protected readonly engine_: PostgresSearchEngine |
|
115
|
protected readonly embedder_?: PostgresSearchEmbedder |
|
116
|
protected readonly vectorDistance_: PostgresVectorDistance |
|
117
|
|
|
118
|
constructor( |
|
119
|
{ manager, logger }: InjectedDependencies, |
|
120
|
options: PostgresSearchProviderOptions = {} |
|
121
|
) { |
|
122
|
super() |
|
123
|
|
|
124
|
if (!manager?.execute) { |
|
125
|
throw new MedusaError( |
|
126
|
MedusaError.Types.INVALID_ARGUMENT, |
|
127
|
"The postgres search provider requires a database manager. Ensure the Search Module is configured with a Postgres connection." |
|
128
|
) |
|
129
|
} |
|
130
|
|
|
131
|
this.manager_ = manager |
|
132
|
this.logger_ = logger |
|
133
|
this.language_ = this.normalizeLanguage(options.language ?? "english") |
|
134
|
this.engine_ = options.engine ?? "native" |
|
135
|
this.embedder_ = options.embedder |
|
136
|
this.vectorDistance_ = options.vector_distance ?? "cosine" |
|
137
|
|
|
138
|
if (this.engine_ !== "native" && this.engine_ !== "lakebase") { |
|
139
|
throw new MedusaError( |
|
140
|
MedusaError.Types.INVALID_DATA, |
|
141
|
`Invalid postgres search engine "${options.engine}". Use "native" or "lakebase".` |
|
142
|
) |
|
143
|
} |
|
144
|
} |
|
145
|
|
|
146
|
protected normalizeLanguage(language: string): string { |
|
147
|
if (!/^[a-z0-9_]+$/i.test(language)) { |
|
148
|
throw new MedusaError( |
|
149
|
MedusaError.Types.INVALID_DATA, |
|
150
|
`Invalid postgres search language "${language}". Use a built-in text search configuration name such as "english" or "simple".` |
|
151
|
) |
|
152
|
} |
|
153
|
return language |
|
154
|
} |
|
155
|
|
|
156
|
protected get tsConfig_(): string { |
|
157
|
return textSearchConfigName(this.language_) |
|
158
|
} |
|
159
|
|
|
160
|
protected get isLakebase_(): boolean { |
|
161
|
return this.engine_ === "lakebase" |
|
162
|
} |
|
163
|
|
|
164
|
protected serializePlan(plan: IndexPlan): string { |
|
165
|
return JSON.stringify({ |
|
166
|
primary_key: plan.primary_key, |
|
167
|
searchable: plan.searchable, |
|
168
|
vectors: plan.vectors, |
|
169
|
schema_hash: plan.schema_hash, |
|
170
|
fields: [...plan.fields.values()].map((planned) => ({ |
|
171
|
path: planned.path, |
|
172
|
kind: planned.kind, |
|
173
|
is_array: planned.is_array, |
|
174
|
is_date: planned.is_date, |
|
175
|
dimensions: planned.dimensions, |
|
176
|
field: planned.field, |
|
177
|
})), |
|
178
|
}) |
|
179
|
} |
|
180
|
|
|
181
|
protected deserializePlan(raw: unknown): IndexPlan { |
|
182
|
const data = |
|
183
|
typeof raw === "string" ? JSON.parse(raw) : (raw as Record<string, any>) |
|
184
|
|
|
185
|
const fields = new Map( |
|
186
|
(data.fields as any[]).map((entry) => [ |
|
187
|
entry.path, |
|
188
|
{ |
|
189
|
path: entry.path, |
|
190
|
kind: entry.kind, |
|
191
|
is_array: entry.is_array, |
|
192
|
is_date: entry.is_date, |
|
193
|
dimensions: entry.dimensions, |
|
194
|
field: entry.field, |
|
195
|
}, |
|
196
|
]) |
|
197
|
) |
|
198
|
|
|
199
|
return { |
|
200
|
primary_key: data.primary_key, |
|
201
|
searchable: data.searchable ?? [], |
|
202
|
vectors: |
|
203
|
data.vectors ?? |
|
204
|
[...fields.values()] |
|
205
|
.filter((f) => f.kind === "vector") |
|
206
|
.map((f) => f.path), |
|
207
|
schema_hash: data.schema_hash, |
|
208
|
fields, |
|
209
|
} |
|
210
|
} |
|
211
|
|
|
212
|
protected async getCatalog( |
|
213
|
name: string, |
|
214
|
manager: DbManager = this.manager_ |
|
215
|
): Promise<StoredIndex | null> { |
|
216
|
const rows = (await manager.execute( |
|
217
|
`SELECT * FROM "${CATALOG_TABLE}" WHERE "name" = ?`, |
|
218
|
[name] |
|
219
|
)) as CatalogRow[] |
|
220
|
|
|
221
|
if (!rows.length) { |
|
222
|
return null |
|
223
|
} |
|
224
|
|
|
225
|
const row = rows[0] |
|
226
|
return { |
|
227
|
name: row.name, |
|
228
|
table_name: row.table_name, |
|
229
|
schema_hash: row.schema_hash, |
|
230
|
plan: this.deserializePlan(row.plan), |
|
231
|
document_count: Number(row.document_count), |
|
232
|
created_at: row.created_at, |
|
233
|
updated_at: row.updated_at, |
|
234
|
} |
|
235
|
} |
|
236
|
|
|
237
|
protected async createDocumentTable( |
|
238
|
table: string, |
|
239
|
plan: IndexPlan, |
|
240
|
manager: DbManager |
|
241
|
) { |
|
242
|
const vectorColumns = plan.vectors |
|
243
|
.map((path) => { |
|
244
|
const planned = plan.fields.get(path)! |
|
245
|
const col = vectorColumnName(path) |
|
246
|
return `"${col}" vector(${planned.dimensions})` |
|
247
|
}) |
|
248
|
.join(",\n ") |
|
249
|
|
|
250
|
await manager.execute(` |
|
251
|
CREATE TABLE IF NOT EXISTS "${table}" ( |
|
252
|
"id" text NOT NULL, |
|
253
|
"document" jsonb NOT NULL, |
|
254
|
"indexed" jsonb NOT NULL DEFAULT '{}'::jsonb, |
|
255
|
"search_vector" tsvector NOT NULL DEFAULT ''::tsvector, |
|
256
|
"search_text" text NOT NULL DEFAULT '', |
|
257
|
${vectorColumns ? `${vectorColumns},` : ""} |
|
258
|
"created_at" timestamptz NOT NULL DEFAULT now(), |
|
259
|
"updated_at" timestamptz NOT NULL DEFAULT now(), |
|
260
|
CONSTRAINT "${table}_pkey" PRIMARY KEY ("id") |
|
261
|
) |
|
262
|
`) |
|
263
|
|
|
264
|
// Add vector columns if the table already existed without them. |
|
265
|
for (const path of plan.vectors) { |
|
266
|
const planned = plan.fields.get(path)! |
|
267
|
const col = vectorColumnName(path) |
|
268
|
await manager.execute(` |
|
269
|
ALTER TABLE "${table}" |
|
270
|
ADD COLUMN IF NOT EXISTS "${col}" vector(${planned.dimensions}) |
|
271
|
`) |
|
272
|
} |
|
273
|
|
|
274
|
if (this.isLakebase_) { |
|
275
|
// BM25 index is created lazily after documents exist (corpus stats). |
|
276
|
await manager.execute(`DROP INDEX IF EXISTS "${table}_fts_idx"`) |
|
277
|
} else { |
|
278
|
await manager.execute( |
|
279
|
`CREATE INDEX IF NOT EXISTS "${table}_fts_idx" ON "${table}" USING GIN ("search_vector")` |
|
280
|
) |
|
281
|
} |
|
282
|
|
|
283
|
await manager.execute( |
|
284
|
`CREATE INDEX IF NOT EXISTS "${table}_trgm_idx" ON "${table}" USING GIN ("search_text" gin_trgm_ops)` |
|
285
|
) |
|
286
|
|
|
287
|
await manager.execute( |
|
288
|
`CREATE INDEX IF NOT EXISTS "${table}_indexed_idx" ON "${table}" USING GIN ("indexed" jsonb_path_ops)` |
|
289
|
) |
|
290
|
|
|
291
|
if (this.isLakebase_) { |
|
292
|
const opClass = vectorOpClass(this.vectorDistance_) |
|
293
|
for (const path of plan.vectors) { |
|
294
|
const col = vectorColumnName(path) |
|
295
|
await manager.execute(` |
|
296
|
CREATE INDEX IF NOT EXISTS "${table}_${col}_ann" |
|
297
|
ON "${table}" USING lakebase_ann ("${col}" ${opClass}) |
|
298
|
`) |
|
299
|
} |
|
300
|
} |
|
301
|
} |
|
302
|
|
|
303
|
protected async ensureBm25Index( |
|
304
|
table: string, |
|
305
|
manager: DbManager = this.manager_ |
|
306
|
) { |
|
307
|
if (!this.isLakebase_) { |
|
308
|
return |
|
309
|
} |
|
310
|
|
|
311
|
const name = bm25IndexName(table) |
|
312
|
await manager.execute(` |
|
313
|
CREATE INDEX IF NOT EXISTS "${name}" |
|
314
|
ON "${table}" USING lakebase_bm25 ("search_vector") |
|
315
|
WITH (default_limit = 1000) |
|
316
|
`) |
|
317
|
} |
|
318
|
|
|
319
|
protected async dropBm25Index( |
|
320
|
table: string, |
|
321
|
manager: DbManager = this.manager_ |
|
322
|
) { |
|
323
|
if (!this.isLakebase_) { |
|
324
|
return |
|
325
|
} |
|
326
|
await manager.execute(`DROP INDEX IF EXISTS "${bm25IndexName(table)}"`) |
|
327
|
} |
|
328
|
|
|
329
|
protected async dropDocumentTable(table: string, manager: DbManager) { |
|
330
|
await manager.execute(`DROP TABLE IF EXISTS "${table}" CASCADE`) |
|
331
|
} |
|
332
|
|
|
333
|
protected async adjustDocumentCount( |
|
334
|
name: string, |
|
335
|
delta: number, |
|
336
|
manager: DbManager = this.manager_ |
|
337
|
) { |
|
338
|
if (!delta) { |
|
339
|
return |
|
340
|
} |
|
341
|
await manager.execute( |
|
342
|
`UPDATE "${CATALOG_TABLE}" |
|
343
|
SET "document_count" = GREATEST("document_count" + ?, 0), "updated_at" = now() |
|
344
|
WHERE "name" = ?`, |
|
345
|
[delta, name] |
|
346
|
) |
|
347
|
} |
|
348
|
|
|
349
|
protected async setDocumentCount( |
|
350
|
name: string, |
|
351
|
count: number, |
|
352
|
manager: DbManager = this.manager_ |
|
353
|
) { |
|
354
|
await manager.execute( |
|
355
|
`UPDATE "${CATALOG_TABLE}" |
|
356
|
SET "document_count" = ?, "updated_at" = now() |
|
357
|
WHERE "name" = ?`, |
|
358
|
[count, name] |
|
359
|
) |
|
360
|
} |
|
361
|
|
|
362
|
protected async withTransaction<T>( |
|
363
|
run: (manager: DbManager) => Promise<T> |
|
364
|
): Promise<T> { |
|
365
|
if (this.manager_.transactional) { |
|
366
|
return await this.manager_.transactional(run) |
|
367
|
} |
|
368
|
return await run(this.manager_) |
|
369
|
} |
|
370
|
|
|
371
|
async upsertIndex({ |
|
372
|
index, |
|
373
|
}: { |
|
374
|
index: SearchTypes.ResolvedSearchIndexDefinition |
|
375
|
}): Promise<SearchTypes.SearchTask> { |
|
376
|
assertIndexSupported(index, this.engine_, this.logger_) |
|
377
|
const plan = buildIndexPlan(index, this.engine_) |
|
378
|
this.assertEmbedderForPlan(plan) |
|
379
|
const table = tableNameForIndex(index.physical_name) |
|
380
|
const existing = await this.getCatalog(index.physical_name) |
|
381
|
const rebuilt = |
|
382
|
!!existing && !sameSchema(existing.plan, plan) && !!existing.table_name |
|
383
|
|
|
384
|
await this.withTransaction(async (manager) => { |
|
385
|
if (rebuilt) { |
|
386
|
await this.dropDocumentTable(existing!.table_name, manager) |
|
387
|
} |
|
388
|
|
|
389
|
await this.createDocumentTable(table, plan, manager) |
|
390
|
|
|
391
|
const planJson = this.serializePlan(plan) |
|
392
|
|
|
393
|
if (existing) { |
|
394
|
await manager.execute( |
|
395
|
`UPDATE "${CATALOG_TABLE}" |
|
396
|
SET "table_name" = ?, "schema_hash" = ?, "plan" = ?::jsonb, |
|
397
|
${rebuilt ? `"document_count" = 0,` : ""} |
|
398
|
"updated_at" = now() |
|
399
|
WHERE "name" = ?`, |
|
400
|
[table, plan.schema_hash, planJson, index.physical_name] |
|
401
|
) |
|
402
|
} else { |
|
403
|
await manager.execute( |
|
404
|
`INSERT INTO "${CATALOG_TABLE}" |
|
405
|
("name", "table_name", "schema_hash", "plan", "document_count") |
|
406
|
VALUES (?, ?, ?, ?::jsonb, 0)`, |
|
407
|
[index.physical_name, table, plan.schema_hash, planJson] |
|
408
|
) |
|
409
|
} |
|
410
|
}) |
|
411
|
|
|
412
|
return this.task(index.physical_name) |
|
413
|
} |
|
414
|
|
|
415
|
async deleteIndex({ |
|
416
|
index, |
|
417
|
}: { |
|
418
|
index: string |
|
419
|
}): Promise<SearchTypes.SearchTask> { |
|
420
|
const existing = await this.getCatalog(index) |
|
421
|
|
|
422
|
if (existing) { |
|
423
|
await this.dropDocumentTable(existing.table_name, this.manager_) |
|
424
|
await this.manager_.execute( |
|
425
|
`DELETE FROM "${CATALOG_TABLE}" WHERE "name" = ?`, |
|
426
|
[index] |
|
427
|
) |
|
428
|
} |
|
429
|
|
|
430
|
return this.task(index) |
|
431
|
} |
|
432
|
|
|
433
|
async listIndexes(): Promise<SearchTypes.SearchIndexInfo[]> { |
|
434
|
const rows = (await this.manager_.execute( |
|
435
|
`SELECT "name", "document_count", "created_at", "updated_at" |
|
436
|
FROM "${CATALOG_TABLE}" |
|
437
|
ORDER BY "name"` |
|
438
|
)) as CatalogRow[] |
|
439
|
|
|
440
|
return rows.map((row) => ({ |
|
441
|
name: row.name, |
|
442
|
provider: PostgresSearchService.identifier, |
|
443
|
document_count: Number(row.document_count), |
|
444
|
created_at: |
|
445
|
row.created_at instanceof Date |
|
446
|
? row.created_at |
|
447
|
: new Date(row.created_at), |
|
448
|
updated_at: |
|
449
|
row.updated_at instanceof Date |
|
450
|
? row.updated_at |
|
451
|
: new Date(row.updated_at), |
|
452
|
})) |
|
453
|
} |
|
454
|
|
|
455
|
protected buildSearchVectorSql( |
|
456
|
weightedParts: { text: string; weight: "A" | "B" | "C" | "D" }[], |
|
457
|
params: unknown[] |
|
458
|
): string { |
|
459
|
if (!weightedParts.length) { |
|
460
|
return `''::tsvector` |
|
461
|
} |
|
462
|
|
|
463
|
return weightedParts |
|
464
|
.map((part) => { |
|
465
|
params.push(part.text) |
|
466
|
return `setweight(to_tsvector('${this.tsConfig_}', coalesce(?, '')), '${part.weight}')` |
|
467
|
}) |
|
468
|
.join(" || ") |
|
469
|
} |
|
470
|
|
|
471
|
async upsertDocuments({ |
|
472
|
index, |
|
473
|
documents, |
|
474
|
}: { |
|
475
|
index: string |
|
476
|
definition: SearchTypes.ResolvedSearchIndexDefinition |
|
477
|
documents: SearchTypes.SearchDocument[] |
|
478
|
}): Promise<SearchTypes.SearchTask> { |
|
479
|
const catalog = await this.retrieve(index) |
|
480
|
|
|
481
|
if (!documents.length) { |
|
482
|
return this.task(index) |
|
483
|
} |
|
484
|
|
|
485
|
// Last write wins on duplicate ids — a multi-row upsert cannot touch the |
|
486
|
// same id twice within one statement. |
|
487
|
const projections = new Map< |
|
488
|
string, |
|
489
|
{ |
|
490
|
document: SearchTypes.SearchDocument |
|
491
|
projection: ReturnType<typeof projectIndexedDocument> |
|
492
|
} |
|
493
|
>() |
|
494
|
for (const document of documents) { |
|
495
|
const projection = projectIndexedDocument(document, catalog.plan) |
|
496
|
projections.set(projection.id, { document, projection }) |
|
497
|
} |
|
498
|
|
|
499
|
await this.applyEngineEmbeddings(projections, catalog.plan) |
|
500
|
|
|
501
|
const vectors = catalog.plan.vectors |
|
502
|
const entries = [...projections.values()] |
|
503
|
|
|
504
|
await this.withTransaction(async (manager) => { |
|
505
|
let inserted = 0 |
|
506
|
|
|
507
|
for ( |
|
508
|
let offset = 0; |
|
509
|
offset < entries.length; |
|
510
|
offset += UPSERT_CHUNK_SIZE |
|
511
|
) { |
|
512
|
const chunk = entries.slice(offset, offset + UPSERT_CHUNK_SIZE) |
|
513
|
const rowsSql: string[] = [] |
|
514
|
const params: unknown[] = [] |
|
515
|
|
|
516
|
for (const { document, projection } of chunk) { |
|
517
|
params.push( |
|
518
|
projection.id, |
|
519
|
JSON.stringify(document), |
|
520
|
JSON.stringify(projection.indexed) |
|
521
|
) |
|
522
|
const vectorSql = this.buildSearchVectorSql( |
|
523
|
projection.weighted_parts, |
|
524
|
params |
|
525
|
) |
|
526
|
params.push(projection.search_text) |
|
527
|
|
|
528
|
const vectorPlaceholders = vectors.map((path) => { |
|
529
|
const embedding = projection.vectors[path] |
|
530
|
params.push(embedding ? `[${embedding.join(",")}]` : null) |
|
531
|
return `?::vector` |
|
532
|
}) |
|
533
|
|
|
534
|
rowsSql.push( |
|
535
|
`(?, ?::jsonb, ?::jsonb, ${vectorSql}, ?${ |
|
536
|
vectorPlaceholders.length |
|
537
|
? `, ${vectorPlaceholders.join(", ")}` |
|
538
|
: "" |
|
539
|
}, now())` |
|
540
|
) |
|
541
|
} |
|
542
|
|
|
543
|
const vectorCols = vectors.map((path) => `"${vectorColumnName(path)}"`) |
|
544
|
const vectorUpdates = vectorCols.map( |
|
545
|
(col) => `${col} = EXCLUDED.${col}` |
|
546
|
) |
|
547
|
|
|
548
|
const rows = await manager.execute( |
|
549
|
` |
|
550
|
INSERT INTO "${catalog.table_name}" |
|
551
|
("id", "document", "indexed", "search_vector", "search_text"${ |
|
552
|
vectorCols.length ? `, ${vectorCols.join(", ")}` : "" |
|
553
|
}, "updated_at") |
|
554
|
VALUES ${rowsSql.join(",\n")} |
|
555
|
ON CONFLICT ("id") DO UPDATE SET |
|
556
|
"document" = EXCLUDED."document", |
|
557
|
"indexed" = EXCLUDED."indexed", |
|
558
|
"search_vector" = EXCLUDED."search_vector", |
|
559
|
"search_text" = EXCLUDED."search_text"${ |
|
560
|
vectorUpdates.length ? `, ${vectorUpdates.join(", ")}` : "" |
|
561
|
}, |
|
562
|
"updated_at" = now() |
|
563
|
RETURNING (xmax = 0)::int AS inserted |
|
564
|
`, |
|
565
|
params |
|
566
|
) |
|
567
|
|
|
568
|
for (const row of rows) { |
|
569
|
inserted += Number(row.inserted ?? 0) |
|
570
|
} |
|
571
|
} |
|
572
|
|
|
573
|
await this.adjustDocumentCount(index, inserted, manager) |
|
574
|
}) |
|
575
|
|
|
576
|
// Create the BM25 index once documents exist (corpus stats need rows). |
|
577
|
if (this.isLakebase_) { |
|
578
|
await this.ensureBm25Index(catalog.table_name) |
|
579
|
} |
|
580
|
|
|
581
|
return this.task(index) |
|
582
|
} |
|
583
|
|
|
584
|
async deleteDocuments({ |
|
585
|
index, |
|
586
|
filters, |
|
587
|
}: SearchTypes.SearchDeleteDocumentsInput): Promise<SearchTypes.SearchTask> { |
|
588
|
const catalog = await this.retrieve(index) |
|
589
|
|
|
590
|
await this.withTransaction(async (manager) => { |
|
591
|
const ids = extractPrimaryKeyFilter(filters, catalog.plan) |
|
592
|
let deleted: any[] = [] |
|
593
|
|
|
594
|
if (ids) { |
|
595
|
if (ids.length) { |
|
596
|
// Bind each id as its own `?`. A single array binding with `ANY(?::text[])` |
|
597
|
// is inlined by MikroORM as `ANY('id'::text[])`, which Postgres rejects. |
|
598
|
const placeholders = ids.map(() => "?").join(", ") |
|
599
|
deleted = await manager.execute( |
|
600
|
`DELETE FROM "${catalog.table_name}" WHERE "id" = ANY(ARRAY[${placeholders}]::text[]) RETURNING "id"`, |
|
601
|
ids |
|
602
|
) |
|
603
|
} |
|
604
|
} else { |
|
605
|
const where = toWhereClause(filters, catalog.plan) |
|
606
|
if (where?.sql) { |
|
607
|
deleted = await manager.execute( |
|
608
|
`DELETE FROM "${catalog.table_name}" WHERE ${where.sql} RETURNING "id"`, |
|
609
|
where.params |
|
610
|
) |
|
611
|
} |
|
612
|
} |
|
613
|
|
|
614
|
await this.adjustDocumentCount(index, -deleted.length, manager) |
|
615
|
}) |
|
616
|
|
|
617
|
return this.task(index) |
|
618
|
} |
|
619
|
|
|
620
|
async clearIndex({ |
|
621
|
index, |
|
622
|
}: { |
|
623
|
index: string |
|
624
|
}): Promise<SearchTypes.SearchTask> { |
|
625
|
const catalog = await this.retrieve(index) |
|
626
|
|
|
627
|
await this.dropBm25Index(catalog.table_name) |
|
628
|
await this.manager_.execute(`TRUNCATE TABLE "${catalog.table_name}"`) |
|
629
|
await this.setDocumentCount(index, 0) |
|
630
|
|
|
631
|
return this.task(index) |
|
632
|
} |
|
633
|
|
|
634
|
protected engineEmbeddedPaths(plan: IndexPlan): string[] { |
|
635
|
return plan.vectors.filter((path) => !!plan.fields.get(path)?.field.embed) |
|
636
|
} |
|
637
|
|
|
638
|
/** |
|
639
|
* Engine-embedded vector fields are produced from the field's own text via |
|
640
|
* the configured `embedder`. Without one the columns would stay null. |
|
641
|
*/ |
|
642
|
protected assertEmbedderForPlan(plan: IndexPlan): void { |
|
643
|
const embedded = this.engineEmbeddedPaths(plan) |
|
644
|
if (!embedded.length || this.embedder_) { |
|
645
|
return |
|
646
|
} |
|
647
|
|
|
648
|
throw new MedusaError( |
|
649
|
MedusaError.Types.INVALID_ARGUMENT, |
|
650
|
`Vector field "${embedded[0]}" declares "embed", which requires an "embedder" function on the postgres search provider options` |
|
651
|
) |
|
652
|
} |
|
653
|
|
|
654
|
protected async applyEngineEmbeddings( |
|
655
|
projections: Map< |
|
656
|
string, |
|
657
|
{ |
|
658
|
document: SearchTypes.SearchDocument |
|
659
|
projection: ReturnType<typeof projectIndexedDocument> |
|
660
|
} |
|
661
|
>, |
|
662
|
plan: IndexPlan |
|
663
|
): Promise<void> { |
|
664
|
const embedded = this.engineEmbeddedPaths(plan) |
|
665
|
if (!embedded.length) { |
|
666
|
return |
|
667
|
} |
|
668
|
|
|
669
|
this.assertEmbedderForPlan(plan) |
|
670
|
const embedder = this.embedder_! |
|
671
|
|
|
672
|
const jobs: Promise<void>[] = [] |
|
673
|
for (const { document, projection } of projections.values()) { |
|
674
|
for (const path of embedded) { |
|
675
|
const planned = plan.fields.get(path)! |
|
676
|
const text = sourceTextForEmbed(document, path) |
|
677
|
if (!text) { |
|
678
|
continue |
|
679
|
} |
|
680
|
|
|
681
|
jobs.push( |
|
682
|
embedder(text).then((embedding) => { |
|
683
|
if (planned.dimensions && embedding.length !== planned.dimensions) { |
|
684
|
throw new MedusaError( |
|
685
|
MedusaError.Types.INVALID_DATA, |
|
686
|
`Embedder returned ${embedding.length} dimensions for "${path}", expected ${planned.dimensions}` |
|
687
|
) |
|
688
|
} |
|
689
|
projection.vectors[path] = embedding |
|
690
|
}) |
|
691
|
) |
|
692
|
} |
|
693
|
} |
|
694
|
|
|
695
|
await Promise.all(jobs) |
|
696
|
} |
|
697
|
|
|
698
|
async search( |
|
699
|
input: SearchTypes.ProviderSearchQuery |
|
700
|
): Promise<SearchTypes.SearchResult> { |
|
701
|
assertQuerySupported(input, this.engine_) |
|
702
|
|
|
703
|
const catalog = await this.retrieve(input.index.physical_name) |
|
704
|
const plan = catalog.plan |
|
705
|
const options = input.search_options ?? {} |
|
706
|
const skip = input.pagination?.skip ?? 0 |
|
707
|
const take = input.pagination?.take ?? 20 |
|
708
|
const started = Date.now() |
|
709
|
|
|
710
|
for (const path of options.attributes_to_search_on ?? []) { |
|
711
|
if (!plan.searchable.includes(path)) { |
|
712
|
throw new MedusaError( |
|
713
|
MedusaError.Types.INVALID_DATA, |
|
714
|
`Field "${path}" is not searchable on search index "${input.index.name}"` |
|
715
|
) |
|
716
|
} |
|
717
|
} |
|
718
|
|
|
719
|
// The index's `distinct_attribute` is the default for every query on it. |
|
720
|
// Resolved once here and threaded down, so a code path that must not |
|
721
|
// deduplicate (a hybrid arm) says so explicitly rather than relying on |
|
722
|
// having cleared `search_options.distinct`. |
|
723
|
const distinct = options.distinct ?? input.index.settings.distinct_attribute |
|
724
|
|
|
725
|
// Fails early on unknown / unsupported distinct fields. |
|
726
|
this.resolveDistinct(distinct, plan, input.index.name) |
|
727
|
|
|
728
|
const q = input.q?.trim() |
|
729
|
const vectorOpts = options.vector |
|
730
|
const semanticRatio = |
|
731
|
vectorOpts?.semantic_ratio ?? (q && vectorOpts ? 0.5 : vectorOpts ? 1 : 0) |
|
732
|
|
|
733
|
if (q && !plan.searchable.length && semanticRatio < 1) { |
|
734
|
throw new MedusaError( |
|
735
|
MedusaError.Types.INVALID_DATA, |
|
736
|
`Search index "${input.index.name}" has no searchable fields, so it cannot be queried by text` |
|
737
|
) |
|
738
|
} |
|
739
|
|
|
740
|
let queryEmbedding: number[] | undefined |
|
741
|
if (vectorOpts && semanticRatio > 0) { |
|
742
|
queryEmbedding = await this.resolveQueryEmbedding(vectorOpts, plan) |
|
743
|
} |
|
744
|
|
|
745
|
const useKeyword = !!q && semanticRatio < 1 |
|
746
|
const useVector = !!queryEmbedding && semanticRatio > 0 |
|
747
|
|
|
748
|
let hitRows: any[] |
|
749
|
let count: number | null |
|
750
|
|
|
751
|
if (useKeyword && useVector) { |
|
752
|
;({ hitRows, count } = await this.searchHybrid({ |
|
753
|
input, |
|
754
|
catalog, |
|
755
|
queryEmbedding: queryEmbedding!, |
|
756
|
semanticRatio, |
|
757
|
distinct, |
|
758
|
skip, |
|
759
|
take, |
|
760
|
})) |
|
761
|
} else if (useVector) { |
|
762
|
;({ hitRows, count } = await this.searchVector({ |
|
763
|
input, |
|
764
|
catalog, |
|
765
|
queryEmbedding: queryEmbedding!, |
|
766
|
distinct, |
|
767
|
skip, |
|
768
|
take, |
|
769
|
})) |
|
770
|
} else { |
|
771
|
;({ hitRows, count } = await this.searchKeyword({ |
|
772
|
input, |
|
773
|
catalog, |
|
774
|
distinct, |
|
775
|
skip, |
|
776
|
take, |
|
777
|
})) |
|
778
|
} |
|
779
|
|
|
780
|
const facets = await this.resolveFacets({ |
|
781
|
table: catalog.table_name, |
|
782
|
plan, |
|
783
|
scopeWhere: this.buildFacetScope({ |
|
784
|
input, |
|
785
|
catalog, |
|
786
|
useKeyword, |
|
787
|
useVector, |
|
788
|
}), |
|
789
|
requests: options.facets as |
|
790
|
| (string | SearchTypes.SearchFacetRequest)[] |
|
791
|
| undefined, |
|
792
|
}) |
|
793
|
|
|
794
|
return { |
|
795
|
hits: hitRows.map((row: any) => { |
|
796
|
const document = |
|
797
|
typeof row.document === "string" |
|
798
|
? JSON.parse(row.document) |
|
799
|
: row.document |
|
800
|
|
|
801
|
return { |
|
802
|
id: row.id, |
|
803
|
score: options.include_score ? Number(row.score) : undefined, |
|
804
|
document: projectDocument(document, input.attributes_to_retrieve), |
|
805
|
} |
|
806
|
}), |
|
807
|
facets, |
|
808
|
metadata: { |
|
809
|
skip, |
|
810
|
take, |
|
811
|
count: options.count === "none" ? null : count, |
|
812
|
query: input.q, |
|
813
|
processing_time_ms: Date.now() - started, |
|
814
|
}, |
|
815
|
} |
|
816
|
} |
|
817
|
|
|
818
|
protected async resolveQueryEmbedding( |
|
819
|
vectorOpts: NonNullable<SearchTypes.SearchOptions["vector"]>, |
|
820
|
plan: IndexPlan |
|
821
|
): Promise<number[]> { |
|
822
|
const field = resolveVectorField(vectorOpts, plan) |
|
823
|
const planned = plan.fields.get(field)! |
|
824
|
|
|
825
|
if (vectorOpts.value) { |
|
826
|
if ( |
|
827
|
planned.dimensions && |
|
828
|
vectorOpts.value.length !== planned.dimensions |
|
829
|
) { |
|
830
|
throw new MedusaError( |
|
831
|
MedusaError.Types.INVALID_DATA, |
|
832
|
`Vector value for "${field}" expected ${planned.dimensions} dimensions, got ${vectorOpts.value.length}` |
|
833
|
) |
|
834
|
} |
|
835
|
return vectorOpts.value |
|
836
|
} |
|
837
|
|
|
838
|
if (!vectorOpts.query) { |
|
839
|
throw new MedusaError( |
|
840
|
MedusaError.Types.INVALID_DATA, |
|
841
|
`search_options.vector requires either "value" (embedding) or "query" (text to embed)` |
|
842
|
) |
|
843
|
} |
|
844
|
|
|
845
|
if (!planned.field.embed) { |
|
846
|
throw new MedusaError( |
|
847
|
MedusaError.Types.INVALID_DATA, |
|
848
|
`search_options.vector.query requires vector field "${field}" to declare "embed"` |
|
849
|
) |
|
850
|
} |
|
851
|
|
|
852
|
if (!this.embedder_) { |
|
853
|
throw new MedusaError( |
|
854
|
MedusaError.Types.INVALID_ARGUMENT, |
|
855
|
`search_options.vector.query requires an "embedder" function on the postgres search provider options` |
|
856
|
) |
|
857
|
} |
|
858
|
|
|
859
|
const embedding = await this.embedder_(vectorOpts.query) |
|
860
|
if (planned.dimensions && embedding.length !== planned.dimensions) { |
|
861
|
throw new MedusaError( |
|
862
|
MedusaError.Types.INVALID_DATA, |
|
863
|
`Embedder returned ${embedding.length} dimensions for "${field}", expected ${planned.dimensions}` |
|
864
|
) |
|
865
|
} |
|
866
|
return embedding |
|
867
|
} |
|
868
|
|
|
869
|
/** |
|
870
|
* The keyword match/rank fragments, shared by the keyword path, the hybrid |
|
871
|
* count and the facet scope so they always describe the same result set. |
|
872
|
* Each fragment pushes its own placeholders when invoked. |
|
873
|
*/ |
|
874
|
protected keywordFragments(input: { |
|
875
|
query: SearchTypes.ProviderSearchQuery |
|
876
|
catalog: StoredIndex |
|
877
|
}): { |
|
878
|
q?: string |
|
879
|
needsBm25Limit: boolean |
|
880
|
rankSql: (params: unknown[]) => string |
|
881
|
matchSql?: (params: unknown[]) => string |
|
882
|
} { |
|
883
|
const { query, catalog } = input |
|
884
|
const plan = catalog.plan |
|
885
|
const options = query.search_options ?? {} |
|
886
|
const q = query.q?.trim() || undefined |
|
887
|
// `search_options.typo_tolerance` is a preference; an index that turned |
|
888
|
// typo tolerance off in its settings serves exact matches instead. |
|
889
|
const typo = !!( |
|
890
|
q && |
|
891
|
options.typo_tolerance && |
|
892
|
(query.index.settings.typo_tolerance?.enabled ?? true) |
|
893
|
) |
|
894
|
const matchLast = options.match_strategy === "last" |
|
895
|
const searchOn = options.attributes_to_search_on ?? plan.searchable |
|
896
|
const searchAllFields = |
|
897
|
searchOn.length === plan.searchable.length && |
|
898
|
searchOn.every((path) => plan.searchable.includes(path)) |
|
899
|
const tsConfig = this.tsConfig_ |
|
900
|
const vectorExpr = searchAllFields |
|
901
|
? `"search_vector"` |
|
902
|
: this.onTheFlyVectorExpr(searchOn, plan) |
|
903
|
const textExpr = searchAllFields |
|
904
|
? `"search_text"` |
|
905
|
: this.onTheFlyTextExpr(searchOn) |
|
906
|
// Prefix queries (`match_strategy: "last"`) are expressed as a tsquery |
|
907
|
// `:*`; BM25 ranks the raw query string and would score those hits 0. |
|
908
|
const useBm25 = this.isLakebase_ && !!q && searchAllFields && !matchLast |
|
909
|
|
|
910
|
const tsquery = (params: unknown[]) => { |
|
911
|
params.push(q) |
|
912
|
return keywordTsQuerySql(tsConfig, options.match_strategy) |
|
913
|
} |
|
914
|
|
|
915
|
const wordSim = (params: unknown[]) => { |
|
916
|
params.push(q) |
|
917
|
return wordSimilarityCall("?", textExpr) |
|
918
|
} |
|
919
|
|
|
920
|
const rankSql = (params: unknown[]) => { |
|
921
|
if (!q) { |
|
922
|
return `0::float4` |
|
923
|
} |
|
924
|
|
|
925
|
let base: string |
|
926
|
if (useBm25) { |
|
927
|
params.push(q) |
|
928
|
const bm25 = bm25IndexName(catalog.table_name) |
|
929
|
// Negative BM25 → negate so higher scores are better (API convention). |
|
930
|
base = `-1 * (${vectorExpr} <@> to_bm25query(to_tsvector('${tsConfig}', ?), '${bm25}'::regclass))` |
|
931
|
} else { |
|
932
|
base = `ts_rank_cd(${vectorExpr}, ${tsquery(params)})` |
|
933
|
} |
|
934
|
|
|
935
|
return typo ? `GREATEST(${base}, ${wordSim(params)})` : base |
|
936
|
} |
|
937
|
|
|
938
|
const matchSql = q |
|
939
|
? (params: unknown[]) => { |
|
940
|
const match = `${vectorExpr} @@ ${tsquery(params)}` |
|
941
|
return typo ? `(${match} OR ${wordSim(params)} > 0.3)` : match |
|
942
|
} |
|
943
|
: undefined |
|
944
|
|
|
945
|
return { q, needsBm25Limit: useBm25, rankSql, matchSql } |
|
946
|
} |
|
947
|
|
|
948
|
protected async searchKeyword(input: { |
|
949
|
input: SearchTypes.ProviderSearchQuery |
|
950
|
catalog: StoredIndex |
|
951
|
distinct?: string |
|
952
|
skip: number |
|
953
|
take: number |
|
954
|
}): Promise<{ hitRows: any[]; count: number | null }> { |
|
955
|
const { input: query, catalog, distinct, skip, take } = input |
|
956
|
const plan = catalog.plan |
|
957
|
const options = query.search_options ?? {} |
|
958
|
const filterWhere = toWhereClause(query.filters, plan) |
|
959
|
const fragments = this.keywordFragments({ query, catalog }) |
|
960
|
|
|
961
|
const conditionsSql = (params: unknown[]) => { |
|
962
|
const conditions: string[] = [] |
|
963
|
if (fragments.matchSql) { |
|
964
|
conditions.push(fragments.matchSql(params)) |
|
965
|
} |
|
966
|
if (filterWhere?.sql) { |
|
967
|
conditions.push(`(${filterWhere.sql})`) |
|
968
|
params.push(...filterWhere.params) |
|
969
|
} |
|
970
|
return conditions |
|
971
|
} |
|
972
|
|
|
973
|
const prelude = fragments.needsBm25Limit |
|
974
|
? async (manager: DbManager) => { |
|
975
|
const bm25 = bm25IndexName(catalog.table_name) |
|
976
|
const [row] = await manager.execute( |
|
977
|
`SELECT to_regclass(?) IS NOT NULL AS exists`, |
|
978
|
[bm25] |
|
979
|
) |
|
980
|
if (!row?.exists) { |
|
981
|
await this.ensureBm25Index(catalog.table_name, manager) |
|
982
|
} |
|
983
|
await manager.execute( |
|
984
|
`SELECT set_config('lakebase_bm25.default_limit', ?, true)`, |
|
985
|
[String(take + skip)] |
|
986
|
) |
|
987
|
} |
|
988
|
: undefined |
|
989
|
|
|
990
|
return await this.executeQuery({ |
|
991
|
table: catalog.table_name, |
|
992
|
rankSql: fragments.rankSql, |
|
993
|
conditionsSql, |
|
994
|
orderSql: this.resolveOrderBy(query, plan, !!fragments.q), |
|
995
|
minScore: options.min_score, |
|
996
|
distinctExpr: this.resolveDistinct(distinct, plan, query.index.name), |
|
997
|
count: options.count !== "none", |
|
998
|
take, |
|
999
|
skip, |
|
1000
|
prelude, |
|
1001
|
}) |
|
1002
|
} |
|
1003
|
|
|
1004
|
protected async searchVector(input: { |
|
1005
|
input: SearchTypes.ProviderSearchQuery |
|
1006
|
catalog: StoredIndex |
|
1007
|
queryEmbedding: number[] |
|
1008
|
distinct?: string |
|
1009
|
skip: number |
|
1010
|
take: number |
|
1011
|
}): Promise<{ hitRows: any[]; count: number | null }> { |
|
1012
|
const { |
|
1013
|
input: query, |
|
1014
|
catalog, |
|
1015
|
queryEmbedding, |
|
1016
|
distinct, |
|
1017
|
skip, |
|
1018
|
take, |
|
1019
|
} = input |
|
1020
|
const options = query.search_options ?? {} |
|
1021
|
const field = resolveVectorField(options.vector!, catalog.plan) |
|
1022
|
const col = vectorColumnName(field) |
|
1023
|
const op = vectorDistanceOperator(this.vectorDistance_) |
|
1024
|
const filterWhere = toWhereClause(query.filters, catalog.plan) |
|
1025
|
const embeddingLiteral = `[${queryEmbedding.join(",")}]` |
|
1026
|
|
|
1027
|
const rankSql = (params: unknown[]) => { |
|
1028
|
params.push(embeddingLiteral) |
|
1029
|
// Distance → relevance (higher is better). |
|
1030
|
return `(1.0 / (1.0 + ("${col}" ${op} ?::vector)))` |
|
1031
|
} |
|
1032
|
|
|
1033
|
const conditionsSql = (params: unknown[]) => { |
|
1034
|
const conditions: string[] = [`"${col}" IS NOT NULL`] |
|
1035
|
if (filterWhere?.sql) { |
|
1036
|
conditions.push(`(${filterWhere.sql})`) |
|
1037
|
params.push(...filterWhere.params) |
|
1038
|
} |
|
1039
|
return conditions |
|
1040
|
} |
|
1041
|
|
|
1042
|
const hasCustomOrder = !!Object.keys(query.pagination?.order ?? {}).length |
|
1043
|
// The default order is distance ASC; expressed directly (instead of via |
|
1044
|
// the score alias) so the ANN index can serve the scan. |
|
1045
|
const fastOrderSql = hasCustomOrder |
|
1046
|
? undefined |
|
1047
|
: (params: unknown[]) => { |
|
1048
|
params.push(embeddingLiteral) |
|
1049
|
return `"${col}" ${op} ?::vector ASC, "id" ASC` |
|
1050
|
} |
|
1051
|
|
|
1052
|
return await this.executeQuery({ |
|
1053
|
table: catalog.table_name, |
|
1054
|
rankSql, |
|
1055
|
conditionsSql, |
|
1056
|
orderSql: this.resolveOrderBy(query, catalog.plan, true), |
|
1057
|
fastOrderSql, |
|
1058
|
minScore: options.min_score, |
|
1059
|
distinctExpr: this.resolveDistinct( |
|
1060
|
distinct, |
|
1061
|
catalog.plan, |
|
1062
|
query.index.name |
|
1063
|
), |
|
1064
|
count: options.count !== "none", |
|
1065
|
take, |
|
1066
|
skip, |
|
1067
|
}) |
|
1068
|
} |
|
1069
|
|
|
1070
|
protected async searchHybrid(input: { |
|
1071
|
input: SearchTypes.ProviderSearchQuery |
|
1072
|
catalog: StoredIndex |
|
1073
|
queryEmbedding: number[] |
|
1074
|
semanticRatio: number |
|
1075
|
distinct?: string |
|
1076
|
skip: number |
|
1077
|
take: number |
|
1078
|
}): Promise<{ hitRows: any[]; count: number | null }> { |
|
1079
|
const { |
|
1080
|
input: query, |
|
1081
|
catalog, |
|
1082
|
queryEmbedding, |
|
1083
|
semanticRatio, |
|
1084
|
distinct, |
|
1085
|
skip, |
|
1086
|
take, |
|
1087
|
} = input |
|
1088
|
const options = query.search_options ?? {} |
|
1089
|
const plan = catalog.plan |
|
1090
|
|
|
1091
|
const order = query.pagination?.order ?? {} |
|
1092
|
const fieldOrderKeys = Object.keys(order).filter((key) => key !== "_score") |
|
1093
|
if (fieldOrderKeys.length) { |
|
1094
|
throw new MedusaError( |
|
1095
|
MedusaError.Types.NOT_ALLOWED, |
|
1096
|
`Hybrid search results are rank-fused, so they can only be ordered by "_score" (got "${fieldOrderKeys.join( |
|
1097
|
", " |
|
1098
|
)}"). Drop the vector option or the field order.` |
|
1099
|
) |
|
1100
|
} |
|
1101
|
|
|
1102
|
// Arms are relevance-ranked candidate lists; page-level options (distinct, |
|
1103
|
// min_score, count, order) apply to the fused list instead. `distinct` is |
|
1104
|
// passed to each arm explicitly below. |
|
1105
|
const candidateLimit = Math.max(take + skip, 40) * 2 |
|
1106
|
const armQuery: SearchTypes.ProviderSearchQuery = { |
|
1107
|
...query, |
|
1108
|
pagination: {}, |
|
1109
|
search_options: { |
|
1110
|
...options, |
|
1111
|
min_score: undefined, |
|
1112
|
count: "none", |
|
1113
|
}, |
|
1114
|
} |
|
1115
|
|
|
1116
|
const [keyword, vector] = await Promise.all([ |
|
1117
|
this.searchKeyword({ |
|
1118
|
input: armQuery, |
|
1119
|
catalog, |
|
1120
|
distinct: undefined, |
|
1121
|
skip: 0, |
|
1122
|
take: candidateLimit, |
|
1123
|
}), |
|
1124
|
this.searchVector({ |
|
1125
|
input: armQuery, |
|
1126
|
catalog, |
|
1127
|
queryEmbedding, |
|
1128
|
distinct: undefined, |
|
1129
|
skip: 0, |
|
1130
|
take: candidateLimit, |
|
1131
|
}), |
|
1132
|
]) |
|
1133
|
|
|
1134
|
// Reciprocal Rank Fusion over keyword + vector candidate lists. Fused |
|
1135
|
// scores live on the RRF scale (≤ ~1/60 per arm), which is also the scale |
|
1136
|
// `min_score` is compared against for hybrid queries. |
|
1137
|
const k = 60 |
|
1138
|
const keywordWeight = 1 - semanticRatio |
|
1139
|
const vectorWeight = semanticRatio |
|
1140
|
const scores = new Map< |
|
1141
|
string, |
|
1142
|
{ id: string; document: unknown; indexed: unknown; score: number } |
|
1143
|
>() |
|
1144
|
|
|
1145
|
keyword.hitRows.forEach((row, rank) => { |
|
1146
|
scores.set(row.id, { |
|
1147
|
id: row.id, |
|
1148
|
document: row.document, |
|
1149
|
indexed: row.indexed, |
|
1150
|
score: keywordWeight * (1 / (k + rank + 1)), |
|
1151
|
}) |
|
1152
|
}) |
|
1153
|
|
|
1154
|
vector.hitRows.forEach((row, rank) => { |
|
1155
|
const rrf = vectorWeight * (1 / (k + rank + 1)) |
|
1156
|
const existing = scores.get(row.id) |
|
1157
|
if (existing) { |
|
1158
|
existing.score += rrf |
|
1159
|
} else { |
|
1160
|
scores.set(row.id, { |
|
1161
|
id: row.id, |
|
1162
|
document: row.document, |
|
1163
|
indexed: row.indexed, |
|
1164
|
score: rrf, |
|
1165
|
}) |
|
1166
|
} |
|
1167
|
}) |
|
1168
|
|
|
1169
|
let ranked = [...scores.values()].sort((a, b) => b.score - a.score) |
|
1170
|
|
|
1171
|
if (distinct) { |
|
1172
|
const seen = new Set<string>() |
|
1173
|
ranked = ranked.filter((row) => { |
|
1174
|
const key = this.readIndexedValue(row.indexed, distinct) |
|
1175
|
if (key === undefined) { |
|
1176
|
return true |
|
1177
|
} |
|
1178
|
if (seen.has(key)) { |
|
1179
|
return false |
|
1180
|
} |
|
1181
|
seen.add(key) |
|
1182
|
return true |
|
1183
|
}) |
|
1184
|
} |
|
1185
|
|
|
1186
|
if (options.min_score !== undefined) { |
|
1187
|
ranked = ranked.filter((row) => row.score >= options.min_score!) |
|
1188
|
} |
|
1189
|
|
|
1190
|
if (order._score === "ASC") { |
|
1191
|
ranked.reverse() |
|
1192
|
} |
|
1193
|
|
|
1194
|
const page = ranked.slice(skip, skip + take) |
|
1195
|
|
|
1196
|
// The fused list is a bounded candidate window, so its length is not a |
|
1197
|
// usable total — count the union of both arms' match sets instead. |
|
1198
|
let count: number | null = null |
|
1199
|
if (options.count !== "none") { |
|
1200
|
const fragments = this.keywordFragments({ query, catalog }) |
|
1201
|
const col = vectorColumnName(resolveVectorField(options.vector!, plan)) |
|
1202
|
const filterWhere = toWhereClause(query.filters, plan) |
|
1203
|
const params: unknown[] = [] |
|
1204
|
const conditions = [ |
|
1205
|
`(${fragments.matchSql!(params)} OR "${col}" IS NOT NULL)`, |
|
1206
|
] |
|
1207
|
if (filterWhere?.sql) { |
|
1208
|
conditions.push(`(${filterWhere.sql})`) |
|
1209
|
params.push(...filterWhere.params) |
|
1210
|
} |
|
1211
|
|
|
1212
|
const distinctExpr = this.resolveDistinct( |
|
1213
|
distinct, |
|
1214
|
plan, |
|
1215
|
query.index.name |
|
1216
|
) |
|
1217
|
const countExpr = distinctExpr |
|
1218
|
? `COUNT(DISTINCT ${distinctExpr})` |
|
1219
|
: `COUNT(*)` |
|
1220
|
|
|
1221
|
const rows = await this.manager_.execute( |
|
1222
|
`SELECT ${countExpr}::int AS count FROM "${ |
|
1223
|
catalog.table_name |
|
1224
|
}" WHERE ${conditions.join(" AND ")}`, |
|
1225
|
params |
|
1226
|
) |
|
1227
|
count = Number(rows[0]?.count ?? 0) |
|
1228
|
} |
|
1229
|
|
|
1230
|
return { hitRows: page, count } |
|
1231
|
} |
|
1232
|
|
|
1233
|
/** |
|
1234
|
* Runs the hits + count statements for a single-arm search. Wraps the base |
|
1235
|
* select in subqueries when `min_score` or `distinct` need to see the score |
|
1236
|
* as a real column. |
|
1237
|
*/ |
|
1238
|
protected async executeQuery( |
|
1239
|
parts: QueryParts |
|
1240
|
): Promise<{ hitRows: any[]; count: number | null }> { |
|
1241
|
const { table, minScore, distinctExpr, take, skip } = parts |
|
1242
|
const wrap = minScore !== undefined || !!distinctExpr |
|
1243
|
|
|
1244
|
const buildBase = (params: unknown[]) => { |
|
1245
|
const rank = parts.rankSql(params) |
|
1246
|
const conditions = parts.conditionsSql(params) |
|
1247
|
const whereSql = conditions.length |
|
1248
|
? `WHERE ${conditions.join(" AND ")}` |
|
1249
|
: "" |
|
1250
|
return `SELECT "id", "document", "indexed", ${rank} AS score FROM "${table}" ${whereSql}` |
|
1251
|
} |
|
1252
|
|
|
1253
|
const buildWrappedFrom = (params: unknown[]) => { |
|
1254
|
let from = `(${buildBase(params)}) ranked` |
|
1255
|
if (distinctExpr) { |
|
1256
|
// One representative row per value, picked by the requested order. |
|
1257
|
from = `( |
|
1258
|
SELECT ranked.*, ROW_NUMBER() OVER ( |
|
1259
|
PARTITION BY ${distinctExpr} ORDER BY ${parts.orderSql} |
|
1260
|
) AS __rn |
|
1261
|
FROM ${from} |
|
1262
|
) deduped` |
|
1263
|
} |
|
1264
|
return from |
|
1265
|
} |
|
1266
|
|
|
1267
|
const wrappedConditions = () => { |
|
1268
|
const outer: string[] = [] |
|
1269
|
if (distinctExpr) { |
|
1270
|
outer.push(`__rn = 1`) |
|
1271
|
} |
|
1272
|
if (minScore !== undefined) { |
|
1273
|
outer.push(`score >= ?`) |
|
1274
|
} |
|
1275
|
return outer |
|
1276
|
} |
|
1277
|
|
|
1278
|
let hitsSql: string |
|
1279
|
const hitsParams: unknown[] = [] |
|
1280
|
|
|
1281
|
if (!wrap) { |
|
1282
|
const base = buildBase(hitsParams) |
|
1283
|
const orderSql = parts.fastOrderSql |
|
1284
|
? parts.fastOrderSql(hitsParams) |
|
1285
|
: parts.orderSql |
|
1286
|
hitsSql = `${base} ORDER BY ${orderSql} LIMIT ? OFFSET ?` |
|
1287
|
hitsParams.push(take, skip) |
|
1288
|
} else { |
|
1289
|
const from = buildWrappedFrom(hitsParams) |
|
1290
|
const outer = wrappedConditions() |
|
1291
|
hitsSql = ` |
|
1292
|
SELECT * FROM ${from} |
|
1293
|
${outer.length ? `WHERE ${outer.join(" AND ")}` : ""} |
|
1294
|
ORDER BY ${parts.orderSql} |
|
1295
|
LIMIT ? OFFSET ? |
|
1296
|
` |
|
1297
|
if (minScore !== undefined) { |
|
1298
|
hitsParams.push(minScore) |
|
1299
|
} |
|
1300
|
hitsParams.push(take, skip) |
|
1301
|
} |
|
1302
|
|
|
1303
|
let countSql: string | null = null |
|
1304
|
const countParams: unknown[] = [] |
|
1305
|
|
|
1306
|
if (parts.count) { |
|
1307
|
if (!wrap) { |
|
1308
|
const conditions = parts.conditionsSql(countParams) |
|
1309
|
countSql = `SELECT COUNT(*)::int AS count FROM "${table}" ${ |
|
1310
|
conditions.length ? `WHERE ${conditions.join(" AND ")}` : "" |
|
1311
|
}` |
|
1312
|
} else { |
|
1313
|
const from = buildWrappedFrom(countParams) |
|
1314
|
const outer = wrappedConditions() |
|
1315
|
countSql = ` |
|
1316
|
SELECT COUNT(*)::int AS count FROM ${from} |
|
1317
|
${outer.length ? `WHERE ${outer.join(" AND ")}` : ""} |
|
1318
|
` |
|
1319
|
if (minScore !== undefined) { |
|
1320
|
countParams.push(minScore) |
|
1321
|
} |
|
1322
|
} |
|
1323
|
} |
|
1324
|
|
|
1325
|
const run = async (manager: DbManager) => { |
|
1326
|
if (parts.prelude) { |
|
1327
|
await parts.prelude(manager) |
|
1328
|
} |
|
1329
|
|
|
1330
|
const hitRows = |
|
1331
|
take === 0 ? [] : await manager.execute(hitsSql, hitsParams) |
|
1332
|
const count = countSql |
|
1333
|
? Number((await manager.execute(countSql, countParams))[0]?.count ?? 0) |
|
1334
|
: null |
|
1335
|
|
|
1336
|
return { hitRows, count } |
|
1337
|
} |
|
1338
|
|
|
1339
|
// set_config in the prelude is transaction-local, so it needs the hits |
|
1340
|
// query inside the same transaction. Plain reads skip the overhead. |
|
1341
|
return parts.prelude |
|
1342
|
? await this.withTransaction(run) |
|
1343
|
: await run(this.manager_) |
|
1344
|
} |
|
1345
|
|
|
1346
|
async searchMany( |
|
1347
|
inputs: SearchTypes.ProviderSearchQuery[] |
|
1348
|
): Promise<SearchTypes.SearchResult[]> { |
|
1349
|
// Postgres has no multi-query protocol; concurrent statements through the |
|
1350
|
// pool are the batch. Facet-only extras (`take: 0`) skip the hits query. |
|
1351
|
return await promiseAll(inputs.map((input) => this.search(input))) |
|
1352
|
} |
|
1353
|
|
|
1354
|
/** |
|
1355
|
* The WHERE fragment facets are scoped by: the filters plus the same match |
|
1356
|
* predicate as the hits, so facet counts describe the result set. |
|
1357
|
*/ |
|
1358
|
protected buildFacetScope(input: { |
|
1359
|
input: SearchTypes.ProviderSearchQuery |
|
1360
|
catalog: StoredIndex |
|
1361
|
useKeyword: boolean |
|
1362
|
useVector: boolean |
|
1363
|
}): SqlFragment | undefined { |
|
1364
|
const { input: query, catalog, useKeyword, useVector } = input |
|
1365
|
const params: unknown[] = [] |
|
1366
|
const conditions: string[] = [] |
|
1367
|
|
|
1368
|
const matchSql = useKeyword |
|
1369
|
? this.keywordFragments({ query, catalog }).matchSql |
|
1370
|
: undefined |
|
1371
|
const vectorCond = useVector |
|
1372
|
? `"${vectorColumnName( |
|
1373
|
resolveVectorField(query.search_options!.vector!, catalog.plan) |
|
1374
|
)}" IS NOT NULL` |
|
1375
|
: undefined |
|
1376
|
|
|
1377
|
if (matchSql && vectorCond) { |
|
1378
|
conditions.push(`(${matchSql(params)} OR ${vectorCond})`) |
|
1379
|
} else if (matchSql) { |
|
1380
|
conditions.push(matchSql(params)) |
|
1381
|
} else if (vectorCond) { |
|
1382
|
conditions.push(vectorCond) |
|
1383
|
} |
|
1384
|
|
|
1385
|
const filterWhere = toWhereClause(query.filters, catalog.plan) |
|
1386
|
if (filterWhere?.sql) { |
|
1387
|
conditions.push(`(${filterWhere.sql})`) |
|
1388
|
params.push(...filterWhere.params) |
|
1389
|
} |
|
1390
|
|
|
1391
|
return conditions.length |
|
1392
|
? { sql: conditions.join(" AND "), params } |
|
1393
|
: undefined |
|
1394
|
} |
|
1395
|
|
|
1396
|
protected async resolveFacets(input: { |
|
1397
|
table: string |
|
1398
|
plan: IndexPlan |
|
1399
|
scopeWhere?: SqlFragment |
|
1400
|
requests?: (string | SearchTypes.SearchFacetRequest)[] |
|
1401
|
}): Promise<Record<string, SearchTypes.SearchFacetResult> | undefined> { |
|
1402
|
const requests = normalizeFacetRequests(input.requests, input.plan) |
|
1403
|
if (!requests.length) { |
|
1404
|
return undefined |
|
1405
|
} |
|
1406
|
|
|
1407
|
const result: Record<string, SearchTypes.SearchFacetResult> = {} |
|
1408
|
const entries = await promiseAll( |
|
1409
|
requests.map(async (request) => { |
|
1410
|
const query = buildFacetQuery({ |
|
1411
|
table: input.table, |
|
1412
|
whereSql: input.scopeWhere?.sql, |
|
1413
|
whereParams: input.scopeWhere?.params ?? [], |
|
1414
|
request, |
|
1415
|
plan: input.plan, |
|
1416
|
}) |
|
1417
|
const rows = await this.manager_.execute(query.sql, query.params) |
|
1418
|
return [request.field, mapFacetResult(request, rows)] as const |
|
1419
|
}) |
|
1420
|
) |
|
1421
|
|
|
1422
|
for (const [field, facet] of entries) { |
|
1423
|
result[field] = facet |
|
1424
|
} |
|
1425
|
|
|
1426
|
return result |
|
1427
|
} |
|
1428
|
|
|
1429
|
protected onTheFlyTextExpr(paths: string[]): string { |
|
1430
|
if (!paths.length) { |
|
1431
|
return `''` |
|
1432
|
} |
|
1433
|
|
|
1434
|
return paths |
|
1435
|
.map((path) => { |
|
1436
|
const jsonPath = `'{${path.split(".").join(",")}}'` |
|
1437
|
return `coalesce(indexed#>>${jsonPath}, '')` |
|
1438
|
}) |
|
1439
|
.join(` || ' ' || `) |
|
1440
|
} |
|
1441
|
|
|
1442
|
protected onTheFlyVectorExpr(paths: string[], plan: IndexPlan): string { |
|
1443
|
if (!paths.length) { |
|
1444
|
return `''::tsvector` |
|
1445
|
} |
|
1446
|
|
|
1447
|
return paths |
|
1448
|
.map((path) => { |
|
1449
|
const planned = plan.fields.get(path) |
|
1450
|
const weight = planned ? weightLabel(planned.field.searchable) : "D" |
|
1451
|
const jsonPath = `'{${path.split(".").join(",")}}'` |
|
1452
|
return `setweight(to_tsvector('${this.tsConfig_}', coalesce(indexed#>>${jsonPath}, '')), '${weight}')` |
|
1453
|
}) |
|
1454
|
.join(" || ") |
|
1455
|
} |
|
1456
|
|
|
1457
|
protected resolveOrderBy( |
|
1458
|
input: SearchTypes.ProviderSearchQuery, |
|
1459
|
plan: IndexPlan, |
|
1460
|
hasScore: boolean |
|
1461
|
): string { |
|
1462
|
const order = Object.entries(input.pagination?.order ?? {}) |
|
1463
|
|
|
1464
|
if (!order.length) { |
|
1465
|
return hasScore ? `score DESC NULLS LAST, "id" ASC` : `"id" ASC` |
|
1466
|
} |
|
1467
|
|
|
1468
|
const clauses: string[] = [] |
|
1469
|
|
|
1470
|
for (const [property, direction] of order) { |
|
1471
|
const dir = direction === "ASC" ? "ASC" : "DESC" |
|
1472
|
|
|
1473
|
if (property === "_score") { |
|
1474
|
clauses.push(`score ${dir} NULLS LAST`) |
|
1475
|
continue |
|
1476
|
} |
|
1477
|
|
|
1478
|
const planned = plan.fields.get(property) |
|
1479
|
if (!planned) { |
|
1480
|
throw new MedusaError( |
|
1481
|
MedusaError.Types.INVALID_DATA, |
|
1482
|
`Cannot sort search index "${input.index.name}" by unknown field "${property}"` |
|
1483
|
) |
|
1484
|
} |
|
1485
|
|
|
1486
|
if (planned.is_array || planned.kind === "vector") { |
|
1487
|
throw new MedusaError( |
|
1488
|
MedusaError.Types.NOT_ALLOWED, |
|
1489
|
`The postgres search provider cannot sort by "${property}"` |
|
1490
|
) |
|
1491
|
} |
|
1492
|
|
|
1493
|
const jsonPath = `'{${property.split(".").join(",")}}'` |
|
1494
|
|
|
1495
|
if (planned.kind === "number") { |
|
1496
|
clauses.push(`(indexed#>>${jsonPath})::float8 ${dir} NULLS LAST`) |
|
1497
|
} else if (planned.kind === "boolean") { |
|
1498
|
clauses.push(`(indexed#>>${jsonPath})::boolean ${dir} NULLS LAST`) |
|
1499
|
} else { |
|
1500
|
clauses.push(`indexed#>>${jsonPath} ${dir} NULLS LAST`) |
|
1501
|
} |
|
1502
|
} |
|
1503
|
|
|
1504
|
return clauses.join(", ") |
|
1505
|
} |
|
1506
|
|
|
1507
|
/** |
|
1508
|
* Validates the field to deduplicate by — `search_options.distinct` or the |
|
1509
|
* index's `settings.distinct_attribute` — and returns the SQL expression for |
|
1510
|
* it, or undefined when neither is set. |
|
1511
|
*/ |
|
1512
|
protected resolveDistinct( |
|
1513
|
distinct: string | undefined, |
|
1514
|
plan: IndexPlan, |
|
1515
|
indexName: string |
|
1516
|
): string | undefined { |
|
1517
|
if (!distinct) { |
|
1518
|
return undefined |
|
1519
|
} |
|
1520
|
|
|
1521
|
const planned = plan.fields.get(distinct) |
|
1522
|
if (!planned) { |
|
1523
|
throw new MedusaError( |
|
1524
|
MedusaError.Types.INVALID_DATA, |
|
1525
|
`Cannot deduplicate search index "${indexName}" by unknown field "${distinct}"` |
|
1526
|
) |
|
1527
|
} |
|
1528
|
|
|
1529
|
if (planned.is_array || planned.kind === "vector") { |
|
1530
|
throw new MedusaError( |
|
1531
|
MedusaError.Types.NOT_ALLOWED, |
|
1532
|
`The postgres search provider cannot deduplicate by "${distinct}"` |
|
1533
|
) |
|
1534
|
} |
|
1535
|
|
|
1536
|
return `indexed#>>'{${distinct.split(".").join(",")}}'` |
|
1537
|
} |
|
1538
|
|
|
1539
|
/** Reads a dotted path from an `indexed` jsonb value returned by a query. */ |
|
1540
|
protected readIndexedValue( |
|
1541
|
indexed: unknown, |
|
1542
|
path: string |
|
1543
|
): string | undefined { |
|
1544
|
const parsed = typeof indexed === "string" ? JSON.parse(indexed) : indexed |
|
1545
|
|
|
1546
|
const value = path |
|
1547
|
.split(".") |
|
1548
|
.reduce<any>( |
|
1549
|
(acc, segment) => (acc == null ? undefined : acc[segment]), |
|
1550
|
parsed |
|
1551
|
) |
|
1552
|
|
|
1553
|
return value == null ? undefined : String(value) |
|
1554
|
} |
|
1555
|
|
|
1556
|
protected async retrieve(index: string): Promise<StoredIndex> { |
|
1557
|
const catalog = await this.getCatalog(index) |
|
1558
|
|
|
1559
|
if (!catalog) { |
|
1560
|
const known = await this.listIndexes() |
|
1561
|
throw new MedusaError( |
|
1562
|
MedusaError.Types.NOT_FOUND, |
|
1563
|
`The postgres search provider has no index "${index}". Known indexes: ${ |
|
1564
|
known.map((entry) => entry.name).join(", ") || "(none)" |
|
1565
|
}` |
|
1566
|
) |
|
1567
|
} |
|
1568
|
|
|
1569
|
return catalog |
|
1570
|
} |
|
1571
|
|
|
1572
|
protected task(index: string): SearchTypes.SearchTask { |
|
1573
|
return { index, status: "succeeded" } |
|
1574
|
} |
|
1575
|
} |