1 import { SearchTypes } from "@medusajs/types"
2
3 /**
4 * An abstract class for search providers. Extend this class to create a search
5 * provider.
6 *
7 * A search provider translates the Search Module's provider-agnostic input into
8 * the calls of a search engine, such as Meilisearch or Typesense: it creates and
9 * migrates the physical indexes, writes and deletes documents, and runs queries.
10 * The Search Module owns everything around it, including index definitions,
11 * batching, task tracking, and reindexing.
12 *
13 * ### constructor
14 *
15 * The constructor allows you to access resources from the module's container using the first parameter,
16 * and the provider's options using the second parameter.
17 *
18 * If you're creating a client with a search engine, do it in the constructor.
19 * Establishing a connection with the search engine should happen in `onApplicationStart`.
20 *
21 * #### Example
22 *
23 * ```ts
24 * import { Logger } from "@medusajs/framework/types"
25 * import { AbstractSearchProviderService } from "@medusajs/framework/utils"
26 *
27 * type InjectedDependencies = {
28 * logger: Logger
29 * }
30 *
31 * type Options = {
32 * host: string
33 * apiKey: string
34 * }
35 *
36 * class MySearchProviderService extends AbstractSearchProviderService {
37 * static identifier = "my-search"
38 *
39 * protected logger_: Logger
40 * protected options_: Options
41 * // assuming you're initializing a client
42 * protected client
43 *
44 * constructor (
45 * { logger }: InjectedDependencies,
46 * options: Options
47 * ) {
48 * super()
49 *
50 * this.logger_ = logger
51 * this.options_ = options
52 *
53 * // assuming you're initializing a client
54 * this.client = new Client(options)
55 * }
56 * }
57 *
58 * export default MySearchProviderService
59 * ```
60 *
61 * ### Handling unsupported features
62 *
63 * There's no list of features to declare. If a query asks for something your engine can't
64 * express, throw; if an index definition asks for something it can't hold, throw from
65 * `upsertIndex` so the error surfaces at startup. Returning a slightly different result is
66 * the one outcome to avoid, since callers can't tell it apart from a correct one.
67 *
68 * @privateRemarks
69 *
70 * `waitForTask` is optional and left out of this class on purpose: the Search
71 * Module treats its presence as support, so only define it if your engine
72 * applies writes asynchronously. `searchMany` has a default that runs `search`
73 * concurrently; override it to pack the queries into one engine round-trip.
74 * Refer to the `ISearchProvider` interface for their expected parameters and
75 * return values.
76 */
77 export class AbstractSearchProviderService
78 implements SearchTypes.ISearchProvider
79 {
80 /**
81 * Each search provider has a unique identifier used to register it and to bind
82 * an index definition to it. An index definition selects a provider by setting
83 * its `provider` property to this identifier. You can also use this identifier
84 * in `medusa-config.ts` to configure the default provider for the Search Module.
85 *
86 * @example
87 * class MySearchProviderService extends AbstractSearchProviderService {
88 * static identifier = "my-search"
89 * // ...
90 * }
91 */
92 static identifier: string
93
94 /**
95 * @ignore
96 */
97 get identifier(): string {
98 return (this.constructor as any).identifier
99 }
100
101 /**
102 * @ignore
103 */
104 getIdentifier(): string {
105 return (this.constructor as any).identifier
106 }
107
108 /**
109 * This method runs a search against an index. The Search Module will use this method in
110 * its `search` and `searchMany` methods.
111 *
112 * The free-text query arrives as `q`, already lifted out of `filters`, and
113 * `attributes_to_retrieve` is already narrowed to the fields the index can return.
114 *
115 * Compile `input.filters` to your engine's filter syntax, and reject the
116 * operators it can't express rather than approximating them. Also, use
117 * `input.index.physical_name` as the index to query, not `input.index.name`,
118 * since the two differ under an index prefix or between versions.
119 *
120 * @param {SearchTypes.ProviderSearchQuery} _input - The query, the resolved index
121 * definition, and the attributes to return.
122 * @returns {Promise<SearchTypes.SearchResult>} The hits, any facets, and the metadata.
123 *
124 * @example
125 * class MySearchProviderService extends AbstractSearchProviderService {
126 * // ...
127 * async search(
128 * input: SearchTypes.ProviderSearchQuery
129 * ): Promise<SearchTypes.SearchResult> {
130 * const response = await this.client.search(input.index.physical_name, {
131 * query: input.q,
132 * limit: input.pagination?.take,
133 * })
134 *
135 * return {
136 * hits: response.hits.map((hit) => ({ id: hit.id, document: hit })),
137 * metadata: {
138 * skip: input.pagination?.skip ?? 0,
139 * take: input.pagination?.take ?? 20,
140 * count: response.total,
141 * },
142 * }
143 * }
144 * }
145 */
146 async search(
147 _input: SearchTypes.ProviderSearchQuery
148 ): Promise<SearchTypes.SearchResult> {
149 throw Error("search must be overridden by the child class")
150 }
151
152 /**
153 * This method runs multiple queries in a single request to the search engine.
154 * The Search Module uses it for its `searchMany` method, including the extra
155 * queries produced by disjunctive faceting.
156 *
157 * The default runs `search` concurrently. Override it to pack the queries into
158 * one engine round-trip.
159 *
160 * @param {SearchTypes.ProviderSearchQuery[]} inputs - The queries to run.
161 * @returns {Promise<SearchTypes.SearchResult[]>} A result for each query, in
162 * the same order as the queries.
163 *
164 * @example
165 * class MySearchProviderService extends AbstractSearchProviderService {
166 * // ...
167 * async searchMany(
168 * inputs: SearchTypes.ProviderSearchQuery[]
169 * ): Promise<SearchTypes.SearchResult[]> {
170 * const { results } = await this.client.multiSearch(
171 * inputs.map((input) => ({
172 * indexUid: input.index.physical_name,
173 * query: input.q,
174 * }))
175 * )
176 *
177 * return results.map((result, i) => this.buildResult(result, inputs[i]))
178 * }
179 * }
180 */
181 async searchMany(
182 inputs: SearchTypes.ProviderSearchQuery[]
183 ): Promise<SearchTypes.SearchResult[]> {
184 return await Promise.all(inputs.map((input) => this.search(input)))
185 }
186
187 /**
188 * This method brings an index in line with its definition, creating it if it doesn't
189 * exist. The Search Module calls it for every definition when migrations run.
190 *
191 * You may recreate the index if your engine can't alter a schema in place. That's safe:
192 * the module only points this at an index it's about to seed, never at one that has to
193 * keep serving reads, and never during a partial rebuild.
194 *
195 * Throw if the definition asks for something your engine can't hold, such as a
196 * facet type it doesn't support. Since migrations run before the application
197 * serves requests, the error surfaces at startup rather than as wrong results
198 * later.
199 *
200 * @param {object} _input - The index to create or update.
201 * @param {SearchTypes.ResolvedSearchIndexDefinition} _input.index - The definition,
202 * including the `physical_name` to create it under, the `primary_key` its
203 * documents are keyed by, the `fields` it holds, and its `settings`.
204 * @returns {Promise<SearchTypes.SearchTask>} The write's task.
205 *
206 * @example
207 * class MySearchProviderService extends AbstractSearchProviderService {
208 * // ...
209 * async upsertIndex({
210 * index,
211 * }: {
212 * index: SearchTypes.ResolvedSearchIndexDefinition
213 * }): Promise<SearchTypes.SearchTask> {
214 * await this.client.createIndex(index.physical_name, {
215 * primaryKey: index.primary_key,
216 * })
217 *
218 * return { index: index.physical_name, status: "succeeded" }
219 * }
220 * }
221 */
222 async upsertIndex(_input: {
223 index: SearchTypes.ResolvedSearchIndexDefinition
224 }): Promise<SearchTypes.SearchTask> {
225 throw Error("upsertIndex must be overridden by the child class")
226 }
227
228 /**
229 * This method deletes an index and everything in it. The Search Module calls it
230 * to clean up an old version of an index once a newer one has taken over.
231 *
232 * @param {object} _input - The index to delete.
233 * @param {string} _input.index - The index's physical name.
234 * @returns {Promise<SearchTypes.SearchTask>} The write's task.
235 *
236 * @example
237 * class MySearchProviderService extends AbstractSearchProviderService {
238 * // ...
239 * async deleteIndex({
240 * index,
241 * }: {
242 * index: string
243 * }): Promise<SearchTypes.SearchTask> {
244 * await this.client.deleteIndex(index)
245 * return { index, status: "succeeded" }
246 * }
247 * }
248 */
249 async deleteIndex(_input: {
250 index: string
251 }): Promise<SearchTypes.SearchTask> {
252 throw Error("deleteIndex must be overridden by the child class")
253 }
254
255 /**
256 * This method lists the indexes you hold. The Search Module reads the document counts to
257 * spot an index that lost its data and needs reseeding.
258 *
259 * @returns {Promise<SearchTypes.SearchIndexInfo[]>} The indexes and their document counts.
260 *
261 * @example
262 * class MySearchProviderService extends AbstractSearchProviderService {
263 * // ...
264 * async listIndexes(): Promise<SearchTypes.SearchIndexInfo[]> {
265 * const indexes = await this.client.listIndexes()
266 *
267 * return indexes.map((index) => ({
268 * name: index.uid,
269 * provider: MySearchProviderService.identifier,
270 * document_count: index.numberOfDocuments,
271 * }))
272 * }
273 * }
274 */
275 async listIndexes(): Promise<SearchTypes.SearchIndexInfo[]> {
276 throw Error("listIndexes must be overridden by the child class")
277 }
278
279 /**
280 * This method adds documents to an index, replacing any that already exist under the same
281 * ID. The Search Module uses it both for direct writes and for seeding, where it's called
282 * once per batch.
283 *
284 * If your engine applies writes later rather than inline, return a task with an `id` and
285 * implement `waitForTask`, so the module can wait before making a new version active.
286 *
287 * Write to `input.index` but read schema information from `input.definition`:
288 * while a new version is being seeded, `input.index` is that version's
289 * physical index, whereas the definition is that of the logical index.
290 *
291 * @param {object} _input - The documents to write.
292 * @param {string} _input.index - The index's physical name. This is the index to
293 * write to.
294 * @param {SearchTypes.ResolvedSearchIndexDefinition} _input.definition - The
295 * definition of the logical index the documents belong to. Use it for schema
296 * information, such as the index's `fields` or `primary_key`.
297 * @param {SearchTypes.SearchDocument[]} _input.documents - The documents, each with an `id`.
298 * @returns {Promise<SearchTypes.SearchTask>} The write's task.
299 *
300 * @example
301 * class MySearchProviderService extends AbstractSearchProviderService {
302 * // ...
303 * async upsertDocuments({
304 * index,
305 * definition,
306 * documents,
307 * }: {
308 * index: string
309 * definition: SearchTypes.ResolvedSearchIndexDefinition
310 * documents: SearchTypes.SearchDocument[]
311 * }): Promise<SearchTypes.SearchTask> {
312 * const task = await this.client.addDocuments(index, documents, {
313 * schema: definition.fields,
314 * })
315 * return { id: `${task.uid}`, index, status: "enqueued" }
316 * }
317 * }
318 */
319 async upsertDocuments(_input: {
320 index: string
321 definition: SearchTypes.ResolvedSearchIndexDefinition
322 documents: SearchTypes.SearchDocument[]
323 }): Promise<SearchTypes.SearchTask> {
324 throw Error("upsertDocuments must be overridden by the child class")
325 }
326
327 /**
328 * This method removes every document matching the given filters.
329 *
330 * Deleting by ID isn't a special case — it arrives as a filter on the primary key, such
331 * as `{ id: ["prod_1", "prod_2"] }`. Recognize that shape and use your engine's
332 * delete-by-ID path, which is usually much faster. If your engine can't delete by
333 * arbitrary filters, either search first and delete the matching IDs, or throw.
334 *
335 * @param {SearchTypes.SearchDeleteDocumentsInput} _input - The index and the filters
336 * selecting the documents to remove.
337 * @returns {Promise<SearchTypes.SearchTask>} The write's task.
338 *
339 * @example
340 * class MySearchProviderService extends AbstractSearchProviderService {
341 * // ...
342 * async deleteDocuments({
343 * index,
344 * filters,
345 * }: SearchTypes.SearchDeleteDocumentsInput): Promise<SearchTypes.SearchTask> {
346 * await this.client.deleteDocumentsByFilter(index, filters)
347 * return { index, status: "succeeded" }
348 * }
349 * }
350 */
351 async deleteDocuments(
352 _input: SearchTypes.SearchDeleteDocumentsInput
353 ): Promise<SearchTypes.SearchTask> {
354 throw Error("deleteDocuments must be overridden by the child class")
355 }
356
357 /**
358 * This method removes every document from an index without deleting the index itself.
359 * The Search Module uses it to empty an index before reseeding it in place.
360 *
361 * @param {object} _input - The index to empty.
362 * @param {string} _input.index - The index's physical name.
363 * @returns {Promise<SearchTypes.SearchTask>} The write's task.
364 *
365 * @example
366 * class MySearchProviderService extends AbstractSearchProviderService {
367 * // ...
368 * async clearIndex({
369 * index,
370 * }: {
371 * index: string
372 * }): Promise<SearchTypes.SearchTask> {
373 * await this.client.deleteAllDocuments(index)
374 * return { index, status: "succeeded" }
375 * }
376 * }
377 */
378 async clearIndex(_input: { index: string }): Promise<SearchTypes.SearchTask> {
379 throw Error("clearIndex must be overridden by the child class")
380 }
381 }