1 import { createHash } from "crypto"
2 import { Logger, SearchTypes } from "@medusajs/framework/types"
3 import { MedusaError } from "@medusajs/framework/utils"
4
5 export type PostgresSearchEngine = "native" | "lakebase"
6
7 export type PostgresFieldKind =
8 | "text"
9 | "keyword"
10 | "number"
11 | "boolean"
12 | "geo"
13 | "vector"
14
15 export type PostgresVectorDistance = "cosine" | "l2" | "inner_product"
16
17 export type PostgresSearchEmbedder = (text: string) => Promise<number[]>
18
19 export type PlannedField = {
20 path: string
21 kind: PostgresFieldKind
22 is_array: boolean
23 is_date: boolean
24 dimensions?: number
25 field: SearchTypes.SearchFieldDefinition
26 }
27
28 export type IndexPlan = {
29 fields: Map<string, PlannedField>
30 searchable: string[]
31 /** Vector field paths declared on the index. */
32 vectors: string[]
33 primary_key: string
34 /**
35 * Stable fingerprint of the physical schema this plan implies. Used to decide
36 * whether an existing table can be reused or must be rebuilt empty.
37 */
38 schema_hash: string
39 }
40
41 export type PostgresSearchProviderOptions = {
42 /**
43 * Text search configuration language passed to `to_tsvector` / `plainto_tsquery`.
44 * @default "english"
45 */
46 language?: string
47 /**
48 * Search engine backend.
49 * - `native` — portable Postgres FTS (GIN + `ts_rank`) + `pg_trgm`. Default.
50 * - `lakebase` — Lakebase Search (`lakebase_text` BM25 + `lakebase_vector` ANN).
51 * @default "native"
52 */
53 engine?: PostgresSearchEngine
54 /**
55 * Embeds text for engine-embedded vector fields (`embed: true` on the field)
56 * at write time, and for `search_options.vector.query` at query time. Required
57 * on the lakebase engine when any vector field declares `embed`.
58 */
59 embedder?: PostgresSearchEmbedder
60 /**
61 * Distance metric for `lakebase_ann` / pgvector indexes.
62 * @default "cosine"
63 */
64 vector_distance?: PostgresVectorDistance
65 }
66
67 function fail(message: string): never {
68 throw new MedusaError(MedusaError.Types.NOT_ALLOWED, message)
69 }
70
71 export function isSearchable(
72 field: SearchTypes.SearchFieldDefinition
73 ): boolean {
74 return field.searchable === true || typeof field.searchable === "object"
75 }
76
77 export function isFacetable(field: SearchTypes.SearchFieldDefinition): boolean {
78 return field.facetable === true || typeof field.facetable === "object"
79 }
80
81 function fieldKind(
82 field: SearchTypes.SearchFieldDefinition
83 ): PostgresFieldKind {
84 switch (field.type) {
85 case "text":
86 return "text"
87 case "keyword":
88 return "keyword"
89 case "integer":
90 case "float":
91 case "date":
92 return "number"
93 case "boolean":
94 return "boolean"
95 case "geo":
96 return "geo"
97 case "vector":
98 return "vector"
99 default:
100 return fail(
101 `The postgres search provider does not support fields of type "${field.type}"`
102 )
103 }
104 }
105
106 /**
107 * Postgres matches typos with `pg_trgm` word similarity over the whole
108 * `search_text` column. It honours `enabled`, but it doesn't support fine-tuning.
109 *
110 * `disabled_on_attributes` states that a field must only ever
111 * match exactly, and ignoring it would fuzzy-match a SKU or a handle the index
112 * deliberately excluded. There is no per-attribute similarity to switch off
113 * here, so it is rejected instead.
114 */
115 function assertTypoToleranceSupported(
116 settings: SearchTypes.SearchIndexSettings
117 ): void {
118 if (settings.typo_tolerance?.disabled_on_attributes?.length) {
119 fail(
120 "The postgres search provider matches typos across all searchable fields at once, so it does not support settings.typo_tolerance.disabled_on_attributes"
121 )
122 }
123 }
124
125 /**
126 * Refuses a definition this engine cannot honour. Vector fields are an
127 * exception: an engine without vector support reports them and ignores them,
128 * so the same index definition stays portable across providers.
129 */
130 export function assertIndexSupported(
131 definition: SearchTypes.ResolvedSearchIndexDefinition,
132 engine: PostgresSearchEngine = "native",
133 logger?: Logger
134 ): void {
135 const supportsVectors = engine === "lakebase"
136 const ignoredVectors: string[] = []
137
138 const walk = (
139 group: Record<string, SearchTypes.SearchFieldDefinition>,
140 prefix: string
141 ) => {
142 for (const [name, field] of Object.entries(group)) {
143 const path = prefix ? `${prefix}.${name}` : name
144
145 if (field.type === "vector") {
146 if (!supportsVectors) {
147 ignoredVectors.push(path)
148 continue
149 }
150 if (!field.dimensions || field.dimensions < 1) {
151 fail(
152 `Vector field "${path}" must declare a positive "dimensions" value`
153 )
154 }
155 if (field.array) {
156 fail(`Vector field "${path}" cannot be an array`)
157 }
158 }
159
160 if (field.type === "geo") {
161 fail(
162 `The postgres search provider does not support geo fields ("${path}")`
163 )
164 }
165
166 if (field.type === "object" && field.fields) {
167 walk(field.fields, path)
168 }
169 }
170 }
171
172 walk(definition.fields, "")
173 assertTypoToleranceSupported(definition.settings)
174
175 if (ignoredVectors.length) {
176 logger?.warn(
177 `The postgres search provider does not support vector search on the "${engine}" engine. Ignoring vector field(s) ${ignoredVectors
178 .map((path) => `"${path}"`)
179 .join(", ")} on search index "${
180 definition.name
181 }". Use Medusa Search to enable vector search.`
182 )
183 }
184 }
185
186 /**
187 * Refuses a query this engine cannot honour without answering incorrectly.
188 */
189 export function assertQuerySupported(
190 query: SearchTypes.ProviderSearchQuery,
191 engine: PostgresSearchEngine = "native"
192 ): void {
193 const options = query.search_options ?? {}
194
195 if (options.highlight && query.q?.trim()) {
196 fail("The postgres search provider does not support highlighting")
197 }
198
199 if (options.vector && engine !== "lakebase") {
200 fail(
201 `Vector search requires engine: "lakebase". The native engine does not support search_options.vector.`
202 )
203 }
204
205 if (options.locales?.length) {
206 fail(
207 "The postgres search provider does not support query-time locales; configure `language` on the provider options instead"
208 )
209 }
210
211 if (query.pagination?.cursor !== undefined) {
212 fail("The postgres search provider does not support cursor pagination")
213 }
214 }
215
216 /**
217 * Keyword match expression. The `?` placeholder is the raw query string.
218 *
219 * - `"all"` (default): `plainto_tsquery` ANDs every complete lexeme.
220 * - `"any"`: the same terms ORed.
221 * - `"last"`: AND, with `:*` on the last lexeme so `"dtc sta"` matches
222 * `"Dtc starter"`.
223 */
224 export function keywordTsQuerySql(
225 tsConfig: string,
226 matchStrategy?: SearchTypes.SearchMatchStrategy
227 ): string {
228 const parsed = `plainto_tsquery('${tsConfig}', ?)`
229
230 if (matchStrategy === "any") {
231 return `replace(${parsed}::text, ' & ', ' | ')::tsquery`
232 }
233
234 if (matchStrategy === "last") {
235 return `regexp_replace(${parsed}::text, '''([^'']+)''$', '''\\1'':*')::tsquery`
236 }
237
238 return parsed
239 }
240
241 /**
242 * Flattens a definition into per-leaf field metadata. Nested objects become
243 * dotted paths; arrays of objects collapse to per-leaf arrays so definitions
244 * stay portable across engines.
245 */
246 export function buildIndexPlan(
247 definition: SearchTypes.ResolvedSearchIndexDefinition,
248 engine: PostgresSearchEngine = "native"
249 ): IndexPlan {
250 const fields = new Map<string, PlannedField>()
251 const searchable: string[] = []
252 const vectors: string[] = []
253 const supportsVectors = engine === "lakebase"
254
255 const walk = (
256 group: Record<string, SearchTypes.SearchFieldDefinition>,
257 prefix: string,
258 inArray: boolean
259 ) => {
260 for (const [name, field] of Object.entries(group)) {
261 const path = prefix ? `${prefix}.${name}` : name
262 const isArray = inArray || field.array === true
263
264 if (field.type === "object") {
265 if (field.fields) {
266 walk(field.fields, path, isArray)
267 }
268 continue
269 }
270
271 if (field.type === "vector" && !supportsVectors) {
272 continue
273 }
274
275 const kind = fieldKind(field)
276 const planned: PlannedField = {
277 path,
278 kind,
279 is_array: isArray,
280 is_date: field.type === "date",
281 dimensions: field.dimensions,
282 field,
283 }
284
285 fields.set(path, planned)
286
287 if (kind === "vector") {
288 vectors.push(path)
289 continue
290 }
291
292 if (isSearchable(field)) {
293 searchable.push(path)
294 }
295 }
296 }
297
298 walk(definition.fields, "", false)
299
300 const schemaPayload = {
301 primary_key: definition.primary_key,
302 fields: [...fields.values()].map((planned) => ({
303 path: planned.path,
304 kind: planned.kind,
305 is_array: planned.is_array,
306 is_date: planned.is_date,
307 dimensions: planned.dimensions,
308 embed: planned.field.embed,
309 searchable: isSearchable(planned.field),
310 filterable: !!planned.field.filterable,
311 sortable: !!planned.field.sortable,
312 facetable: isFacetable(planned.field),
313 })),
314 searchable: [...searchable].sort(),
315 vectors: [...vectors].sort(),
316 }
317
318 return {
319 fields,
320 searchable,
321 vectors,
322 primary_key: definition.primary_key,
323 schema_hash: createHash("sha256")
324 .update(JSON.stringify(schemaPayload))
325 .digest("hex"),
326 }
327 }
328
329 export function sameSchema(a: IndexPlan, b: IndexPlan): boolean {
330 return a.schema_hash === b.schema_hash
331 }
332
333 /**
334 * Maps a field weight onto Postgres `setweight` labels. Higher weights land in
335 * denser buckets so `ts_rank` prefers title matches over body matches.
336 */
337 export function weightLabel(
338 searchable: SearchTypes.SearchFieldDefinition["searchable"]
339 ): "A" | "B" | "C" | "D" {
340 const weight =
341 typeof searchable === "object" && searchable.weight !== undefined
342 ? searchable.weight
343 : 1
344
345 if (weight >= 3) {
346 return "A"
347 }
348 if (weight >= 2) {
349 return "B"
350 }
351 if (weight > 1) {
352 return "C"
353 }
354 return "D"
355 }
356
357 /**
358 * Turns a physical index name into a safe Postgres table identifier.
359 */
360 export function tableNameForIndex(physicalName: string): string {
361 const safe = physicalName
362 .toLowerCase()
363 .replace(/[^a-z0-9_]/g, "_")
364 .replace(/_+/g, "_")
365 .replace(/^_|_$/g, "")
366
367 if (!safe) {
368 fail(`Cannot derive a table name from index "${physicalName}"`)
369 }
370
371 return `search_pg_${safe}`
372 }
373
374 /** BM25 index name for a document table (lakebase engine). */
375 export function bm25IndexName(table: string): string {
376 return `${table}_bm25`
377 }
378
379 /**
380 * Resolves which vector field a query targets. `vector.field` is optional when
381 * the index declares exactly one vector field.
382 */
383 export function resolveVectorField(
384 vector: NonNullable<SearchTypes.SearchOptions["vector"]>,
385 plan: IndexPlan
386 ): string {
387 if (vector.field) {
388 if (!plan.vectors.includes(vector.field)) {
389 fail(
390 `Vector search field "${vector.field}" is not a vector field on this index`
391 )
392 }
393 return vector.field
394 }
395
396 if (plan.vectors.length === 1) {
397 return plan.vectors[0]
398 }
399
400 fail(
401 plan.vectors.length
402 ? `search_options.vector.field is required when the index has more than one vector field`
403 : `search_options.vector requires a vector field on this index`
404 )
405 }
406
407 /**
408 * Physical column name for a vector field path.
409 * `embedding` → `v_embedding`, `meta.vec` → `v_meta_vec`.
410 */
411 export function vectorColumnName(path: string): string {
412 const safe = path
413 .toLowerCase()
414 .replace(/[^a-z0-9_]/g, "_")
415 .replace(/_+/g, "_")
416 return `v_${safe}`
417 }
418
419 export function vectorOpClass(distance: PostgresVectorDistance): string {
420 switch (distance) {
421 case "l2":
422 return "vector_l2_ops"
423 case "inner_product":
424 return "vector_ip_ops"
425 case "cosine":
426 default:
427 return "vector_cosine_ops"
428 }
429 }
430
431 export function vectorDistanceOperator(
432 distance: PostgresVectorDistance
433 ): string {
434 switch (distance) {
435 case "l2":
436 return "<->"
437 case "inner_product":
438 return "<#>"
439 case "cosine":
440 default:
441 return "<=>"
442 }
443 }
444
445 export const CATALOG_TABLE = "search_postgres_index"