1 import { SearchTypes } from "@medusajs/framework/types"
2 import { MedusaError } from "@medusajs/framework/utils"
3 import type {
4 AttributeSchemaConfig,
5 ComputeAttributes,
6 Filter,
7 FuzzyEditDistanceThreshold,
8 HighlightFragment,
9 Limit,
10 IndexQuery,
11 RankBy,
12 Row,
13 TokenFilterOptions,
14 } from "./api-types"
15 import { mergeFilters, textMatchFilter, toSearchFilter } from "./filters"
16 import type { MedusaSearchQueryOptions } from "./options"
17 import { IndexPlan, isSearchable } from "./plan"
18
19 export type HighlightPlan = {
20 pre_tag: string
21 post_tag: string
22 fields: { path: string; key: string }[]
23 }
24
25 export type QueryPlan = {
26 query: IndexQuery
27 skip: number
28 take: number
29 options: MedusaSearchQueryOptions
30 highlight?: HighlightPlan
31 distinct?: string
32 }
33
34 function fail(message: string): never {
35 throw new MedusaError(MedusaError.Types.NOT_ALLOWED, message)
36 }
37
38 function providerOptions(
39 input: SearchTypes.ProviderSearchQuery
40 ): MedusaSearchQueryOptions {
41 return (input.search_options?.provider_options?.["search-medusa"] ??
42 {}) as MedusaSearchQueryOptions
43 }
44
45 function searchableFields(
46 input: SearchTypes.ProviderSearchQuery,
47 plan: IndexPlan
48 ): string[] {
49 const fields =
50 input.search_options?.attributes_to_search_on ?? plan.searchable
51
52 if (!fields.length) {
53 fail(
54 `Search index "${input.index.name}" has no searchable fields for a text query`
55 )
56 }
57
58 for (const path of fields) {
59 const field = plan.fields.get(path)
60 if (!field || !isSearchable(field.field)) {
61 fail(`Field "${path}" is not searchable`)
62 }
63 }
64
65 return fields
66 }
67
68 /**
69 * The last word of the query is a prefix, not a whole token, when
70 * `match_strategy` is "last" (typeahead) — every BM25 clause built over
71 * `input.q` needs this so a prefix-only match (query "egg" against document
72 * "Eggs") is scored/highlighted consistently with how `textMatchFilter`
73 * decided the document matches in the first place.
74 */
75 function matchStrategySuffix(
76 input: SearchTypes.ProviderSearchQuery
77 ): TokenFilterOptions | undefined {
78 return input.search_options?.match_strategy === "last"
79 ? { last_as_prefix: true }
80 : undefined
81 }
82
83 function textRank(
84 input: SearchTypes.ProviderSearchQuery,
85 plan: IndexPlan
86 ): RankBy {
87 const fields = searchableFields(input, plan)
88 const suffix = matchStrategySuffix(input)
89
90 const clauses = fields.map((path): unknown => {
91 const field = plan.fields.get(path)!
92
93 const clause = suffix
94 ? [path, "BM25", input.q!, suffix]
95 : [path, "BM25", input.q!]
96 const weight =
97 typeof field.field.searchable === "object"
98 ? field.field.searchable.weight
99 : undefined
100
101 return weight !== undefined && weight !== 1
102 ? ["Product", weight, clause]
103 : clause
104 })
105
106 return clauses.length === 1 ? clauses[0] : (["Sum", clauses] as RankBy)
107 }
108
109 const TYPO_TOLERANCE_RANK_WEIGHT = 0.01
110
111 function fuzzyMaxEditDistance(plan: IndexPlan): FuzzyEditDistanceThreshold[] {
112 // Both thresholds are validated against Cloud's floor when the index is
113 // planned, so they can be passed through as configured.
114 return [
115 {
116 min_query_chars: plan.typo_tolerance.min_word_size_for_one_typo,
117 distance: 1,
118 },
119 {
120 min_query_chars: plan.typo_tolerance.min_word_size_for_two_typos,
121 distance: 2,
122 },
123 ]
124 }
125
126 function fuzzyFields(
127 input: SearchTypes.ProviderSearchQuery,
128 plan: IndexPlan
129 ): string[] {
130 return searchableFields(input, plan).filter((path) => {
131 const schema = plan.schema[path]
132 return (
133 typeof schema === "object" && !!(schema as AttributeSchemaConfig).fuzzy
134 )
135 })
136 }
137
138 function fuzzyMatchFilter(
139 input: SearchTypes.ProviderSearchQuery,
140 plan: IndexPlan
141 ): Filter | undefined {
142 const fields = fuzzyFields(input, plan)
143 const words = (input.q ?? "").trim().split(/\s+/).filter(Boolean)
144
145 if (!fields.length || !words.length) {
146 return undefined
147 }
148
149 const maxEditDistance = fuzzyMaxEditDistance(plan)
150 const wordClauses = words.map((word): Filter => {
151 const fieldClauses = fields.map(
152 (path): Filter => [
153 path,
154 "Fuzzy",
155 word,
156 { max_edit_distance: maxEditDistance, case_sensitive: false },
157 ]
158 )
159 return mergeFilters(fieldClauses, "Or")!
160 })
161
162 const combinator =
163 input.search_options?.match_strategy === "any" ? "Or" : "And"
164 return mergeFilters(wordClauses, combinator)
165 }
166
167 function boostWithTypoTolerance(
168 input: SearchTypes.ProviderSearchQuery,
169 plan: IndexPlan,
170 rankBy: RankBy
171 ): RankBy {
172 const fuzzy = fuzzyMatchFilter(input, plan)
173 if (!fuzzy) {
174 return rankBy
175 }
176
177 return [
178 "Sum",
179 [rankBy, ["Product", TYPO_TOLERANCE_RANK_WEIGHT, fuzzy]],
180 ] as RankBy
181 }
182
183 export function buildQueryFilters(
184 input: SearchTypes.ProviderSearchQuery,
185 plan: IndexPlan
186 ): Filter | undefined {
187 const semanticRatio = vectorSemanticRatio(input)
188 const includeTextMatch = !input.search_options?.vector || semanticRatio === 0
189 const text = includeTextMatch
190 ? textMatchFilter(
191 input.q,
192 input.q ? searchableFields(input, plan) : [],
193 input.search_options?.match_strategy
194 )
195 : undefined
196 const match =
197 includeTextMatch && applyTypoTolerance(input, plan)
198 ? mergeFilters([text, fuzzyMatchFilter(input, plan)], "Or")
199 : text
200
201 return mergeFilters([toSearchFilter(input.filters, plan), match])
202 }
203
204 const DEFAULT_HIGHLIGHT_PRE_TAG = "<mark>"
205 const DEFAULT_HIGHLIGHT_POST_TAG = "</mark>"
206 const DEFAULT_HIGHLIGHT_FRAGMENT_LIMIT = 1
207 const SNIPPET_HIGHLIGHT_FRAGMENT_LIMIT = 3
208
209 function hasTextQuery(input: SearchTypes.ProviderSearchQuery): boolean {
210 return !!input.q?.trim()
211 }
212
213 function applyTypoTolerance(
214 input: SearchTypes.ProviderSearchQuery,
215 plan: IndexPlan
216 ): boolean {
217 return (
218 !!input.search_options?.typo_tolerance &&
219 hasTextQuery(input) &&
220 fuzzyFields(input, plan).length > 0
221 )
222 }
223
224 function resolveHighlightOptions(
225 input: SearchTypes.ProviderSearchQuery,
226 plan: IndexPlan
227 ): SearchTypes.SearchHighlightOptions | undefined {
228 const highlight = input.search_options?.highlight
229 if (!highlight || !hasTextQuery(input)) {
230 return undefined
231 }
232
233 if (highlight === true) {
234 return { fields: searchableFields(input, plan) }
235 }
236
237 return highlight
238 }
239
240 function buildHighlightPlan(
241 input: SearchTypes.ProviderSearchQuery,
242 plan: IndexPlan,
243 highlight: SearchTypes.SearchHighlightOptions
244 ): { compute_attributes: ComputeAttributes; highlight: HighlightPlan } {
245 if (!highlight.fields.length) {
246 fail("Medusa search highlighting requires at least one field")
247 }
248
249 const snippet = !!highlight.snippet
250 const computeAttributes: ComputeAttributes = {}
251 const suffix = matchStrategySuffix(input)
252 const rankFragmentsBy = suffix
253 ? ["$fragment", "BM25", input.q!, suffix]
254 : ["$fragment", "BM25", input.q!]
255
256 const fields = highlight.fields.map((path, index) => {
257 const field = plan.fields.get(path)
258 if (!field || !isSearchable(field.field)) {
259 fail(
260 `Search index "${input.index.name}" cannot highlight field "${path}" — it is not searchable`
261 )
262 }
263
264 const key = `__medusa_highlight_${index}__`
265 computeAttributes[key] = [
266 "Highlight",
267 path,
268 {
269 fragment_by: snippet ? "sentence" : "none",
270 rank_fragments_by: rankFragmentsBy,
271 fragment_limit: snippet
272 ? SNIPPET_HIGHLIGHT_FRAGMENT_LIMIT
273 : DEFAULT_HIGHLIGHT_FRAGMENT_LIMIT,
274 include_offsets: "utf-16",
275 },
276 ]
277 return { path, key }
278 })
279
280 return {
281 compute_attributes: computeAttributes,
282 highlight: {
283 pre_tag: highlight.pre_tag ?? DEFAULT_HIGHLIGHT_PRE_TAG,
284 post_tag: highlight.post_tag ?? DEFAULT_HIGHLIGHT_POST_TAG,
285 fields,
286 },
287 }
288 }
289
290 /**
291 * Applies `pre_tag`/`post_tag` markup around a fragment's matched ranges.
292 * Offsets come back as `utf-16` (see `buildHighlightPlan`) so they line up
293 * with JS string indices without extra decoding.
294 */
295 function tagFragment(
296 fragment: HighlightFragment,
297 preTag: string,
298 postTag: string
299 ): string {
300 const ranges = [...(fragment.match_ranges ?? [])].sort((a, b) => b[0] - a[0])
301 let text = fragment.text
302 for (const [start, end] of ranges) {
303 text =
304 text.slice(0, start) +
305 preTag +
306 text.slice(start, end) +
307 postTag +
308 text.slice(end)
309 }
310 return text
311 }
312
313 export function parseHighlights(
314 row: Row,
315 highlight: HighlightPlan | undefined
316 ): Record<string, string[]> | undefined {
317 if (!highlight) {
318 return undefined
319 }
320
321 const result: Record<string, string[]> = {}
322 for (const { path, key } of highlight.fields) {
323 const fragments = row[key] as HighlightFragment[] | undefined
324 if (fragments?.length) {
325 result[path] = fragments.map((fragment) =>
326 tagFragment(fragment, highlight.pre_tag, highlight.post_tag)
327 )
328 }
329 }
330
331 return Object.keys(result).length ? result : undefined
332 }
333
334 function attributeRank(
335 input: SearchTypes.ProviderSearchQuery
336 ): RankBy | undefined {
337 const entries = Object.entries(input.pagination?.order ?? {}).filter(
338 ([path]) => path !== "_score"
339 )
340 if (!entries.length) {
341 return undefined
342 }
343
344 const ranks = entries.map(
345 ([path, direction]) =>
346 [path, direction.toLowerCase()] as [string, "asc" | "desc"]
347 )
348 return ranks.length === 1 ? ranks[0] : ranks
349 }
350
351 function vectorSemanticRatio(input: SearchTypes.ProviderSearchQuery): number {
352 const vector = input.search_options?.vector
353 if (!vector) {
354 return 0
355 }
356
357 if (vector.semantic_ratio !== undefined) {
358 return vector.semantic_ratio
359 }
360
361 return input.q ? 0.5 : 1
362 }
363
364 function resolveVectorField(
365 vector: NonNullable<SearchTypes.SearchOptions["vector"]>,
366 plan: IndexPlan,
367 indexName: string
368 ): string {
369 if (vector.field) {
370 const planned = plan.fields.get(vector.field)
371 if (!planned || planned.field.type !== "vector") {
372 fail(
373 `Vector search field "${vector.field}" is not a vector field on search index "${indexName}"`
374 )
375 }
376 return vector.field
377 }
378
379 if (plan.vectors.length === 1) {
380 return plan.vectors[0]
381 }
382
383 fail(
384 plan.vectors.length
385 ? `search_options.vector.field is required when the index has more than one vector field`
386 : `search_options.vector requires a vector field on search index "${indexName}"`
387 )
388 }
389
390 function vectorRank(
391 input: SearchTypes.ProviderSearchQuery,
392 plan: IndexPlan
393 ): RankBy {
394 const vector = input.search_options!.vector!
395 const field = resolveVectorField(vector, plan, input.index.name)
396 const planned = plan.fields.get(field)!
397
398 if (vector.value && vector.query) {
399 fail(
400 "search_options.vector.value and search_options.vector.query are mutually exclusive"
401 )
402 }
403
404 if (vector.value) {
405 if (planned.dimensions && vector.value.length !== planned.dimensions) {
406 fail(
407 `Vector value for "${field}" expected ${planned.dimensions} dimensions, got ${vector.value.length}`
408 )
409 }
410 return [field, "ANN", vector.value] as RankBy
411 }
412
413 const text = vector.query
414 if (!text) {
415 fail(
416 "Vector search requires search_options.vector.value or search_options.vector.query"
417 )
418 }
419
420 if (!planned.embed) {
421 fail(
422 `search_options.vector.query requires vector field "${field}" to declare "embed"`
423 )
424 }
425
426 return [field, "ANN", ["Embed", text]] as RankBy
427 }
428
429 export function buildQueryPlan(
430 input: SearchTypes.ProviderSearchQuery,
431 plan: IndexPlan
432 ): QueryPlan {
433 const options = input.search_options ?? {}
434 const skip = input.pagination?.skip ?? 0
435 const take = input.pagination?.take ?? 20
436
437 if (input.pagination?.cursor !== undefined) {
438 fail("The Medusa search provider does not support cursor pagination")
439 }
440 if (skip + take > 10000) {
441 fail("Medusa search can return at most 10,000 results per query")
442 }
443 if (options.locales?.length) {
444 fail(
445 "Configure Medusa search full-text language on index fields, not per query"
446 )
447 }
448 if (options.min_score !== undefined) {
449 fail("Medusa search min_score is not implemented by this provider yet")
450 }
451
452 const ordered = attributeRank(input)
453 let rankBy: RankBy
454
455 if (options.vector) {
456 if (ordered) {
457 fail("Vector search cannot also order by an attribute")
458 }
459 rankBy = vectorRank(input, plan)
460 const semanticRatio = vectorSemanticRatio(input)
461 if (input.q && semanticRatio < 1) {
462 let text = textRank(input, plan)
463 if (applyTypoTolerance(input, plan)) {
464 text = boostWithTypoTolerance(input, plan, text)
465 }
466 rankBy =
467 semanticRatio === 0
468 ? text
469 : ([
470 "Sum",
471 [
472 ["Product", 1 - semanticRatio, text],
473 ["Product", semanticRatio, rankBy],
474 ],
475 ] as RankBy)
476 }
477 } else if (input.q) {
478 // Text matching is a filter (ContainsAllTokens). Attribute order is a
479 // hard sort over those matches. Soft BM25+attribute boosting exists in
480 // the engine but is not what pagination.order means.
481 if (ordered) {
482 rankBy = ordered
483 } else {
484 rankBy = textRank(input, plan)
485 if (applyTypoTolerance(input, plan)) {
486 rankBy = boostWithTypoTolerance(input, plan, rankBy)
487 }
488 }
489 } else {
490 rankBy = ordered ?? (["id", "asc"] as RankBy)
491 }
492
493 let limit: number | Limit = skip + take
494 const distinct = options.distinct ?? input.index.settings.distinct_attribute
495 if (distinct) {
496 const planned = plan.fields.get(distinct)
497 if (!planned) {
498 fail(
499 `Cannot deduplicate search index "${input.index.name}" by unknown field "${distinct}"`
500 )
501 }
502 if (planned.is_array || planned.field.type === "vector") {
503 fail(`The Medusa search provider cannot deduplicate by "${distinct}"`)
504 }
505 limit = {
506 total: skip + take,
507 per: { attributes: [distinct], limit: 1 },
508 }
509 }
510
511 const highlight = resolveHighlightOptions(input, plan)
512 const highlightPlan = highlight
513 ? buildHighlightPlan(input, plan, highlight)
514 : undefined
515
516 return {
517 query: {
518 rank_by: rankBy,
519 filters: buildQueryFilters(input, plan),
520 include_attributes: input.attributes_to_retrieve,
521 limit,
522 compute_attributes: highlightPlan?.compute_attributes,
523 },
524 skip,
525 take,
526 options: providerOptions(input),
527 highlight: highlightPlan?.highlight,
528 distinct,
529 }
530 }