1 {"slug":"/references/search/provider","title":"How to Create a Search Module Provider","frontmatter":{"slug":"/references/search/provider","keywords":["search","provider","integration"]},"toc":[{"title":"Implementation Example","id":"implementation-example","level":2},{"title":"Create Module Provider Directory","id":"create-module-provider-directory","level":2},{"title":"2. Create the Search Module Provider's Service","id":"2-create-the-search-module-provider-s-service","level":2},{"title":"constructor","id":"constructor","level":3},{"title":"Example","id":"example","level":4},{"title":"Handling unsupported features","id":"handling-unsupported-features","level":3},{"title":"identifier","id":"identifier","level":3},{"title":"Example","id":"example-1","level":4},{"title":"clearIndex","id":"clearindex","level":3},{"title":"Example","id":"example-2","level":4},{"title":"Parameters","id":"clearindex-parameters","level":4},{"title":"Returns","id":"clearindex-returns","level":4},{"title":"deleteDocuments","id":"deletedocuments","level":3},{"title":"Example","id":"example-3","level":4},{"title":"Parameters","id":"deletedocuments-parameters","level":4},{"title":"Returns","id":"deletedocuments-returns","level":4},{"title":"deleteIndex","id":"deleteindex","level":3},{"title":"Example","id":"example-4","level":4},{"title":"Parameters","id":"deleteindex-parameters","level":4},{"title":"Returns","id":"deleteindex-returns","level":4},{"title":"listIndexes","id":"listindexes","level":3},{"title":"Example","id":"example-5","level":4},{"title":"Returns","id":"listindexes-returns","level":4},{"title":"search","id":"search","level":3},{"title":"Example","id":"example-6","level":4},{"title":"Parameters","id":"search-parameters","level":4},{"title":"Returns","id":"search-returns","level":4},{"title":"searchMany","id":"searchmany","level":3},{"title":"Example","id":"example-7","level":4},{"title":"Parameters","id":"searchmany-parameters","level":4},{"title":"Returns","id":"searchmany-returns","level":4},{"title":"upsertDocuments","id":"upsertdocuments","level":3},{"title":"Example","id":"example-8","level":4},{"title":"Parameters","id":"upsertdocuments-parameters","level":4},{"title":"Returns","id":"upsertdocuments-returns","level":4},{"title":"upsertIndex","id":"upsertindex","level":3},{"title":"Example","id":"example-9","level":4},{"title":"Parameters","id":"upsertindex-parameters","level":4},{"title":"Returns","id":"upsertindex-returns","level":4},{"title":"waitForTask","id":"waitfortask","level":3},{"title":"Example","id":"example-10","level":4},{"title":"Parameters","id":"waitfortask-parameters","level":4},{"title":"Returns","id":"waitfortask-returns","level":4},{"title":"3. Create Module Provider Definition File","id":"3-create-module-provider-definition-file","level":2},{"title":"4. Use Module Provider","id":"4-use-module-provider","level":2},{"title":"5. Test it Out","id":"5-test-it-out","level":2},{"title":"Additional Resources","id":"additional-resources","level":2}],"blocks":[{"kind":"markdown","html":"In this document, you’ll learn how to create a Search Module Provider and the methods you must implement in its main service."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"Implementation Example","id":"implementation-example"},{"kind":"markdown","html":"As you implement your Search Module Provider, it can be useful to refer to an existing provider and how it's implemeted.\n\nIf you need to refer to an existing implementation as an example, check the [Postgres Search Module Provider in the Medusa repository](https://github.com/medusajs/medusa/tree/develop/packages/modules/providers/search-postgres).\n\n---"},{"kind":"heading","level":2,"text":"Create Module Provider Directory","id":"create-module-provider-directory"},{"kind":"markdown","html":"Start by creating a new directory for your module provider.\n\nIf you're creating the module provider in a Medusa application, create it under the `src/modules` directory. For example, `src/modules/my-search`.\n\nIf you're creating the module provider in a plugin, create it under the `src/providers` directory. For example, `src/providers/my-search`."},{"kind":"note","variant":"note","html":"The rest of this guide always uses the `src/modules/my-search` directory as an example."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"2. Create the Search Module Provider's Service","id":"2-create-the-search-module-provider-s-service"},{"kind":"markdown","html":"Create the file `src/modules/my-search/service.ts` that holds the implementation of the module provider's main service. It must extend the `AbstractSearchProviderService` class imported from `@medusajs/framework/utils`:\n\n```ts title=\"src/modules/my-search/service.ts\"\nimport { AbstractSearchProviderService } from \"@medusajs/framework/utils\"\n\nclass MySearchProviderService extends AbstractSearchProviderService {\n // TODO implement methods\n}\n\nexport default MySearchProviderService\n```"},{"kind":"markdown","html":"An abstract class for search providers. Extend this class to create a search\nprovider.\n\nA search provider translates the Search Module's provider-agnostic input into\nthe calls of a search engine, such as Meilisearch or Typesense: it creates and\nmigrates the physical indexes, writes and deletes documents, and runs queries.\nThe Search Module owns everything around it, including index definitions,\nbatching, task tracking, and reindexing."},{"kind":"heading","level":3,"text":"constructor","id":"constructor"},{"kind":"markdown","html":"The constructor allows you to access resources from the module's container using the first parameter,\nand the provider's options using the second parameter.\n\nIf you're creating a client with a search engine, do it in the constructor.\nEstablishing a connection with the search engine should happen in `onApplicationStart`."},{"kind":"heading","level":4,"text":"Example","id":"example"},{"kind":"markdown","html":"```ts\nimport { Logger } from \"@medusajs/framework/types\"\nimport { AbstractSearchProviderService } from \"@medusajs/framework/utils\"\n\ntype InjectedDependencies = {\n logger: Logger\n}\n\ntype Options = {\n host: string\n apiKey: string\n}\n\nclass MySearchProviderService extends AbstractSearchProviderService {\n static identifier = \"my-search\"\n\n protected logger_: Logger\n protected options_: Options\n // assuming you're initializing a client\n protected client\n\n constructor (\n { logger }: InjectedDependencies,\n options: Options\n ) {\n super()\n\n this.logger_ = logger\n this.options_ = options\n\n // assuming you're initializing a client\n this.client = new Client(options)\n }\n}\n\nexport default MySearchProviderService\n```"},{"kind":"heading","level":3,"text":"Handling unsupported features","id":"handling-unsupported-features"},{"kind":"markdown","html":"There's no list of features to declare. If a query asks for something your engine can't\nexpress, throw; if an index definition asks for something it can't hold, throw from\n`upsertIndex` so the error surfaces at startup. Returning a slightly different result is\nthe one outcome to avoid, since callers can't tell it apart from a correct one."},{"kind":"heading","level":3,"text":"identifier","id":"identifier"},{"kind":"markdown","html":"Each search provider has a unique identifier used to register it and to bind\nan index definition to it. An index definition selects a provider by setting\nits `provider` property to this identifier. You can also use this identifier\nin `medusa-config.ts` to configure the default provider for the Search Module."},{"kind":"heading","level":4,"text":"Example","id":"example-1"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n static identifier = \"my-search\"\n // ...\n}\n```"},{"kind":"heading","level":3,"text":"clearIndex","id":"clearindex"},{"kind":"markdown","html":"This method removes every document from an index without deleting the index itself.\nThe Search Module uses it to empty an index before reseeding it in place."},{"kind":"heading","level":4,"text":"Example","id":"example-2"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async clearIndex({\n index,\n }: {\n index: string\n }): Promise<SearchTypes.SearchTask> {\n await this.client.deleteAllDocuments(index)\n return { index, status: \"succeeded\" }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"clearindex-parameters"},{"kind":"typeList","sectionTitle":"clearIndex","types":[{"name":"_input","type":"`object`","description":"The index to empty.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"index","type":"`string`","description":"The index's physical name.","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"clearindex-returns"},{"kind":"typeList","sectionTitle":"clearIndex","types":[{"name":"Promise","type":"Promise&#60;[SearchTask](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchTask)&#62;","optional":false,"defaultValue":"","description":"The write's task.","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID identifying the write in the search engine, which is passed back to\nthe provider's `waitForTask` method. It's set only for a deferred write,\nsince a provider applying writes inline has nothing to identify.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"index","type":"`string`","description":"The name of the index the write was applied to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[SearchTaskStatus](/references/types/SearchTypes/types/types.SearchTypes.SearchTaskStatus)","description":"The write's status.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"error","type":"`object`","description":"The error that made the write fail, if its `status` is `failed`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"message","type":"`string`","description":"The error's message.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The error's code, as reported by the search engine.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":3,"text":"deleteDocuments","id":"deletedocuments"},{"kind":"markdown","html":"This method removes every document matching the given filters.\n\nDeleting by ID isn't a special case — it arrives as a filter on the primary key, such\nas `{ id: [\"prod_1\", \"prod_2\"] }`. Recognize that shape and use your engine's\ndelete-by-ID path, which is usually much faster. If your engine can't delete by\narbitrary filters, either search first and delete the matching IDs, or throw."},{"kind":"heading","level":4,"text":"Example","id":"example-3"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async deleteDocuments({\n index,\n filters,\n }: SearchTypes.SearchDeleteDocumentsInput): Promise<SearchTypes.SearchTask> {\n await this.client.deleteDocumentsByFilter(index, filters)\n return { index, status: \"succeeded\" }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"deletedocuments-parameters"},{"kind":"typeList","sectionTitle":"deleteDocuments","types":[{"name":"_input","type":"[SearchDeleteDocumentsInput](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchDeleteDocumentsInput)","description":"The index and the filters\nselecting the documents to remove.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"index","type":"`string`","description":"The physical name of the index to delete the documents from.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"filters","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)","description":"The filters selecting the documents to remove. Deleting by ID is a filter on\nthe index's primary key, such as `{ id: [\"prod_1\", \"prod_2\"] }`.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"$and","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)[]","description":"Filters that must all match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"$or","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)[]","description":"Filters of which at least one must match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"$not","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)","description":"Filters that must not match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"q","type":"`string`","description":"The free-text query. Sits among the filters so a `query.graph` call converts\nto `query.search` unchanged; the module lifts it out before compiling the\nrest, so a provider never sees `q` as a field.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"deletedocuments-returns"},{"kind":"typeList","sectionTitle":"deleteDocuments","types":[{"name":"Promise","type":"Promise&#60;[SearchTask](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchTask)&#62;","optional":false,"defaultValue":"","description":"The write's task.","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID identifying the write in the search engine, which is passed back to\nthe provider's `waitForTask` method. It's set only for a deferred write,\nsince a provider applying writes inline has nothing to identify.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"index","type":"`string`","description":"The name of the index the write was applied to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[SearchTaskStatus](/references/types/SearchTypes/types/types.SearchTypes.SearchTaskStatus)","description":"The write's status.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"error","type":"`object`","description":"The error that made the write fail, if its `status` is `failed`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"message","type":"`string`","description":"The error's message.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The error's code, as reported by the search engine.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":3,"text":"deleteIndex","id":"deleteindex"},{"kind":"markdown","html":"This method deletes an index and everything in it. The Search Module calls it\nto clean up an old version of an index once a newer one has taken over."},{"kind":"heading","level":4,"text":"Example","id":"example-4"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async deleteIndex({\n index,\n }: {\n index: string\n }): Promise<SearchTypes.SearchTask> {\n await this.client.deleteIndex(index)\n return { index, status: \"succeeded\" }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"deleteindex-parameters"},{"kind":"typeList","sectionTitle":"deleteIndex","types":[{"name":"_input","type":"`object`","description":"The index to delete.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"index","type":"`string`","description":"The index's physical name.","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"deleteindex-returns"},{"kind":"typeList","sectionTitle":"deleteIndex","types":[{"name":"Promise","type":"Promise&#60;[SearchTask](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchTask)&#62;","optional":false,"defaultValue":"","description":"The write's task.","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID identifying the write in the search engine, which is passed back to\nthe provider's `waitForTask` method. It's set only for a deferred write,\nsince a provider applying writes inline has nothing to identify.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"index","type":"`string`","description":"The name of the index the write was applied to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[SearchTaskStatus](/references/types/SearchTypes/types/types.SearchTypes.SearchTaskStatus)","description":"The write's status.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"error","type":"`object`","description":"The error that made the write fail, if its `status` is `failed`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"message","type":"`string`","description":"The error's message.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The error's code, as reported by the search engine.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":3,"text":"listIndexes","id":"listindexes"},{"kind":"markdown","html":"This method lists the indexes you hold. The Search Module reads the document counts to\nspot an index that lost its data and needs reseeding."},{"kind":"heading","level":4,"text":"Example","id":"example-5"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async listIndexes(): Promise<SearchTypes.SearchIndexInfo[]> {\n const indexes = await this.client.listIndexes()\n\n return indexes.map((index) => ({\n name: index.uid,\n provider: MySearchProviderService.identifier,\n document_count: index.numberOfDocuments,\n }))\n }\n}\n```"},{"kind":"heading","level":4,"text":"Returns","id":"listindexes-returns"},{"kind":"typeList","sectionTitle":"listIndexes","types":[{"name":"Promise","type":"Promise&#60;[SearchIndexInfo](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIndexInfo)[]&#62;","optional":false,"defaultValue":"","description":"The indexes and their document counts.","expandable":false,"children":[{"name":"SearchIndexInfo[]","type":"[SearchIndexInfo](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIndexInfo)[]","optional":false,"defaultValue":"","description":"","expandable":false,"children":[{"name":"name","type":"`string`","description":"The index's physical name.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider","type":"`string`","description":"The identifier of the provider holding the index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"document_count","type":"`number`","description":"The number of documents in the index. The Search Module uses it to spot an\nindex that lost its data and needs reseeding.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"created_at","type":"`Date`","description":"The date the index was created.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"updated_at","type":"`Date`","description":"The date the index was last updated.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":3,"text":"search","id":"search"},{"kind":"markdown","html":"This method runs a search against an index. The Search Module will use this method in\nits `search` and `searchMany` methods.\n\nThe free-text query arrives as `q`, already lifted out of `filters`, and\n`attributes_to_retrieve` is already narrowed to the fields the index can return.\n\nCompile `input.filters` to your engine's filter syntax, and reject the\noperators it can't express rather than approximating them. Also, use\n`input.index.physical_name` as the index to query, not `input.index.name`,\nsince the two differ under an index prefix or between versions."},{"kind":"heading","level":4,"text":"Example","id":"example-6"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async search(\n input: SearchTypes.ProviderSearchQuery\n ): Promise<SearchTypes.SearchResult> {\n const response = await this.client.search(input.index.physical_name, {\n query: input.q,\n limit: input.pagination?.take,\n })\n\n return {\n hits: response.hits.map((hit) => ({ id: hit.id, document: hit })),\n metadata: {\n skip: input.pagination?.skip ?? 0,\n take: input.pagination?.take ?? 20,\n count: response.total,\n },\n }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"search-parameters"},{"kind":"typeList","sectionTitle":"search","types":[{"name":"_input","type":"[ProviderSearchQuery](/references/types/SearchTypes/interfaces/types.SearchTypes.ProviderSearchQuery)","description":"The query, the resolved index\ndefinition, and the attributes to return.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"index","type":"[ResolvedSearchIndexDefinition](/references/types/SearchTypes/interfaces/types.SearchTypes.ResolvedSearchIndexDefinition)","description":"The resolved definition of the index to query. Use its `physical_name` as\nthe index to query, since it differs from the index's name under an index\nprefix or between versions.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"name","type":"`string`","description":"The index's unique name, which is what `query.search({ entity })` resolves\nagainst.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"entity","type":"`string`","description":"The `query.graph` entrypoint used to hydrate non-indexed fields.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"fields","type":"`Record<string, [SearchFieldDefinition](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchFieldDefinition)>`","description":"The fields the index holds, keyed by their path in the document.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"events","type":"`string`[]","description":"Events related and that can affect the data for this index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"consume","type":"(`event`: [Event](/references/types/EventBusTypes/types/types.EventBusTypes.Event)&#60;any&#62;, `context`: [SearchIngestionContext](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIngestionContext)) => Promise&#60;[SearchMutation](/references/types/SearchTypes/types/types.SearchTypes.SearchMutation)[]&#62;","description":"Executed on event ingestion to determine the action that needs to be performed on the index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"seed","type":"(`context`: [SearchSeedContext](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchSeedContext)) => AsyncIterable&#60;[SearchMutation](/references/types/SearchTypes/types/types.SearchTypes.SearchMutation)[]&#62;","description":"Yields mutations in batches — the same shape `consume` returns, so a\nseed can express a delete, not just an upsert. Ran when there is no data\nin the index, on reindex, and for the catch-up pass after a full seed.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"primary_key","type":"`string`","description":"The field whose value keys the index's documents.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider","type":"`string`","description":"The identifier of the provider backing this index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"settings","type":"[SearchIndexSettings](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIndexSettings)","description":"The settings applied to the index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"definition_hash","type":"`string`","description":"A hash of the definition, which the module compares to detect that an index\ndrifted from its definition and must be migrated.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"physical_name","type":"`string`","description":"The root physical index name, derived from `name` and the module's\n`index_prefix`. Never queried directly: each version of this index gets its\nown physical index derived from this root, and the module resolves which\none is currently active before reading or writing.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"attributes_to_retrieve","type":"`string`[]","description":"The field paths the search engine must return on every hit. Already narrowed\nby the Search Module to the fields the index can serve, so project it as\ngiven.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"q","type":"`string`","description":"Lifted out of `filters` by the module, because `filters` compiles to a DSL\nwith no representation for free text.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"filters","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)","description":"The filters to apply, including the free-text query as `q`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"$and","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)[]","description":"Filters that must all match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"$or","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)[]","description":"Filters of which at least one must match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"$not","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)","description":"Filters that must not match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"q","type":"`string`","description":"The free-text query. Sits among the filters so a `query.graph` call converts\nto `query.search` unchanged; the module lifts it out before compiling the\nrest, so a provider never sees `q` as a field.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"pagination","type":"[SearchPagination](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchPagination)","description":"How the results are paginated and sorted.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"skip","type":"`number`","description":"The number of documents to skip before the returned hits. Mutually exclusive\nwith `cursor`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"take","type":"`number`","description":"The maximum number of hits to return.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"order","type":"`Record<string, [SearchOrderBy](/references/types/SearchTypes/types/types.SearchTypes.SearchOrderBy)>`","description":"The fields to sort the hits by, keyed by the field's dotted path. The\nreserved `_score` key sorts by relevance.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"cursor","type":"`string`","description":"An opaque provider cursor, as returned in a previous result's\n`metadata.next_cursor`. Mutually exclusive with `skip`.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"search_options","type":"[SearchOptions](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchOptions)","description":"The options changing how the query is matched, scored, and aggregated.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"attributes_to_search_on","type":"`string`[]","description":"The dotted paths of the fields to match the free-text query against. Defaults\nto every field marked `searchable` on the index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"match_strategy","type":"[SearchMatchStrategy](/references/types/SearchTypes/types/types.SearchTypes.SearchMatchStrategy)","description":"How query terms combine.\n\n- `\"all\"` (default): every term must appear as a complete token.\n- `\"any\"`: at least one term must match.\n- `\"last\"`: typeahead. Completed terms must match in full; the last term\n is a prefix, so `\"my sear\"` matches `\"My search results\"`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"typo_tolerance","type":"`boolean`","description":"Whether to match terms that are misspelled by a character or two.\nit is ignored unless the query includes a free-text `q` and the\nsearched fields have typo tolerance enabled in the index's `settings.typo_tolerance`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"facets","type":"(`string` \\| [SearchFacetRequest](/references/types/SearchTypes/types/types.SearchTypes.SearchFacetRequest))[]","description":"The facets to compute alongside the hits. A string is shorthand for a `value`\nfacet on that field.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"disjunctive_facets","type":"`boolean`","description":"Compute each facet ignoring the filter on that same field, so a storefront\nkeeps showing sibling values of an active filter. Needs one query per facet\non every engine reviewed, so the module expands them and hands the set to\n`provider.searchMany`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"highlight","type":"`boolean` \\| [SearchHighlightOptions](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchHighlightOptions)","description":"How the matched terms are highlighted in the returned hits. Applied only\nwhen the query includes a free-text `q`; otherwise it is ignored.\n\n`true` highlights every field the query searches on. Pass an object to pick\nfields, tags, or snippet cropping.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"distinct","type":"`string`","description":"Return at most one hit per distinct value of this field.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"min_score","type":"`number`","description":"Discard hits scoring below this threshold.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"include_score","type":"`boolean`","description":"Whether to return each hit's relevance score.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"locales","type":"`string`[]","description":"Query-time language hint, e.g. `[\"en\"]`. Engines that analyze per language\n(Meilisearch, Algolia) use it to pick the analyzer; a provider that cannot\nhonour it rejects it rather than silently matching differently. Neither\nfirst-party provider does: configure the analyzer language on the provider\n(postgres) or on the field (Medusa) instead.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"vector","type":"[SearchVectorOptions](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchVectorOptions)","description":"The options of a vector, or semantic, search to run instead of, or alongside,\nthe free-text query.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"count","type":"[SearchCountStrategy](/references/types/SearchTypes/types/types.SearchTypes.SearchCountStrategy)","description":"How the total number of matching documents is computed. `\"exact\"` may be\nrejected or slow depending on the provider.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"provider_options","type":"`Record<string, Record&#60;string, unknown&#62;>`","description":"Escape hatch for engine features the interface does not model, keyed by\nprovider identifier, e.g. `{ typesense: { drop_tokens_threshold: 0 } }`.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"context","type":"[QueryContextType](/references/types/CommonTypes/types/types.CommonTypes.QueryContextType)","description":"The context passed to the `query.graph` call during hydration.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"search-returns"},{"kind":"typeList","sectionTitle":"search","types":[{"name":"Promise","type":"Promise&#60;[SearchResult](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchResult)&#60;Record&#60;string, unknown&#62;&#62;&#62;","optional":false,"defaultValue":"","description":"The hits, any facets, and the metadata.","expandable":false,"children":[]}]},{"kind":"heading","level":3,"text":"searchMany","id":"searchmany"},{"kind":"markdown","html":"This method runs multiple queries in a single request to the search engine.\nThe Search Module uses it for its `searchMany` method, including the extra\nqueries produced by disjunctive faceting.\n\nThe default runs `search` concurrently. Override it to pack the queries into\none engine round-trip."},{"kind":"heading","level":4,"text":"Example","id":"example-7"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async searchMany(\n inputs: SearchTypes.ProviderSearchQuery[]\n ): Promise<SearchTypes.SearchResult[]> {\n const { results } = await this.client.multiSearch(\n inputs.map((input) => ({\n indexUid: input.index.physical_name,\n query: input.q,\n }))\n )\n\n return results.map((result, i) => this.buildResult(result, inputs[i]))\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"searchmany-parameters"},{"kind":"typeList","sectionTitle":"searchMany","types":[{"name":"inputs","type":"[ProviderSearchQuery](/references/types/SearchTypes/interfaces/types.SearchTypes.ProviderSearchQuery)[]","description":"The queries to run.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"index","type":"[ResolvedSearchIndexDefinition](/references/types/SearchTypes/interfaces/types.SearchTypes.ResolvedSearchIndexDefinition)","description":"The resolved definition of the index to query. Use its `physical_name` as\nthe index to query, since it differs from the index's name under an index\nprefix or between versions.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"name","type":"`string`","description":"The index's unique name, which is what `query.search({ entity })` resolves\nagainst.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"entity","type":"`string`","description":"The `query.graph` entrypoint used to hydrate non-indexed fields.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"fields","type":"`Record<string, [SearchFieldDefinition](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchFieldDefinition)>`","description":"The fields the index holds, keyed by their path in the document.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"events","type":"`string`[]","description":"Events related and that can affect the data for this index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"consume","type":"(`event`: [Event](/references/types/EventBusTypes/types/types.EventBusTypes.Event)&#60;any&#62;, `context`: [SearchIngestionContext](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIngestionContext)) => Promise&#60;[SearchMutation](/references/types/SearchTypes/types/types.SearchTypes.SearchMutation)[]&#62;","description":"Executed on event ingestion to determine the action that needs to be performed on the index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"seed","type":"(`context`: [SearchSeedContext](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchSeedContext)) => AsyncIterable&#60;[SearchMutation](/references/types/SearchTypes/types/types.SearchTypes.SearchMutation)[]&#62;","description":"Yields mutations in batches — the same shape `consume` returns, so a\nseed can express a delete, not just an upsert. Ran when there is no data\nin the index, on reindex, and for the catch-up pass after a full seed.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"primary_key","type":"`string`","description":"The field whose value keys the index's documents.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider","type":"`string`","description":"The identifier of the provider backing this index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"settings","type":"[SearchIndexSettings](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIndexSettings)","description":"The settings applied to the index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"definition_hash","type":"`string`","description":"A hash of the definition, which the module compares to detect that an index\ndrifted from its definition and must be migrated.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"physical_name","type":"`string`","description":"The root physical index name, derived from `name` and the module's\n`index_prefix`. Never queried directly: each version of this index gets its\nown physical index derived from this root, and the module resolves which\none is currently active before reading or writing.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"attributes_to_retrieve","type":"`string`[]","description":"The field paths the search engine must return on every hit. Already narrowed\nby the Search Module to the fields the index can serve, so project it as\ngiven.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"q","type":"`string`","description":"Lifted out of `filters` by the module, because `filters` compiles to a DSL\nwith no representation for free text.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"filters","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)","description":"The filters to apply, including the free-text query as `q`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"$and","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)[]","description":"Filters that must all match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"$or","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)[]","description":"Filters of which at least one must match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"$not","type":"[SearchFilters](/references/types/SearchTypes/types/types.SearchTypes.SearchFilters)","description":"Filters that must not match.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"q","type":"`string`","description":"The free-text query. Sits among the filters so a `query.graph` call converts\nto `query.search` unchanged; the module lifts it out before compiling the\nrest, so a provider never sees `q` as a field.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"pagination","type":"[SearchPagination](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchPagination)","description":"How the results are paginated and sorted.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"skip","type":"`number`","description":"The number of documents to skip before the returned hits. Mutually exclusive\nwith `cursor`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"take","type":"`number`","description":"The maximum number of hits to return.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"order","type":"`Record<string, [SearchOrderBy](/references/types/SearchTypes/types/types.SearchTypes.SearchOrderBy)>`","description":"The fields to sort the hits by, keyed by the field's dotted path. The\nreserved `_score` key sorts by relevance.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"cursor","type":"`string`","description":"An opaque provider cursor, as returned in a previous result's\n`metadata.next_cursor`. Mutually exclusive with `skip`.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"search_options","type":"[SearchOptions](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchOptions)","description":"The options changing how the query is matched, scored, and aggregated.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"attributes_to_search_on","type":"`string`[]","description":"The dotted paths of the fields to match the free-text query against. Defaults\nto every field marked `searchable` on the index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"match_strategy","type":"[SearchMatchStrategy](/references/types/SearchTypes/types/types.SearchTypes.SearchMatchStrategy)","description":"How query terms combine.\n\n- `\"all\"` (default): every term must appear as a complete token.\n- `\"any\"`: at least one term must match.\n- `\"last\"`: typeahead. Completed terms must match in full; the last term\n is a prefix, so `\"my sear\"` matches `\"My search results\"`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"typo_tolerance","type":"`boolean`","description":"Whether to match terms that are misspelled by a character or two.\nit is ignored unless the query includes a free-text `q` and the\nsearched fields have typo tolerance enabled in the index's `settings.typo_tolerance`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"facets","type":"(`string` \\| [SearchFacetRequest](/references/types/SearchTypes/types/types.SearchTypes.SearchFacetRequest))[]","description":"The facets to compute alongside the hits. A string is shorthand for a `value`\nfacet on that field.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"disjunctive_facets","type":"`boolean`","description":"Compute each facet ignoring the filter on that same field, so a storefront\nkeeps showing sibling values of an active filter. Needs one query per facet\non every engine reviewed, so the module expands them and hands the set to\n`provider.searchMany`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"highlight","type":"`boolean` \\| [SearchHighlightOptions](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchHighlightOptions)","description":"How the matched terms are highlighted in the returned hits. Applied only\nwhen the query includes a free-text `q`; otherwise it is ignored.\n\n`true` highlights every field the query searches on. Pass an object to pick\nfields, tags, or snippet cropping.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"distinct","type":"`string`","description":"Return at most one hit per distinct value of this field.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"min_score","type":"`number`","description":"Discard hits scoring below this threshold.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"include_score","type":"`boolean`","description":"Whether to return each hit's relevance score.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"locales","type":"`string`[]","description":"Query-time language hint, e.g. `[\"en\"]`. Engines that analyze per language\n(Meilisearch, Algolia) use it to pick the analyzer; a provider that cannot\nhonour it rejects it rather than silently matching differently. Neither\nfirst-party provider does: configure the analyzer language on the provider\n(postgres) or on the field (Medusa) instead.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"vector","type":"[SearchVectorOptions](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchVectorOptions)","description":"The options of a vector, or semantic, search to run instead of, or alongside,\nthe free-text query.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"count","type":"[SearchCountStrategy](/references/types/SearchTypes/types/types.SearchTypes.SearchCountStrategy)","description":"How the total number of matching documents is computed. `\"exact\"` may be\nrejected or slow depending on the provider.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"provider_options","type":"`Record<string, Record&#60;string, unknown&#62;>`","description":"Escape hatch for engine features the interface does not model, keyed by\nprovider identifier, e.g. `{ typesense: { drop_tokens_threshold: 0 } }`.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"context","type":"[QueryContextType](/references/types/CommonTypes/types/types.CommonTypes.QueryContextType)","description":"The context passed to the `query.graph` call during hydration.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"searchmany-returns"},{"kind":"typeList","sectionTitle":"searchMany","types":[{"name":"Promise","type":"Promise&#60;[SearchResult](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchResult)&#60;Record&#60;string, unknown&#62;&#62;[]&#62;","optional":false,"defaultValue":"","description":"A result for each query, in\nthe same order as the queries.","expandable":false,"children":[{"name":"SearchResult&#60;Record&#60;string, unknown&#62;&#62;[]","type":"[SearchResult](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchResult)&#60;Record&#60;string, unknown&#62;&#62;[]","optional":false,"defaultValue":"","description":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"upsertDocuments","id":"upsertdocuments"},{"kind":"markdown","html":"This method adds documents to an index, replacing any that already exist under the same\nID. The Search Module uses it both for direct writes and for seeding, where it's called\nonce per batch.\n\nIf your engine applies writes later rather than inline, return a task with an `id` and\nimplement `waitForTask`, so the module can wait before making a new version active.\n\nWrite to `input.index` but read schema information from `input.definition`:\nwhile a new version is being seeded, `input.index` is that version's\nphysical index, whereas the definition is that of the logical index."},{"kind":"heading","level":4,"text":"Example","id":"example-8"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async upsertDocuments({\n index,\n definition,\n documents,\n }: {\n index: string\n definition: SearchTypes.ResolvedSearchIndexDefinition\n documents: SearchTypes.SearchDocument[]\n }): Promise<SearchTypes.SearchTask> {\n const task = await this.client.addDocuments(index, documents, {\n schema: definition.fields,\n })\n return { id: `${task.uid}`, index, status: \"enqueued\" }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"upsertdocuments-parameters"},{"kind":"typeList","sectionTitle":"upsertDocuments","types":[{"name":"_input","type":"`object`","description":"The documents to write.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"index","type":"`string`","description":"The index's physical name. This is the index to\nwrite to.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"definition","type":"[ResolvedSearchIndexDefinition](/references/types/SearchTypes/interfaces/types.SearchTypes.ResolvedSearchIndexDefinition)","description":"The\ndefinition of the logical index the documents belong to. Use it for schema\ninformation, such as the index's `fields` or `primary_key`.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"name","type":"`string`","description":"The index's unique name, which is what `query.search({ entity })` resolves\nagainst.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"entity","type":"`string`","description":"The `query.graph` entrypoint used to hydrate non-indexed fields.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"fields","type":"`Record<string, [SearchFieldDefinition](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchFieldDefinition)>`","description":"The fields the index holds, keyed by their path in the document.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"events","type":"`string`[]","description":"Events related and that can affect the data for this index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"consume","type":"(`event`: [Event](/references/types/EventBusTypes/types/types.EventBusTypes.Event)&#60;any&#62;, `context`: [SearchIngestionContext](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIngestionContext)) => Promise&#60;[SearchMutation](/references/types/SearchTypes/types/types.SearchTypes.SearchMutation)[]&#62;","description":"Executed on event ingestion to determine the action that needs to be performed on the index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"seed","type":"(`context`: [SearchSeedContext](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchSeedContext)) => AsyncIterable&#60;[SearchMutation](/references/types/SearchTypes/types/types.SearchTypes.SearchMutation)[]&#62;","description":"Yields mutations in batches — the same shape `consume` returns, so a\nseed can express a delete, not just an upsert. Ran when there is no data\nin the index, on reindex, and for the catch-up pass after a full seed.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"primary_key","type":"`string`","description":"The field whose value keys the index's documents.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider","type":"`string`","description":"The identifier of the provider backing this index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"settings","type":"[SearchIndexSettings](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIndexSettings)","description":"The settings applied to the index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"definition_hash","type":"`string`","description":"A hash of the definition, which the module compares to detect that an index\ndrifted from its definition and must be migrated.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"physical_name","type":"`string`","description":"The root physical index name, derived from `name` and the module's\n`index_prefix`. Never queried directly: each version of this index gets its\nown physical index derived from this root, and the module resolves which\none is currently active before reading or writing.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"documents","type":"[SearchDocument](/references/types/SearchTypes/types/types.SearchTypes.SearchDocument)[]","description":"The documents, each with an `id`.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"upsertdocuments-returns"},{"kind":"typeList","sectionTitle":"upsertDocuments","types":[{"name":"Promise","type":"Promise&#60;[SearchTask](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchTask)&#62;","optional":false,"defaultValue":"","description":"The write's task.","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID identifying the write in the search engine, which is passed back to\nthe provider's `waitForTask` method. It's set only for a deferred write,\nsince a provider applying writes inline has nothing to identify.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"index","type":"`string`","description":"The name of the index the write was applied to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[SearchTaskStatus](/references/types/SearchTypes/types/types.SearchTypes.SearchTaskStatus)","description":"The write's status.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"error","type":"`object`","description":"The error that made the write fail, if its `status` is `failed`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"message","type":"`string`","description":"The error's message.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The error's code, as reported by the search engine.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":3,"text":"upsertIndex","id":"upsertindex"},{"kind":"markdown","html":"This method brings an index in line with its definition, creating it if it doesn't\nexist. The Search Module calls it for every definition when migrations run.\n\nYou may recreate the index if your engine can't alter a schema in place. That's safe:\nthe module only points this at an index it's about to seed, never at one that has to\nkeep serving reads, and never during a partial rebuild.\n\nThrow if the definition asks for something your engine can't hold, such as a\nfacet type it doesn't support. Since migrations run before the application\nserves requests, the error surfaces at startup rather than as wrong results\nlater."},{"kind":"heading","level":4,"text":"Example","id":"example-9"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async upsertIndex({\n index,\n }: {\n index: SearchTypes.ResolvedSearchIndexDefinition\n }): Promise<SearchTypes.SearchTask> {\n await this.client.createIndex(index.physical_name, {\n primaryKey: index.primary_key,\n })\n\n return { index: index.physical_name, status: \"succeeded\" }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"upsertindex-parameters"},{"kind":"typeList","sectionTitle":"upsertIndex","types":[{"name":"_input","type":"`object`","description":"The index to create or update.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"index","type":"[ResolvedSearchIndexDefinition](/references/types/SearchTypes/interfaces/types.SearchTypes.ResolvedSearchIndexDefinition)","description":"The definition,\nincluding the `physical_name` to create it under, the `primary_key` its\ndocuments are keyed by, the `fields` it holds, and its `settings`.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"name","type":"`string`","description":"The index's unique name, which is what `query.search({ entity })` resolves\nagainst.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"entity","type":"`string`","description":"The `query.graph` entrypoint used to hydrate non-indexed fields.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"fields","type":"`Record<string, [SearchFieldDefinition](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchFieldDefinition)>`","description":"The fields the index holds, keyed by their path in the document.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"events","type":"`string`[]","description":"Events related and that can affect the data for this index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"consume","type":"(`event`: [Event](/references/types/EventBusTypes/types/types.EventBusTypes.Event)&#60;any&#62;, `context`: [SearchIngestionContext](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIngestionContext)) => Promise&#60;[SearchMutation](/references/types/SearchTypes/types/types.SearchTypes.SearchMutation)[]&#62;","description":"Executed on event ingestion to determine the action that needs to be performed on the index.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"seed","type":"(`context`: [SearchSeedContext](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchSeedContext)) => AsyncIterable&#60;[SearchMutation](/references/types/SearchTypes/types/types.SearchTypes.SearchMutation)[]&#62;","description":"Yields mutations in batches — the same shape `consume` returns, so a\nseed can express a delete, not just an upsert. Ran when there is no data\nin the index, on reindex, and for the catch-up pass after a full seed.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"primary_key","type":"`string`","description":"The field whose value keys the index's documents.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider","type":"`string`","description":"The identifier of the provider backing this index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"settings","type":"[SearchIndexSettings](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchIndexSettings)","description":"The settings applied to the index.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"definition_hash","type":"`string`","description":"A hash of the definition, which the module compares to detect that an index\ndrifted from its definition and must be migrated.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"physical_name","type":"`string`","description":"The root physical index name, derived from `name` and the module's\n`index_prefix`. Never queried directly: each version of this index gets its\nown physical index derived from this root, and the module resolves which\none is currently active before reading or writing.","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"upsertindex-returns"},{"kind":"typeList","sectionTitle":"upsertIndex","types":[{"name":"Promise","type":"Promise&#60;[SearchTask](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchTask)&#62;","optional":false,"defaultValue":"","description":"The write's task.","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID identifying the write in the search engine, which is passed back to\nthe provider's `waitForTask` method. It's set only for a deferred write,\nsince a provider applying writes inline has nothing to identify.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"index","type":"`string`","description":"The name of the index the write was applied to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[SearchTaskStatus](/references/types/SearchTypes/types/types.SearchTypes.SearchTaskStatus)","description":"The write's status.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"error","type":"`object`","description":"The error that made the write fail, if its `status` is `failed`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"message","type":"`string`","description":"The error's message.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The error's code, as reported by the search engine.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":3,"text":"waitForTask","id":"waitfortask"},{"kind":"badges","badges":[{"variant":"neutral","label":"optional"}]},{"kind":"markdown","html":"This method waits until a deferred write is applied. The Search Module uses it\nto wait for a seed to be applied before making the new version active.\n\nImplement it if your engine acknowledges writes and applies them later. When\nit's not implemented, the module assumes a write is applied once\n`upsertDocuments` resolves."},{"kind":"heading","level":4,"text":"Example","id":"example-10"},{"kind":"markdown","html":"```ts\nclass MySearchProviderService extends AbstractSearchProviderService {\n // ...\n async waitForTask(\n task: SearchTypes.SearchTask,\n options?: { timeout_ms?: number }\n ): Promise<SearchTypes.SearchTask> {\n const result = await this.client.waitForTask(task.id!, {\n timeOutMs: options?.timeout_ms,\n })\n\n return {\n ...task,\n status: result.status === \"succeeded\" ? \"succeeded\" : \"failed\",\n }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"waitfortask-parameters"},{"kind":"typeList","sectionTitle":"waitForTask","types":[{"name":"task","type":"[SearchTask](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchTask)","description":"The task returned by the write, holding the `id`\nthat identifies it.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID identifying the write in the search engine, which is passed back to\nthe provider's `waitForTask` method. It's set only for a deferred write,\nsince a provider applying writes inline has nothing to identify.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"index","type":"`string`","description":"The name of the index the write was applied to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[SearchTaskStatus](/references/types/SearchTypes/types/types.SearchTypes.SearchTaskStatus)","description":"The write's status.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"error","type":"`object`","description":"The error that made the write fail, if its `status` is `failed`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"message","type":"`string`","description":"The error's message.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The error's code, as reported by the search engine.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"name":"options","type":"`object`","description":"The options of the wait.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"timeout_ms","type":"`number`","description":"How long to wait for the task before\ngiving up, in milliseconds.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"waitfortask-returns"},{"kind":"typeList","sectionTitle":"waitForTask","types":[{"name":"Promise","type":"Promise&#60;[SearchTask](/references/types/SearchTypes/interfaces/types.SearchTypes.SearchTask)&#62;","optional":false,"defaultValue":"","description":"The task in its final state.","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID identifying the write in the search engine, which is passed back to\nthe provider's `waitForTask` method. It's set only for a deferred write,\nsince a provider applying writes inline has nothing to identify.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"index","type":"`string`","description":"The name of the index the write was applied to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[SearchTaskStatus](/references/types/SearchTypes/types/types.SearchTypes.SearchTaskStatus)","description":"The write's status.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"error","type":"`object`","description":"The error that made the write fail, if its `status` is `failed`.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"message","type":"`string`","description":"The error's message.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The error's code, as reported by the search engine.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"3. Create Module Provider Definition File","id":"3-create-module-provider-definition-file"},{"kind":"markdown","html":"Create the file `src/modules/my-search/index.ts` with the following content:\n\n```ts title=\"src/modules/my-search/index.ts\"\nimport MySearchProviderService from \"./service\"\nimport { \n ModuleProvider, \n Modules\n} from \"@medusajs/framework/utils\"\n\nexport default ModuleProvider(Modules.SEARCH, {\n services: [MySearchProviderService],\n})\n```\n\nThis exports the module provider's definition, indicating that the `MySearchProviderService` is the module provider's service.\n\n---"},{"kind":"heading","level":2,"text":"4. Use Module Provider","id":"4-use-module-provider"},{"kind":"markdown","html":"To use your Search Module Provider, add it to the `providers` array of the Search Module in `medusa-config.ts`:"},{"kind":"note","variant":"note","html":"If you're using more than one Search Module Provider, make sure to set the `default_provider` option of the Search Module to the provider you want to use by default. You can also set it in an index definition's `provider` property to use a specific provider for that index."},{"kind":"markdown","html":"```ts title=\"medusa-config.ts\"\nmodule.exports = defineConfig({\n // ...\n modules: [\n {\n resolve: \"@medusajs/medusa/search\",\n options: {\n // Only needed with more than one provider.\n // default_provider: \"my-search\",\n providers: [\n {\n // if module provider is in a plugin, use `plugin-name/providers/my-search`\n resolve: \"./src/modules/my-search\",\n id: \"my-search\",\n options: {\n // provider options...\n },\n },\n // ...\n ],\n },\n },\n ],\n})\n```\n\n\n---"},{"kind":"heading","level":2,"text":"5. Test it Out","id":"5-test-it-out"},{"kind":"markdown","html":"To test the module out, add an API route that uses `query.search` to search through products. For example, create the file `src/api/search-products/route.ts` with the following content:\n\n```ts title=\"src/api/search-products/route.ts\"\nimport {\n MedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework/http\"\n\nexport const GET = async (\n req: MedusaRequest,\n res: MedusaResponse\n) => {\n const query = req.scope.resolve(\"query\")\n\n const { data, search_result } = await query.search({\n entity: \"product\",\n fields: [\"id\", \"title\", \"handle\"],\n filters: {\n q: req.query.q as string,\n status: \"published\",\n },\n pagination: { take: 20 },\n })\n\n res.json({\n products: data,\n metadata: search_result.metadata,\n })\n}\n```\n\nThis route resolves the [Query](!docs!/learn/fundamentals/module-links/query) from the [Medusa container](!docs!/learn/fundamentals/medusa-container) and uses its `search` method to search the `product` index. `query.search` uses your Search Module Provider under the hood to run the query, then hydrates the returned hits with `query.graph`.\n\nFinally, start your Medusa application:\n\n```bash npm2yarn\nnpm run dev\n```\n\nThen, send a request to the route:\n\n```bash\ncurl \"http://localhost:9000/search-products?q=shirt\"\n```\n\nYou'll receive the products whose titles match the query, ordered by relevance, based on your Search Module Provider's implementation:\n\n```json title=\"Example Response\"\n{\n \"products\": [\n {\n \"id\": \"prod_01KXR3J9J610DT161E2E4ZS6P1\",\n \"title\": \"Medusa T-Shirt\",\n \"handle\": \"t-shirt\"\n }\n ],\n \"metadata\": {\n \"skip\": 0,\n \"take\": 20,\n \"count\": 1,\n \"query\": \"shirt\",\n \"processing_time_ms\": 9\n }\n}\n```\n\n\n---"},{"kind":"heading","level":2,"text":"Additional Resources","id":"additional-resources"},{"kind":"markdown","html":"- [How to Use the Search Module](/references/search/service)"}]}