|
1
|
import { Logger, SearchTypes } from "@medusajs/framework/types" |
|
2
|
import { |
|
3
|
AbstractSearchProviderService, |
|
4
|
MedusaError, |
|
5
|
} from "@medusajs/framework/utils" |
|
6
|
import { |
|
7
|
buildFacetQueries, |
|
8
|
buildIndexPlan, |
|
9
|
buildQueryPlan, |
|
10
|
fromSearchDocument, |
|
11
|
MedusaSearchClient, |
|
12
|
CloudServiceError, |
|
13
|
MedusaSearchProviderOptions, |
|
14
|
ResolvedMedusaSearchProviderOptions, |
|
15
|
parseFacetResults, |
|
16
|
parseHighlights, |
|
17
|
toSearchDocument, |
|
18
|
toSearchFilter, |
|
19
|
resolveMedusaSearchOptions, |
|
20
|
type FacetQuery, |
|
21
|
type IndexQuery, |
|
22
|
type IndexMultiQueryResponse, |
|
23
|
type IndexQueryResult, |
|
24
|
type QueryPlan, |
|
25
|
type Row, |
|
26
|
} from "../utils" |
|
27
|
|
|
28
|
type InjectedDependencies = { |
|
29
|
logger?: Logger |
|
30
|
} |
|
31
|
|
|
32
|
const MAX_WRITE_BYTES = 480 * 1024 * 1024 |
|
33
|
const MAX_MULTI_QUERIES = 16 |
|
34
|
const MAX_AGGREGATION_GROUPS = 10000 |
|
35
|
|
|
36
|
type BuiltMultiQuery = { |
|
37
|
input: SearchTypes.ProviderSearchQuery |
|
38
|
base: QueryPlan |
|
39
|
facets: FacetQuery[] |
|
40
|
queries: IndexQuery[] |
|
41
|
hitsIndex: number |
|
42
|
countIndex: number |
|
43
|
facetOffset: number |
|
44
|
} |
|
45
|
|
|
46
|
export class MedusaSearchService extends AbstractSearchProviderService { |
|
47
|
static identifier = "search-medusa" |
|
48
|
|
|
49
|
protected readonly logger_?: Logger |
|
50
|
protected readonly options_: ResolvedMedusaSearchProviderOptions |
|
51
|
protected readonly client_: MedusaSearchClient |
|
52
|
|
|
53
|
constructor( |
|
54
|
{ logger }: InjectedDependencies = {}, |
|
55
|
options: MedusaSearchProviderOptions |
|
56
|
) { |
|
57
|
super() |
|
58
|
|
|
59
|
const resolvedOptions = resolveMedusaSearchOptions(options) |
|
60
|
|
|
61
|
this.logger_ = logger |
|
62
|
this.options_ = resolvedOptions |
|
63
|
this.client_ = new MedusaSearchClient(resolvedOptions, { |
|
64
|
fetchImpl: resolvedOptions.fetch, |
|
65
|
}) |
|
66
|
} |
|
67
|
|
|
68
|
/** |
|
69
|
* Cloud scopes storage from the environment handle. The provider |
|
70
|
* passes Medusa physical index names unchanged. |
|
71
|
*/ |
|
72
|
protected index(name: string) { |
|
73
|
return this.client_.index(name) |
|
74
|
} |
|
75
|
|
|
76
|
async upsertIndex({ |
|
77
|
index, |
|
78
|
}: { |
|
79
|
index: SearchTypes.ResolvedSearchIndexDefinition |
|
80
|
}): Promise<SearchTypes.SearchTask> { |
|
81
|
const plan = buildIndexPlan(index) |
|
82
|
const remote = this.index(index.physical_name) |
|
83
|
|
|
84
|
// Migration is the only place that reconciles schema / existence. Runtime |
|
85
|
// writes and clears assume the index is already there. |
|
86
|
// |
|
87
|
// Every version gets its own namespace (see `versionPhysicalName` in the |
|
88
|
// Search Module), so this only ever finds a namespace that doesn't exist |
|
89
|
// yet, or — on a migration re-run after a crash — one that was already |
|
90
|
// created with this same, unchanging schema. Medusa can't apply a |
|
91
|
// schema change in place anyway, which is exactly why a new namespace is |
|
92
|
// used instead of trying to. |
|
93
|
try { |
|
94
|
await remote.metadata() |
|
95
|
} catch (error) { |
|
96
|
if (!(error instanceof CloudServiceError && error.isNotFound)) { |
|
97
|
throw error |
|
98
|
} |
|
99
|
|
|
100
|
await this.client_.createIndex({ |
|
101
|
name: index.physical_name, |
|
102
|
schema: plan.schema, |
|
103
|
distance_metric: plan.options.distance_metric, |
|
104
|
}) |
|
105
|
return this.task(index.physical_name) |
|
106
|
} |
|
107
|
|
|
108
|
await remote.updateSchema({ schema: plan.schema }) |
|
109
|
return this.task(index.physical_name) |
|
110
|
} |
|
111
|
|
|
112
|
async deleteIndex({ |
|
113
|
index, |
|
114
|
}: { |
|
115
|
index: string |
|
116
|
}): Promise<SearchTypes.SearchTask> { |
|
117
|
try { |
|
118
|
await this.index(index).deleteAll() |
|
119
|
} catch (error) { |
|
120
|
if (!(error instanceof CloudServiceError && error.isNotFound)) { |
|
121
|
throw error |
|
122
|
} |
|
123
|
} |
|
124
|
return this.task(index) |
|
125
|
} |
|
126
|
|
|
127
|
/** |
|
128
|
* Lists indexes for this Cloud environment. Document counts come from |
|
129
|
* metadata (`approx_row_count`) rather than a Count aggregation per index. |
|
130
|
*/ |
|
131
|
async listIndexes(): Promise<SearchTypes.SearchIndexInfo[]> { |
|
132
|
const entries: { id: string }[] = [] |
|
133
|
|
|
134
|
for await (const entry of this.client_.indexes()) { |
|
135
|
entries.push(entry) |
|
136
|
} |
|
137
|
|
|
138
|
return await Promise.all( |
|
139
|
entries.map(async (entry) => { |
|
140
|
const metadata = await this.client_.index(entry.id).metadata() |
|
141
|
|
|
142
|
return { |
|
143
|
name: entry.id, |
|
144
|
provider: MedusaSearchService.identifier, |
|
145
|
document_count: Number(metadata.approx_row_count ?? 0), |
|
146
|
created_at: new Date(metadata.created_at), |
|
147
|
updated_at: new Date(metadata.updated_at), |
|
148
|
} |
|
149
|
}) |
|
150
|
) |
|
151
|
} |
|
152
|
|
|
153
|
async upsertDocuments({ |
|
154
|
index, |
|
155
|
definition, |
|
156
|
documents, |
|
157
|
}: { |
|
158
|
index: string |
|
159
|
definition: SearchTypes.ResolvedSearchIndexDefinition |
|
160
|
documents: SearchTypes.SearchDocument[] |
|
161
|
}): Promise<SearchTypes.SearchTask> { |
|
162
|
const plan = buildIndexPlan(definition) |
|
163
|
const rows = documents.map((document) => toSearchDocument(document, plan)) |
|
164
|
const remote = this.index(index) |
|
165
|
|
|
166
|
for (const chunk of this.chunkRows(rows)) { |
|
167
|
await remote.write({ |
|
168
|
upsert_rows: chunk, |
|
169
|
schema: plan.schema, |
|
170
|
distance_metric: plan.options.distance_metric, |
|
171
|
}) |
|
172
|
} |
|
173
|
|
|
174
|
return this.task(index) |
|
175
|
} |
|
176
|
|
|
177
|
async deleteDocuments({ |
|
178
|
index, |
|
179
|
filters, |
|
180
|
}: SearchTypes.SearchDeleteDocumentsInput): Promise<SearchTypes.SearchTask> { |
|
181
|
const compiled = toSearchFilter(filters) |
|
182
|
if (!compiled) { |
|
183
|
throw new MedusaError( |
|
184
|
MedusaError.Types.INVALID_ARGUMENT, |
|
185
|
"Deleting Medusa search documents requires filters" |
|
186
|
) |
|
187
|
} |
|
188
|
|
|
189
|
let remaining = true |
|
190
|
while (remaining) { |
|
191
|
const response = await this.index(index).write({ |
|
192
|
delete_by_filter: compiled, |
|
193
|
delete_by_filter_allow_partial: true, |
|
194
|
}) |
|
195
|
remaining = response.rows_remaining === true |
|
196
|
} |
|
197
|
|
|
198
|
return this.task(index) |
|
199
|
} |
|
200
|
|
|
201
|
async clearIndex({ |
|
202
|
index, |
|
203
|
}: { |
|
204
|
index: string |
|
205
|
}): Promise<SearchTypes.SearchTask> { |
|
206
|
try { |
|
207
|
let remaining = true |
|
208
|
while (remaining) { |
|
209
|
const response = await this.index(index).write({ |
|
210
|
delete_by_filter: ["id", "NotEq", null], |
|
211
|
delete_by_filter_allow_partial: true, |
|
212
|
}) |
|
213
|
remaining = response.rows_remaining === true |
|
214
|
} |
|
215
|
} catch (error) { |
|
216
|
if (!(error instanceof CloudServiceError && error.isNotFound)) { |
|
217
|
throw error |
|
218
|
} |
|
219
|
} |
|
220
|
|
|
221
|
return this.task(index) |
|
222
|
} |
|
223
|
|
|
224
|
async search( |
|
225
|
input: SearchTypes.ProviderSearchQuery |
|
226
|
): Promise<SearchTypes.SearchResult> { |
|
227
|
const [result] = await this.searchMany([input]) |
|
228
|
return result |
|
229
|
} |
|
230
|
|
|
231
|
async searchMany( |
|
232
|
inputs: SearchTypes.ProviderSearchQuery[] |
|
233
|
): Promise<SearchTypes.SearchResult[]> { |
|
234
|
if (!inputs.length) { |
|
235
|
return [] |
|
236
|
} |
|
237
|
|
|
238
|
const built = inputs.map((input) => this.buildMultiQuery(input)) |
|
239
|
const results: SearchTypes.SearchResult[] = new Array(inputs.length) |
|
240
|
const emptyResponse: IndexMultiQueryResponse = { |
|
241
|
results: [], |
|
242
|
performance: {}, |
|
243
|
} |
|
244
|
|
|
245
|
const groups = new Map<string, { item: BuiltMultiQuery; index: number }[]>() |
|
246
|
|
|
247
|
built.forEach((item, index) => { |
|
248
|
if (!item.queries.length) { |
|
249
|
results[index] = this.parseMultiQueryResult(emptyResponse, item) |
|
250
|
return |
|
251
|
} |
|
252
|
|
|
253
|
const key = `${item.input.index.physical_name}::${ |
|
254
|
item.base.options.consistency ?? "" |
|
255
|
}` |
|
256
|
const group = groups.get(key) |
|
257
|
if (group) { |
|
258
|
group.push({ item, index }) |
|
259
|
return |
|
260
|
} |
|
261
|
groups.set(key, [{ item, index }]) |
|
262
|
}) |
|
263
|
|
|
264
|
await Promise.all( |
|
265
|
[...groups].map(async ([, group]) => { |
|
266
|
const chunks: { item: BuiltMultiQuery; index: number }[][] = [] |
|
267
|
let current: { item: BuiltMultiQuery; index: number }[] = [] |
|
268
|
let currentCount = 0 |
|
269
|
|
|
270
|
for (const entry of group) { |
|
271
|
const size = entry.item.queries.length |
|
272
|
if (current.length && currentCount + size > MAX_MULTI_QUERIES) { |
|
273
|
chunks.push(current) |
|
274
|
current = [] |
|
275
|
currentCount = 0 |
|
276
|
} |
|
277
|
current.push(entry) |
|
278
|
currentCount += size |
|
279
|
} |
|
280
|
|
|
281
|
if (current.length) { |
|
282
|
chunks.push(current) |
|
283
|
} |
|
284
|
|
|
285
|
const physicalName = group[0].item.input.index.physical_name |
|
286
|
const consistency = group[0].item.base.options.consistency |
|
287
|
|
|
288
|
await Promise.all( |
|
289
|
chunks.map(async (chunk) => { |
|
290
|
const queries = chunk.flatMap((entry) => entry.item.queries) |
|
291
|
const response = await this.index(physicalName).multiQuery({ |
|
292
|
queries, |
|
293
|
consistency: consistency ? { level: consistency } : undefined, |
|
294
|
}) |
|
295
|
|
|
296
|
let offset = 0 |
|
297
|
for (const entry of chunk) { |
|
298
|
const sliced: IndexMultiQueryResponse = { |
|
299
|
results: response.results.slice( |
|
300
|
offset, |
|
301
|
offset + entry.item.queries.length |
|
302
|
), |
|
303
|
billing: response.billing, |
|
304
|
performance: response.performance, |
|
305
|
} |
|
306
|
offset += entry.item.queries.length |
|
307
|
results[entry.index] = this.parseMultiQueryResult( |
|
308
|
sliced, |
|
309
|
entry.item |
|
310
|
) |
|
311
|
} |
|
312
|
}) |
|
313
|
) |
|
314
|
}) |
|
315
|
) |
|
316
|
|
|
317
|
return results |
|
318
|
} |
|
319
|
|
|
320
|
protected buildMultiQuery( |
|
321
|
input: SearchTypes.ProviderSearchQuery |
|
322
|
): BuiltMultiQuery { |
|
323
|
const plan = buildIndexPlan(input.index) |
|
324
|
const base = buildQueryPlan(input, plan) |
|
325
|
const facets = buildFacetQueries(input, plan) |
|
326
|
const includeHits = (input.pagination?.take ?? 20) > 0 |
|
327
|
const includeCount = input.search_options?.count !== "none" |
|
328
|
const queries: IndexQuery[] = [] |
|
329
|
const hitsIndex = includeHits ? queries.length : -1 |
|
330
|
|
|
331
|
if (includeHits) { |
|
332
|
queries.push(base.query) |
|
333
|
} |
|
334
|
|
|
335
|
const countIndex = includeCount ? queries.length : -1 |
|
336
|
|
|
337
|
if (includeCount) { |
|
338
|
// Cloud has no distinct count, so a deduplicated total is the number of |
|
339
|
// groups. Past MAX_AGGREGATION_GROUPS it is a lower bound. |
|
340
|
queries.push( |
|
341
|
base.distinct |
|
342
|
? { |
|
343
|
aggregate_by: { count: ["Count"] }, |
|
344
|
group_by: [base.distinct], |
|
345
|
filters: base.query.filters, |
|
346
|
top_k: MAX_AGGREGATION_GROUPS, |
|
347
|
} |
|
348
|
: { |
|
349
|
aggregate_by: { count: ["Count"] }, |
|
350
|
filters: base.query.filters, |
|
351
|
} |
|
352
|
) |
|
353
|
} |
|
354
|
|
|
355
|
const facetOffset = queries.length |
|
356
|
queries.push(...facets.map((facet) => facet.query)) |
|
357
|
|
|
358
|
if (queries.length > MAX_MULTI_QUERIES) { |
|
359
|
throw new MedusaError( |
|
360
|
MedusaError.Types.NOT_ALLOWED, |
|
361
|
`Medusa search accepts at most ${MAX_MULTI_QUERIES} queries per multi-query; this search needs ${queries.length}` |
|
362
|
) |
|
363
|
} |
|
364
|
|
|
365
|
return { |
|
366
|
input, |
|
367
|
base, |
|
368
|
facets, |
|
369
|
queries, |
|
370
|
hitsIndex, |
|
371
|
countIndex, |
|
372
|
facetOffset, |
|
373
|
} |
|
374
|
} |
|
375
|
|
|
376
|
protected parseMultiQueryResult( |
|
377
|
response: IndexMultiQueryResponse, |
|
378
|
built: BuiltMultiQuery |
|
379
|
): SearchTypes.SearchResult { |
|
380
|
const { input, base, facets, hitsIndex, countIndex, facetOffset } = built |
|
381
|
const hitResult = hitsIndex === -1 ? undefined : response.results[hitsIndex] |
|
382
|
const rows = (hitResult?.rows ?? []).slice(base.skip, base.skip + base.take) |
|
383
|
const parsedFacets = parseFacetResults( |
|
384
|
facets, |
|
385
|
response.results.slice(facetOffset) |
|
386
|
) |
|
387
|
|
|
388
|
return { |
|
389
|
hits: rows.map((row) => ({ |
|
390
|
id: String(row.id), |
|
391
|
score: input.search_options?.include_score ? row.$dist : undefined, |
|
392
|
document: fromSearchDocument(row as Row, input.attributes_to_retrieve), |
|
393
|
highlights: parseHighlights(row as Row, base.highlight), |
|
394
|
})), |
|
395
|
facets: parsedFacets, |
|
396
|
metadata: { |
|
397
|
skip: base.skip, |
|
398
|
take: base.take, |
|
399
|
count: this.parseCount(response.results[countIndex], built), |
|
400
|
query: input.q, |
|
401
|
processing_time_ms: response.performance.server_total_ms, |
|
402
|
}, |
|
403
|
provider_metadata: { |
|
404
|
billing: response.billing, |
|
405
|
performance: response.performance, |
|
406
|
}, |
|
407
|
} |
|
408
|
} |
|
409
|
|
|
410
|
protected parseCount( |
|
411
|
result: IndexQueryResult | undefined, |
|
412
|
built: BuiltMultiQuery |
|
413
|
): number | null { |
|
414
|
if (built.countIndex === -1) { |
|
415
|
return null |
|
416
|
} |
|
417
|
if (built.base.distinct) { |
|
418
|
return result?.aggregation_groups?.length ?? 0 |
|
419
|
} |
|
420
|
return Number(result?.aggregations?.count ?? 0) |
|
421
|
} |
|
422
|
|
|
423
|
protected chunkRows(rows: Row[]): Row[][] { |
|
424
|
const chunks: Row[][] = [] |
|
425
|
let chunk: Row[] = [] |
|
426
|
let bytes = 0 |
|
427
|
|
|
428
|
for (const row of rows) { |
|
429
|
const rowBytes = Buffer.byteLength(JSON.stringify(row), "utf8") |
|
430
|
if (rowBytes > MAX_WRITE_BYTES) { |
|
431
|
throw new MedusaError( |
|
432
|
MedusaError.Types.INVALID_DATA, |
|
433
|
`A Medusa search document exceeds the ${MAX_WRITE_BYTES}-byte provider limit` |
|
434
|
) |
|
435
|
} |
|
436
|
if (chunk.length && bytes + rowBytes > MAX_WRITE_BYTES) { |
|
437
|
chunks.push(chunk) |
|
438
|
chunk = [] |
|
439
|
bytes = 0 |
|
440
|
} |
|
441
|
chunk.push(row) |
|
442
|
bytes += rowBytes |
|
443
|
} |
|
444
|
|
|
445
|
if (chunk.length) { |
|
446
|
chunks.push(chunk) |
|
447
|
} |
|
448
|
return chunks |
|
449
|
} |
|
450
|
|
|
451
|
protected task(index: string): SearchTypes.SearchTask { |
|
452
|
return { index, status: "succeeded" } |
|
453
|
} |
|
454
|
} |