1 import { SearchTypes } from "@medusajs/framework/types"
2 import { Modules } from "@medusajs/framework/utils"
3 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
4 import {
5 baseProducts,
6 dataset,
7 productIndex,
8 removeProduct,
9 resetDataset,
10 setOnBulkSeedStart,
11 touchProduct,
12 } from "../__fixtures__/product-index"
13
14 jest.setTimeout(120000)
15
16 type SearchService = SearchTypes.ISearchModuleService
17
18 // The startup hook seeds indexes, so the lifecycle tests re-run it to simulate
19 // a boot.
20 const boot = (service: SearchService) =>
21 (service as any).onApplicationStart_() as Promise<void>
22
23 const migrate = async (service: SearchService) =>
24 service.executeIndexMigrationPlan(await service.createIndexMigrationPlan())
25
26 // Every version — including the first — gets its own physical table, so a
27 // raw provider call (rather than one going through the module service, which
28 // resolves this itself) has to look up whichever version is currently active.
29 const activeVersion = async (service: SearchService, name: string) => {
30 const [record] = await (service as any).context_.indexService.list({ name })
31 const [version] = await (service as any).context_.versionService.list({
32 search_index_id: record.id,
33 version: record.active_version,
34 })
35 return version
36 }
37
38 const activePhysicalName = async (service: SearchService, name: string) =>
39 (await activeVersion(service, name)).physical_name
40
41 // Simulates schema drift: the active version's `definition_hash` now lives on
42 // `SearchIndexVersion`, not `SearchIndex`.
43 const staleActiveVersion = async (service: SearchService, name: string) => {
44 const version = await activeVersion(service, name)
45 await (service as any).context_.versionService.update({
46 selector: { id: version.id },
47 data: { definition_hash: "stale" },
48 })
49 }
50
51 // The provider itself, for the write paths the module only reaches through
52 // events (delete-by-filter) and for catalog assertions.
53 const provider = (service: SearchService) =>
54 (service as any).context_.providers.retrieve("search-postgres")
55
56 const ids = (result: SearchTypes.SearchResult) =>
57 result.hits.map((hit) => hit.id)
58
59 const reseed = async (service: SearchService) => {
60 resetDataset()
61 const p = provider(service)
62 await p.clearIndex({ index: await activePhysicalName(service, "product") })
63 await service.upsertDocuments({
64 index: "product",
65 documents: dataset.products,
66 })
67 }
68
69 moduleIntegrationTestRunner<SearchService>({
70 moduleName: Modules.SEARCH,
71 resolve: __dirname + "/../../../../search",
72 // The schema spans two packages: the module owns `search_index`, the provider
73 // owns its catalog and the search extensions.
74 pathToMigrations: [
75 __dirname + "/../../../../search/src/migrations",
76 __dirname + "/../../src/migrations",
77 ],
78 moduleOptions: {
79 providers: [
80 {
81 resolve: require.resolve("../../src"),
82 id: "postgres",
83 },
84 ],
85 indexes: [productIndex],
86 },
87 hooks: {
88 beforeModuleInit: async () => {
89 resetDataset()
90 },
91 // Indexes are created by `db:migrate`, never by the application. The
92 // startup hook has already run by the time this fires, so migrate and boot
93 // again — which is the order a real deploy uses.
94 afterModuleInit: async (_app: any, service: SearchService) => {
95 await migrate(service)
96 await boot(service)
97 },
98 },
99 testSuite: ({ service }) =>
100 describe("Postgres Search Provider", () => {
101 describe("seeding and counts", () => {
102 it("seeds every document at startup", async () => {
103 const result = await service.search({
104 entity: "product",
105 fields: ["id", "title"],
106 })
107
108 expect(result.metadata.count).toBe(3)
109 expect(ids(result).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
110 })
111
112 it("tracks the document count in the catalog", async () => {
113 await reseed(service)
114
115 const [info] = await provider(service).listIndexes()
116 expect(info.document_count).toBe(3)
117 })
118 })
119
120 describe("keyword search", () => {
121 beforeEach(async () => reseed(service))
122
123 it("ranks and filters by the query", async () => {
124 const result = await service.search({
125 entity: "product",
126 fields: ["id", "title"],
127 filters: { q: "shoe" },
128 search_options: { include_score: true },
129 })
130
131 expect(ids(result)).toEqual(["prod_1"])
132 expect(result.hits[0].score).toBeGreaterThan(0)
133 expect(result.metadata.count).toBe(1)
134 })
135
136 it("ANDs terms by default and ORs them with match_strategy any", async () => {
137 const all = await service.search({
138 entity: "product",
139 fields: ["id"],
140 filters: { q: "shoe hat" },
141 })
142 expect(all.metadata.count).toBe(0)
143
144 const any = await service.search({
145 entity: "product",
146 fields: ["id"],
147 filters: { q: "shoe hat" },
148 search_options: { match_strategy: "any" },
149 })
150 expect(ids(any).sort()).toEqual(["prod_1", "prod_3"])
151 })
152
153 it("prefixes the last term with match_strategy last", async () => {
154 const prefix = await service.search({
155 entity: "product",
156 fields: ["id"],
157 filters: { q: "sho" },
158 search_options: { match_strategy: "last" },
159 })
160 expect(ids(prefix)).toEqual(["prod_1"])
161
162 const twoTerms = await service.search({
163 entity: "product",
164 fields: ["id"],
165 filters: { q: "red sho" },
166 search_options: { match_strategy: "last" },
167 })
168 expect(ids(twoTerms)).toEqual(["prod_1"])
169
170 const exact = await service.search({
171 entity: "product",
172 fields: ["id"],
173 filters: { q: "sho" },
174 })
175 expect(ids(exact)).toEqual([])
176 })
177
178 it("tolerates typos through trigram word similarity", async () => {
179 const result = await service.search({
180 entity: "product",
181 fields: ["id"],
182 filters: { q: "runing" },
183 search_options: { typo_tolerance: true },
184 })
185
186 expect(ids(result).sort()).toEqual(["prod_1", "prod_2"])
187 })
188
189 it("ignores highlighting and typo tolerance when there is no text query", async () => {
190 const result = await service.search({
191 entity: "product",
192 fields: ["id"],
193 filters: { status: "published" },
194 search_options: { highlight: true, typo_tolerance: true },
195 })
196
197 expect(ids(result).sort()).toEqual(["prod_1", "prod_2"])
198 })
199
200 it("rejects vector search when the index has no vector field", async () => {
201 await expect(
202 service.search({
203 entity: "product",
204 fields: ["id"],
205 search_options: {
206 vector: { field: "embedding", value: [0.1] },
207 },
208 })
209 ).rejects.toThrow(/Unknown field "embedding"/)
210 })
211 })
212
213 describe("filters", () => {
214 beforeEach(async () => reseed(service))
215
216 it("treats equality on an array field as membership", async () => {
217 const result = await service.search({
218 entity: "product",
219 fields: ["id"],
220 filters: { tags: "sport" },
221 })
222
223 expect(ids(result).sort()).toEqual(["prod_1", "prod_2"])
224 })
225
226 it("matches numeric array elements", async () => {
227 const result = await service.search({
228 entity: "product",
229 fields: ["id"],
230 filters: { sizes: { $in: [41, 38] } },
231 })
232
233 expect(ids(result).sort()).toEqual(["prod_1", "prod_2"])
234 })
235
236 it("keeps $exists scoped to its own field in a conjunction", async () => {
237 const result = await service.search({
238 entity: "product",
239 fields: ["id"],
240 filters: { status: "published", deleted_at: { $exists: false } },
241 })
242
243 // prod_2 is published but soft-deleted; prod_3 is not published.
244 expect(ids(result)).toEqual(["prod_1"])
245 })
246
247 it("supports $contains, nested paths, $or and $not", async () => {
248 const contains = await service.search({
249 entity: "product",
250 fields: ["id"],
251 filters: { tags: { $contains: ["shoe", "sport"] } },
252 })
253 expect(ids(contains)).toEqual(["prod_1"])
254
255 const nested = await service.search({
256 entity: "product",
257 fields: ["id"],
258 filters: { "variants.color": "red" },
259 })
260 expect(ids(nested)).toEqual(["prod_1"])
261
262 const composed = await service.search({
263 entity: "product",
264 fields: ["id"],
265 filters: {
266 $or: [{ brand: "borg" }, { min_price: { $gte: 150 } }],
267 $not: { status: "draft" },
268 },
269 })
270 expect(ids(composed)).toEqual(["prod_2"])
271 })
272
273 it("deletes by primary key without treating the id list as a Postgres array literal", async () => {
274 const physicalName = await activePhysicalName(service, "product")
275
276 await provider(service).deleteDocuments({
277 index: physicalName,
278 filters: { id: "prod_1" },
279 })
280
281 await provider(service).deleteDocuments({
282 index: physicalName,
283 filters: { id: ["prod_2", "prod_3"] },
284 })
285
286 const remaining = await service.search({
287 entity: "product",
288 fields: ["id"],
289 })
290 expect(ids(remaining)).toEqual([])
291
292 const [info] = await provider(service).listIndexes()
293 expect(info.document_count).toBe(0)
294 })
295
296 it("deletes by filter without $exists leaking across the conjunction", async () => {
297 await provider(service).deleteDocuments({
298 index: await activePhysicalName(service, "product"),
299 filters: { status: "draft", deleted_at: { $exists: false } },
300 })
301
302 const remaining = await service.search({
303 entity: "product",
304 fields: ["id"],
305 })
306
307 expect(ids(remaining).sort()).toEqual(["prod_1", "prod_2"])
308
309 const [info] = await provider(service).listIndexes()
310 expect(info.document_count).toBe(2)
311 })
312 })
313
314 describe("facets", () => {
315 beforeEach(async () => reseed(service))
316
317 it("scopes facet counts to the query matches", async () => {
318 const result = await service.search({
319 entity: "product",
320 fields: ["id"],
321 filters: { q: "running" },
322 search_options: { facets: ["brand"] },
323 })
324
325 expect(result.metadata.count).toBe(2)
326 expect(result.facets?.brand).toEqual({
327 type: "value",
328 values: expect.arrayContaining([
329 { value: "acme", count: 1 },
330 { value: "borg", count: 1 },
331 ]),
332 })
333 })
334
335 it("computes range facets alongside filters", async () => {
336 const result = await service.search({
337 entity: "product",
338 fields: ["id"],
339 filters: { status: "published" },
340 search_options: {
341 facets: [
342 {
343 field: "min_price",
344 type: "range",
345 ranges: [
346 { key: "low", to: 100 },
347 { key: "high", from: 100 },
348 ],
349 },
350 ],
351 },
352 })
353
354 expect(result.facets?.min_price).toEqual({
355 type: "range",
356 ranges: [
357 { key: "low", from: undefined, to: 100, count: 1 },
358 { key: "high", from: 100, to: undefined, count: 1 },
359 ],
360 })
361 })
362
363 it("computes stats facets", async () => {
364 const result = await service.search({
365 entity: "product",
366 fields: ["id"],
367 search_options: { facets: [{ field: "min_price", type: "stats" }] },
368 })
369
370 expect(result.facets?.min_price).toMatchObject({
371 type: "stats",
372 min: 50,
373 max: 200,
374 count: 3,
375 })
376 })
377 })
378
379 describe("ordering, min_score and distinct", () => {
380 beforeEach(async () => reseed(service))
381
382 it("orders by a field", async () => {
383 const result = await service.search({
384 entity: "product",
385 fields: ["id"],
386 pagination: { order: { min_price: "ASC" } },
387 })
388
389 expect(ids(result)).toEqual(["prod_2", "prod_1", "prod_3"])
390 })
391
392 it("keeps the requested order when min_score is set", async () => {
393 const result = await service.search({
394 entity: "product",
395 fields: ["id"],
396 filters: { q: "running" },
397 search_options: { min_score: 0.000001 },
398 pagination: { order: { title: "ASC" } },
399 })
400
401 // Blue... sorts before Red...; without the fix this came back by id.
402 expect(ids(result)).toEqual(["prod_2", "prod_1"])
403 expect(result.metadata.count).toBe(2)
404 })
405
406 it("filters out hits below min_score", async () => {
407 const result = await service.search({
408 entity: "product",
409 fields: ["id"],
410 filters: { q: "running" },
411 search_options: { min_score: 1000 },
412 })
413
414 expect(result.hits).toEqual([])
415 expect(result.metadata.count).toBe(0)
416 })
417
418 it("returns one hit per distinct value", async () => {
419 const result = await service.search({
420 entity: "product",
421 fields: ["id", "brand"],
422 search_options: { distinct: "brand" },
423 pagination: { order: { min_price: "ASC" } },
424 })
425
426 // Cheapest per brand: prod_2 (borg, 50) and prod_1 (acme, 100).
427 expect(ids(result)).toEqual(["prod_2", "prod_1"])
428 expect(result.metadata.count).toBe(2)
429 })
430 })
431
432 describe("reindexing", () => {
433 beforeEach(async () => reseed(service))
434
435 const stale = () => staleActiveVersion(service, "product")
436
437 it("survives repeated migrate + seed cycles, each building a fresh version", async () => {
438 // Two full stale → migrate → boot cycles each build a brand-new,
439 // never-before-used physical table (`product_v2`, `product_v3`, ...)
440 // and make it active in turn.
441 for (let cycle = 0; cycle < 2; cycle++) {
442 await stale()
443 await migrate(service)
444 await boot(service)
445
446 const result = await service.search({
447 entity: "product",
448 fields: ["id"],
449 })
450 expect(result.metadata.count).toBe(3)
451 }
452
453 // The latest version's table got its full-text and trigram indexes
454 // built correctly, same as the first.
455 const result = await service.search({
456 entity: "product",
457 fields: ["id"],
458 filters: { q: "shoe" },
459 })
460 expect(ids(result)).toEqual(["prod_1"])
461 })
462
463 it("catches an update that landed after the bulk pass took its snapshot", async () => {
464 setOnBulkSeedStart(() => {
465 touchProduct("prod_1", { title: "Scarlet trail shoe" })
466 })
467
468 await service.reindex()
469
470 const result = await service.search({
471 entity: "product",
472 fields: ["id", "title"],
473 filters: { q: "scarlet" },
474 })
475 expect(ids(result)).toEqual(["prod_1"])
476 })
477
478 it("catches a delete that landed after the bulk pass took its snapshot", async () => {
479 setOnBulkSeedStart(() => {
480 removeProduct("prod_1")
481 })
482
483 await service.reindex()
484
485 const result = await service.search({
486 entity: "product",
487 fields: ["id"],
488 })
489 expect(ids(result).sort()).toEqual(["prod_2", "prod_3"])
490 })
491 })
492
493 describe("vector fields", () => {
494 const vectorIndex = {
495 name: "vector_product",
496 entity: "vector_product",
497 primary_key: "id",
498 provider: "search-postgres",
499 physical_name: "vector_product_v1",
500 definition_hash: "vector-1",
501 settings: {},
502 seed: async function* () {},
503 fields: {
504 id: { type: "keyword", filterable: true },
505 title: { type: "text", searchable: true },
506 embedding: { type: "vector", dimensions: 3 },
507 },
508 } as unknown as SearchTypes.ResolvedSearchIndexDefinition
509
510 afterEach(async () => {
511 await provider(service).deleteIndex({
512 index: vectorIndex.physical_name,
513 })
514 })
515
516 it("ignores vector fields rather than refusing the index", async () => {
517 const p = provider(service)
518
519 await p.upsertIndex({ index: vectorIndex })
520 await p.upsertDocuments({
521 index: vectorIndex.physical_name,
522 definition: vectorIndex,
523 documents: [
524 {
525 id: "vec_1",
526 title: "Red running shoe",
527 embedding: [0.1, 0.2, 0.3],
528 },
529 ],
530 })
531
532 const result = await p.search({
533 index: vectorIndex,
534 q: "shoe",
535 attributes_to_retrieve: ["id"],
536 })
537 expect(ids(result)).toEqual(["vec_1"])
538
539 const columns = (await p.manager_.execute(
540 `SELECT "column_name" FROM information_schema.columns WHERE "table_name" = ?`,
541 ["search_pg_vector_product_v1"]
542 )) as { column_name: string }[]
543
544 expect(columns.map((column) => column.column_name)).not.toContain(
545 "v_embedding"
546 )
547 })
548 })
549 }),
550 })