1 import { TypeList, Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Search Queries`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you’ll learn about Query's `search` method and how to use it to run full-text search queries with filters, facets, highlighting, and vector search.
10
11 <Prerequisites
12 items={[
13 {
14 text: "Medusa v2.21.1+",
15 link: "https://github.com/medusajs/medusa/releases/tag/v2.21.1"
16 }
17 ]}
18 />
19
20 ## What is a Search Query?
21
22 A search query runs against the [Search Module](!resources!/infrastructure-modules/search) to retrieve and rank documents based on relevance. For example, searching products with full-text search, filtering by price, and sorting by popularity.
23
24 Under the hood, the Search Module retrieves the results from the integrated [Search Module Provider](!resources!/infrastructure-modules/search/providers), such as [Medusa Search](!cloud!/search) or your custom third-party provider.
25
26 For searching from a storefront, Medusa provides a [Store Search API route](!api!/store/search/search-indexes) that returns the fields your search indexes hold. Use `query.search` in your custom API routes to hydrate hits with other fields, or to search data models that the route doesn't expose.
27
28 <Note title="Best Practices">
29
30 Prefer `query.search` over `query.graph` when the request has a free-text term to rank by. `query.graph` filters records in the database without relevance ranking, whereas `query.search` delegates the ranking to a [Search Module Provider](!resources!/infrastructure-modules/search/providers).
31
32 </Note>
33
34 <Note title="Don't use query.search if" type="error">
35
36 - The request has no search term and no relevance ordering. Use [`query.graph`](../page.mdx) instead.
37
38 </Note>
39
40 ---
41
42 ## Search Example
43
44 Assuming you want a separate API route for searching products, create an API route at `src/api/store/products/custom-search/route.ts` with the following content:
45
46 export const exampleHighlights = [
47 ["13", "query", "Resolve Query from the Medusa container."],
48 ["17", "search", "Run a search query and hydrate the hits."],
49 ["18", "entity", "The name of the index to search."],
50 ["19", "fields", "The fields to return on every result."],
51 ["27", "q", "The free-text term, passed among the filters."],
52 ["38", "metadata", "The pagination details the provider reported."],
53 ]
54
55 ```ts title="src/api/store/products/custom-search/route.ts" highlights={exampleHighlights} collapsibleLines="1-7" expandButtonLabel="Show Imports"
56 import {
57 MedusaRequest,
58 MedusaResponse,
59 } from "@medusajs/framework/http"
60 import {
61 ContainerRegistrationKeys,
62 } from "@medusajs/framework/utils"
63
64 export const GET = async (
65 req: MedusaRequest,
66 res: MedusaResponse
67 ) => {
68 const query = req.scope.resolve(
69 ContainerRegistrationKeys.QUERY
70 )
71
72 const { data, search_result } = await query.search({
73 entity: "product",
74 fields: [
75 "id",
76 "title",
77 "handle",
78 "variants.id",
79 "variants.sku",
80 ],
81 filters: {
82 q: req.query.q as string,
83 status: "published",
84 },
85 pagination: {
86 skip: 0,
87 take: 20,
88 },
89 })
90
91 res.json({
92 products: data,
93 metadata: search_result.metadata,
94 })
95 }
96 ```
97
98 In the above example, you resolve Query from the Medusa container using the `ContainerRegistrationKeys.QUERY` (`query`) key.
99
100 Then, you run a search using its `search` method. This method accepts as a parameter an object with the following properties:
101
102 - `entity` (required): The name of the index to search, as specified in the `name` property of the [index definition](!resources!/infrastructure-modules/search/index-definitions).
103 - `fields`: The fields to return on every result, including fields that the index doesn't hold, such as `variants.sku`. If you omit `fields`, you'll receive every retrievable field the index holds.
104 - `filters`: The filters to apply, with the free-text term passed as `q`.
105 - `pagination`: The `skip` and `take` options that page through the results.
106
107 The method returns an object with two properties:
108
109 - `data`: The hydrated entities, in the relevance order the provider returned.
110 - `search_result`: What the provider reported, including hits, scores, facets, and pagination metadata.
111
112 For example, if you pass `q=t-shirt` in the request, the response may look like this:
113
114 ```json title="Returned Data"
115 {
116 "data": [
117 {
118 "id": "prod_123",
119 "title": "Medusa T-Shirt",
120 "handle": "t-shirt",
121 "variants": [
122 {
123 "id": "variant_123",
124 "sku": "SHIRT-S"
125 }
126 ]
127 }
128 ],
129 "search_result": {
130 "hits": [
131 {
132 "id": "prod_123",
133 "document": {
134 "id": "prod_123",
135 "title": "Medusa T-Shirt",
136 "handle": "t-shirt"
137 }
138 }
139 ],
140 "metadata": {
141 "skip": 0,
142 "take": 20,
143 "count": 1,
144 "query": "t-shirt",
145 "processing_time_ms": 9
146 }
147 }
148 }
149 ```
150
151 ### Search Usage in Workflows
152
153 To run a search query in a workflow, create a step that resolves Query from the container and uses it to run the search query.
154
155 For example:
156
157 export const workflowHighlights = [
158 ["10", "resolve", "Resolve the Search Module's service."],
159 ]
160
161 ```ts title="src/workflows/steps/search-products.ts" highlights={workflowHighlights}
162 import { Modules } from "@medusajs/framework/utils"
163 import {
164 createStep,
165 StepResponse,
166 } from "@medusajs/framework/workflows-sdk"
167
168 export const searchProductsStep = createStep(
169 "search-products",
170 async (input: { q: string }, { container }) => {
171 const searchModuleService = container.resolve(
172 ContainerRegistrationKeys.QUERY
173 )
174
175 const { data, search_result } = await query.search({
176 entity: "product",
177 fields: [
178 "id",
179 "title",
180 "handle",
181 "variants.id",
182 "variants.sku",
183 ],
184 filters: {
185 q: input.q,
186 status: "published",
187 },
188 pagination: {
189 skip: 0,
190 take: 20,
191 },
192 })
193
194 return new StepResponse({
195 products: data,
196 metadata: search_result.metadata,
197 })
198 }
199 )
200 ```
201
202 ---
203
204 ## How Search Queries Work
205
206 When you pass `fields` to `query.search`, the Search Module splits them into two groups:
207
208 1. The fields the index holds. The provider returns them on every hit.
209 2. The remaining fields. `query.graph` fetches them, and they're merged to the returned `data`.
210
211 So you can request fields of relations that the index never stores, such as `variants.sku`, without adding them to the index definition.
212
213 ---
214
215 ## Select Specific Fields
216
217 Always list in `fields` the fields you need, rather than relying on the default or passing `{relation}.*`.
218
219 Selecting specific fields keeps the hydration query cheaper, and it keeps the response smaller. For example, instead of retrieving all properties of a product and its variants:
220
221 ```ts title="Avoid"
222 const { data } = await query.search({
223 entity: "product",
224 fields: ["*", "variants.*"],
225 filters: {
226 q: "shirt",
227 },
228 })
229 ```
230
231 Retrieve only the fields you use:
232
233 ```ts title="Prefer"
234 const { data } = await query.search({
235 entity: "product",
236 fields: [
237 "id",
238 "title",
239 "variants.id",
240 "variants.sku",
241 ],
242 filters: {
243 q: "shirt",
244 },
245 })
246 ```
247
248 ---
249
250 ## Apply Filters
251
252 The `search` method accepts a `filters` property, whose value is an object of filters to apply. Its keys are index field names, and its values are the values to filter on.
253
254 To perform a free-text search, pass the term in the `q` property. The Search Module lifts `q` out before it compiles the rest, so a provider never treats `q` as a field.
255
256 ```ts highlights={[["4"], ["5"], ["6"], ["7"]]}
257 const { data } = await query.search({
258 entity: "product",
259 fields: ["id", "title"],
260 filters: {
261 q: "running shoe",
262 status: "published",
263 },
264 })
265 ```
266
267 In this example, the search query looks for products that match the free-text term `"running shoe"` and also have a `status` of `"published"`.
268
269 <Note>
270
271 You can only filter on fields that the index definition marks as `filterable`. The Search Module validates the query against the definition before it reaches the provider, so an unsupported field fails with a clear error.
272
273 </Note>
274
275 You can also filter by multiple values of a field. For example:
276
277 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"], ["9"], ["10"]]}
278 const { data } = await query.search({
279 entity: "product",
280 fields: ["id", "title"],
281 filters: {
282 q: "shoe",
283 brand: [
284 "acme",
285 "borg",
286 ],
287 },
288 })
289 ```
290
291 ### Filter Operators
292
293 A filter value can be:
294
295 - A literal value performing an equality check, such as filtering by a specific status.
296
297 ```ts
298 const { data } = await query.search({
299 entity: "product",
300 fields: ["id", "title"],
301 filters: {
302 q: "shoe",
303 status: "published",
304 },
305 })
306 ```
307
308 - An array performing an "is one of" check, such as filtering by multiple brands.
309
310 ```ts
311 const { data } = await query.search({
312 entity: "product",
313 fields: ["id", "title"],
314 filters: {
315 q: "shoe",
316 brand: [
317 "acme",
318 "borg",
319 ],
320 },
321 })
322 ```
323
324 - An object of operators for advanced filtering, such as filtering by a minimum price.
325
326 ```ts
327 const { data } = await query.search({
328 entity: "product",
329 fields: ["id", "title"],
330 filters: {
331 q: "shoe",
332 min_price: {
333 $gte: 50,
334 },
335 },
336 })
337 ```
338
339 For object filters, you can use the following operators:
340
341 <TypeList types={[
342 {
343 name: "$eq",
344 type: "`any`",
345 description: "Equals a literal value."
346 },
347 {
348 name: "$ne",
349 type: "`any`",
350 description: "Doesn't equal a literal value."
351 },
352 {
353 name: "$in",
354 type: "`any[]`",
355 description: "Is one of the given values."
356 },
357 {
358 name: "$nin",
359 type: "`any[]`",
360 description: "Isn't one of the given values."
361 },
362 {
363 name: "$lt",
364 type: "`number` \| `Date`",
365 description: "The number or date is less than the given value."
366 },
367 {
368 name: "$lte",
369 type: "`number` \| `Date`",
370 description: "The number or date is less than or equal to the given value."
371 },
372 {
373 name: "$gt",
374 type: "`number` \| `Date`",
375 description: "The number or date is greater than the given value."
376 },
377 {
378 name: "$gte",
379 type: "`number` \| `Date`",
380 description: "The number or date is greater than or equal to the given value."
381 },
382 {
383 name: "$exists",
384 type: "`boolean`",
385 description: "Whether the field has a value."
386 },
387 {
388 name: "$contains",
389 type: "`any` \| `any[]`",
390 description: "An array field contains all of the given values."
391 },
392 {
393 name: "$overlaps",
394 type: "`any[]`",
395 description: "An array field contains at least one of the given values."
396 },
397 {
398 name: "$prefix",
399 type: "`string`",
400 description: "The value starts with the given string."
401 },
402 {
403 name: "$like",
404 type: "`string`",
405 description: "The value matches the given pattern."
406 }
407 ]} sectionTitle="Filter Operators" />
408
409 #### Filter by a Range
410
411 For example, to filter products by a price range:
412
413 ```ts highlights={[["6"], ["7"], ["8"], ["9"]]}
414 const { data } = await query.search({
415 entity: "product",
416 fields: ["id", "title"],
417 filters: {
418 q: "shoe",
419 min_price: {
420 $gte: 50,
421 $lte: 200,
422 },
423 },
424 })
425 ```
426
427 #### Filter an Array Field
428
429 For example, to filter products by tags that overlap with a given set:
430
431 ```ts highlights={[["6"], ["7"], ["8"], ["9"], ["10"]]}
432 const { data } = await query.search({
433 entity: "product",
434 fields: ["id", "title"],
435 filters: {
436 q: "shoe",
437 tags: {
438 $overlaps: [
439 "summer",
440 "sale",
441 ],
442 },
443 },
444 })
445 ```
446
447 In the example above, you retrieve the products having at least one of the `summer` and `sale` tags. Use `$contains` instead to require all of them.
448
449 #### Filter a Nested Field
450
451 For example, to filter products by a nested field:
452
453 ```ts highlights={[["6"]]}
454 const { data } = await query.search({
455 entity: "product",
456 fields: ["id", "title"],
457 filters: {
458 q: "shoe",
459 "variants.color": "olive",
460 },
461 })
462 ```
463
464 In the example above, you filter on a nested field of the index. The index definition must declare `variants.color` as `filterable`.
465
466 #### Combine Filters
467
468 You can nest conditions with the `$and`, `$or`, and `$not` operators:
469
470 ```ts highlights={[["6"], ["7"], ["8"], ["9"], ["10"], ["11"], ["12"]]}
471 const { data } = await query.search({
472 entity: "product",
473 fields: ["id", "title"],
474 filters: {
475 q: "shoe",
476 $or: [
477 { status: "published" },
478 { brand: { $eq: "acme" } },
479 ],
480 $not: {
481 tags: { $contains: "clearance" },
482 },
483 },
484 })
485 ```
486
487 In the example above, you retrieve the products that are either published or from the `acme` brand, excluding the ones tagged as `clearance`.
488
489 ---
490
491 ## Apply Pagination
492
493 The `search` method's object parameter accepts a `pagination` property to configure the pagination of returned hits.
494
495 For example:
496
497 ```ts highlights={[["9", "skip", "The number of hits to skip before returning the results."], ["10", "take", "The number of hits to return."]]}
498 const {
499 data,
500 search_result: { metadata },
501 } = await query.search({
502 entity: "product",
503 fields: ["id", "title"],
504 filters: { q: "shoe" },
505 pagination: {
506 skip: 0,
507 take: 15,
508 },
509 })
510 ```
511
512 In this example, the `pagination` property specifies that the search should skip the first `0` hits and return the next `15` hits.
513
514 `pagination` is optional. If you omit it, or omit one of its properties, the Search Module applies `skip: 0` and `take: 20`. So a search returns at most `20` hits unless you raise `take`.
515
516 <Note>
517
518 This is unlike `query.graph`, which returns every matching record when you don't pass `pagination`.
519
520 </Note>
521
522 <TypeList types={[
523 {
524 name: "skip",
525 type: "`number`",
526 description: "The number of hits to skip.",
527 defaultValue: "0"
528 },
529 {
530 name: "take",
531 type: "`number`",
532 description: "The number of hits to return.",
533 defaultValue: "20"
534 },
535 {
536 name: "order",
537 type: "`Record<string, \"ASC\" \| \"DESC\">`",
538 description: "An object mapping a sortable field to its sort direction. Refer to [Sort Hits](#sort-hits)."
539 },
540 {
541 name: "cursor",
542 type: "`string`",
543 description: "An opaque cursor from a previous result's `next_cursor`, for deep pagination. You can't pass it along with `skip`."
544 }
545 ]} sectionTitle="Apply Pagination" />
546
547 The result's `metadata` property is an object with the following properties:
548
549 <TypeList types={[
550 {
551 name: "skip",
552 type: "`number`",
553 description: "The number of hits skipped."
554 },
555 {
556 name: "take",
557 type: "`number`",
558 description: "The number of hits requested."
559 },
560 {
561 name: "count",
562 type: "`number` \| `null`",
563 description: "The total number of matching documents. It's `null` when you set the `count` search option to `none`."
564 },
565 {
566 name: "next_cursor",
567 type: "`string`",
568 description: "The cursor to pass in the next request's `pagination.cursor`, if the provider supports cursors."
569 },
570 {
571 name: "query",
572 type: "`string`",
573 description: "The free-text term the provider ran."
574 },
575 {
576 name: "processing_time_ms",
577 type: "`number`",
578 description: "The time the provider took to run the query, in milliseconds."
579 }
580 ]} sectionTitle="Apply Pagination" />
581
582 <Note>
583
584 No provider that Medusa ships supports `pagination.cursor`, so paginate with `skip` and `take`.
585
586 </Note>
587
588 ### Sort Hits
589
590 To sort the returned hits, pass an `order` property to `pagination`. Its value is an object whose keys are field names, and whose values are either `ASC` or `DESC`.
591
592 ```ts highlights={[["5"], ["6"], ["7"], ["8"]]}
593 const { data } = await query.search({
594 entity: "product",
595 fields: ["id", "title"],
596 filters: { q: "shoe" },
597 pagination: {
598 order: {
599 min_price: "ASC",
600 },
601 },
602 })
603 ```
604
605 The index definition must mark a field as `sortable` before you can order by it. The only exception is the reserved `_score` key, which orders by relevance:
606
607 ```ts highlights={[["6"]]}
608 const { data } = await query.search({
609 entity: "product",
610 fields: ["id", "title"],
611 filters: { q: "shoe" },
612 pagination: {
613 order: { _score: "DESC" },
614 },
615 })
616 ```
617
618 ### Change the Count Strategy
619
620 Counting every matching document can be expensive on a large index, so the `count` search option tells the provider how accurate the count has to be:
621
622 ```ts highlights={[["6"]]}
623 const { data } = await query.search({
624 entity: "product",
625 fields: ["id", "title"],
626 filters: { q: "shoe" },
627 search_options: {
628 count: "exact",
629 },
630 })
631 ```
632
633 `count` accepts one of the following values:
634
635 - `estimated` (default): The provider returns whichever count its engine can produce cheaply, which may be an estimate.
636 - `exact`: The provider counts every matching document.
637 - `none`: The provider skips the count query, and `metadata.count` is `null`. Use this when the page you're building never shows a total or page numbers, such as a storefront with a "Load more" button. To find out whether more hits exist, check whether the returned hits filled the page, meaning their number equals `take`.
638
639 <Note>
640
641 No provider that Medusa ships treats `exact` differently from `estimated`. All of them run a real count unless you pass `none`. The distinction only matters for a provider whose engine can't count exactly, which either rejects `exact` or runs it slowly.
642
643 </Note>
644
645 ---
646
647 ## Query Search Options
648
649 The `search_options` property of the `search` method's parameter object is an object of options passed to the provider to control how it treats the query. For example, you can tell it which fields to match the term against, whether to enable typo tolerance, and which facets to compute.
650
651 If a provider doesn't support an option, it either ignores it or throws an error. Refer to [Medusa Search vs PostgreSQL](!cloud!/search/postgres) for what each one does with the options below.
652
653 It accepts the following properties:
654
655 <TypeList types={[
656 {
657 name: "attributes_to_search_on",
658 type: "`string[]`",
659 description: "The searchable fields to match the `q` filter against.",
660 defaultValue: "Every field marked `searchable`"
661 },
662 {
663 name: "match_strategy",
664 type: "`\"all\"` \| `\"any\"` \| `\"last\"`",
665 description: "Whether a hit must match `all` the terms in the `q` filter, `any` of them, or all but the `last` one. Matching all but the last term suits as-you-type search, where the final word is still incomplete.\n\nThe Search Module sets no default, so omitting it falls back to the provider's own behavior. The PostgreSQL provider requires every term to match, which is equivalent to `all`."
666 },
667 {
668 name: "typo_tolerance",
669 type: "`boolean`",
670 description: "Whether to allow approximate matches for the terms in the `q` filter. It has no effect on the field filters, which always match exactly."
671 },
672 {
673 name: "facets",
674 type: "`(string \| object)[]`",
675 description: "The facets to compute. Refer to [Facets](#facets)."
676 },
677 {
678 name: "disjunctive_facets",
679 type: "`boolean`",
680 description: "Whether to compute each facet while ignoring the filter on that same field. Refer to [Disjunctive Facets](#disjunctive-facets)."
681 },
682 {
683 name: "highlight",
684 type: "`object`",
685 description: "Wraps the matched terms in the returned fields. Refer to [Highlighting](#highlighting)."
686 },
687 {
688 name: "distinct",
689 type: "`string`",
690 description: "A field to deduplicate on, so the provider returns at most one hit per distinct value. The count in `metadata.count` then counts the deduplicated hits.\n\nThe field must exist in the index, and it can't be an array or vector field."
691 },
692 {
693 name: "min_score",
694 type: "`number`",
695 description: "Discards the hits scoring below this threshold."
696 },
697 {
698 name: "include_score",
699 type: "`boolean`",
700 description: "Whether to return each hit's relevance score in its `score` property. Scores aren't comparable across providers."
701 },
702 {
703 name: "locales",
704 type: "`string[]`",
705 description: "A language hint for this query, such as `[\"en\"]`. Neither first-party provider honors it: a provider that can't apply it rejects the query rather than matching differently. Set the analyzer language on the provider (PostgreSQL) or on the field (Medusa Search) instead."
706 },
707 {
708 name: "vector",
709 type: "`object`",
710 description: "Runs a similarity search. Refer to [Vector and Hybrid Search](#vector-and-hybrid-search)."
711 },
712 {
713 name: "count",
714 type: "`\"estimated\"` \| `\"exact\"` \| `\"none\"`",
715 description: "How to count the matching documents. Refer to [Change the Count Strategy](#change-the-count-strategy).",
716 defaultValue: "estimated"
717 },
718 {
719 name: "provider_options",
720 type: "`Record<string, Record<string, unknown>>`",
721 description: "Provider features that the interface doesn't model, keyed by provider identifier. For example, `{ \"search-medusa\": { consistency: \"strong\" } }` asks the Medusa Search Module Provider for a strongly consistent read. The PostgreSQL provider accepts no query-time options."
722 }
723 ]} sectionTitle="Search Options" />
724
725 For example, to match any of the query's terms in the product's title only:
726
727 ```ts highlights={[["6"], ["7"], ["8"]]}
728 const { data } = await query.search({
729 entity: "product",
730 fields: ["id", "title"],
731 filters: { q: "comfortable running shoe" },
732 search_options: {
733 attributes_to_search_on: ["title"],
734 match_strategy: "any",
735 include_score: true,
736 },
737 })
738 ```
739
740 ---
741
742 ## Facets
743
744 Facets return the distinct values of a field and how many documents fall into each one, which is what a storefront's filter sidebar shows.
745
746 <Note>
747
748 A field must be marked `facetable` in the index definition. Learn more in the [Search Index Field Modifiers](!resources!/infrastructure-modules/search/index-definitions/modifiers) guide.
749
750 </Note>
751
752 Pass a field name for a value facet, or an object for more control:
753
754 ```ts highlights={[["6"], ["7"], ["8"], ["9"]]}
755 const { search_result } = await query.search({
756 entity: "product",
757 fields: ["id", "title"],
758 filters: { q: "shoe" },
759 search_options: {
760 facets: [
761 "brand",
762 { field: "status", limit: 5, sort: "count" },
763 ],
764 },
765 })
766 ```
767
768 There are three facet types:
769
770 - `value` (default): The distinct values of the field and their counts.
771 - `range`: The number of documents falling into each range you define. Available on numeric and date fields.
772 - `stats`: The minimum, maximum, average, sum, and count of the field.
773
774 For example, to compute a range facet and a stats facet on the same field:
775
776 ```ts
777 const { search_result } = await query.search({
778 entity: "product",
779 fields: ["id", "title"],
780 filters: { q: "shoe" },
781 search_options: {
782 facets: [
783 {
784 field: "min_price",
785 type: "range",
786 ranges: [
787 { key: "cheap", to: 50 },
788 { key: "mid", from: 50, to: 200 },
789 { key: "expensive", from: 200 },
790 ],
791 },
792 { field: "min_price", type: "stats" },
793 ],
794 },
795 })
796 ```
797
798 The facets are in the result's `facets` property, keyed by field name. For example:
799
800 ```json title="Returned Facets"
801 {
802 "facets": {
803 "min_price": {
804 "type": "range",
805 "ranges": [
806 { "key": "cheap", "to": 50, "count": 1 },
807 { "key": "mid", "from": 50, "to": 200, "count": 2 }
808 ]
809 }
810 }
811 }
812 ```
813
814 ### Disjunctive Facets
815
816 When a customer filters by one brand, a facet on `brand` normally returns only that brand. Set `disjunctive_facets` to `true` so the provider computes each facet while ignoring the filter on its own field, keeping the sibling values visible:
817
818 ```ts highlights={[["9"]]}
819 const { search_result } = await query.search({
820 entity: "product",
821 fields: ["id", "title"],
822 filters: {
823 q: "shoe",
824 brand: "acme",
825 },
826 search_options: {
827 facets: ["brand", "status"],
828 disjunctive_facets: true,
829 },
830 })
831 ```
832
833 The result's `facets` property then holds the following:
834
835 ```json title="Returned Facets"
836 {
837 "facets": {
838 "brand": {
839 "type": "value",
840 "values": [
841 { "value": "acme", "count": 12 },
842 { "value": "borg", "count": 7 },
843 { "value": "zeta", "count": 3 }
844 ]
845 },
846 "status": {
847 "type": "value",
848 "values": [
849 { "value": "published", "count": 10 },
850 { "value": "draft", "count": 2 }
851 ]
852 }
853 }
854 }
855 ```
856
857 The `brand` facet still lists `borg` and `zeta`, despite the `brand: "acme"` filter. A shopper can see how many results switching brands would give them.
858
859 The `status` facet is unaffected because the query didn't filter on `status`. So, its results only show the counts of published and draft products whose brand is `acme`.
860
861 ---
862
863 ## Highlighting
864
865 Highlighting wraps the matched terms in the fields you name, so a storefront can show why a result matched.
866
867 ```ts highlights={[["7"], ["8"], ["9"], ["10"]]}
868 const { search_result } = await query.search({
869 entity: "product",
870 fields: ["id", "title", "description"],
871 filters: { q: "shoe" },
872 search_options: {
873 highlight: {
874 fields: ["title", "description"],
875 pre_tag: "<mark>",
876 post_tag: "</mark>",
877 snippet: { length: 120 },
878 },
879 },
880 })
881 ```
882
883 `highlight` accepts the following properties:
884
885 <TypeList types={[
886 {
887 name: "fields",
888 type: "`string[]`",
889 description: "The fields to highlight the matched terms in."
890 },
891 {
892 name: "pre_tag",
893 type: "`string`",
894 description: "The string to insert before every matched term.",
895 defaultValue: "<mark>"
896 },
897 {
898 name: "post_tag",
899 type: "`string`",
900 description: "The string to insert after every matched term.",
901 defaultValue: "</mark>"
902 },
903 {
904 name: "snippet",
905 type: "`boolean` \| `{ length: number }`",
906 description: "Whether to crop a fragment around the match instead of returning the whole field. Pass an object to set the fragment's length."
907 }
908 ]} sectionTitle="Highlighting" />
909
910 The highlighted fragments are in each hit's `highlights` property, keyed by field name. Each key holds an array, since a field can match in more than one place:
911
912 ```json title="Returned Hits"
913 {
914 "hits": [
915 {
916 "id": "prod_123",
917 "document": {
918 "id": "prod_123",
919 "title": "Trail Running Shoe",
920 "description": "A light shoe for trails."
921 },
922 "highlights": {
923 "title": ["Trail Running <mark>Shoe</mark>"],
924 "description": ["A light <mark>shoe</mark> for trails."]
925 }
926 }
927 ]
928 }
929 ```
930
931 The `document` property keeps the original values, so render the `highlights` fragments only where you want the matched terms marked.
932
933 ---
934
935 ## Vector and Hybrid Search
936
937 A field declared with `search.vector(dimensions)` holds an embedding, which lets the provider rank results by semantic similarity instead of term matching.
938
939 <Note>
940
941 Learn more about vector fields in the [Search Index Fields](!resources!/infrastructure-modules/search/index-definitions/fields) guide.
942
943 </Note>
944
945 Pass text as `search_options.vector.query` for the provider's embedder to embed:
946
947 ```ts highlights={[["6"], ["7"], ["8"], ["9"]]}
948 const { data } = await query.search({
949 entity: "product",
950 fields: ["id", "title"],
951 search_options: {
952 vector: {
953 field: "title_embedding",
954 query: "comfortable shoes for long runs",
955 semantic_ratio: 0.7,
956 },
957 },
958 })
959 ```
960
961 Alternatively, pass a pre-computed embedding as `search_options.vector.value`:
962
963 ```ts highlights={[["7"]]}
964 const { data } = await query.search({
965 entity: "product",
966 fields: ["id", "title"],
967 search_options: {
968 vector: {
969 field: "title_embedding",
970 value: [0.021, -0.113, 0.884],
971 },
972 },
973 })
974 ```
975
976 `search_options.vector` accepts the following properties:
977
978 <TypeList types={[
979 {
980 name: "field",
981 type: "`string`",
982 description: "The vector field to compare the embedding against."
983 },
984 {
985 name: "value",
986 type: "`number[]`",
987 description: "Pre-computed embeddings. Its length must match the field's `dimensions`. You can't pass it along with `query`."
988 },
989 {
990 name: "query",
991 type: "`string`",
992 description: "The text to embed with the provider's configured embedder. You can't pass it along with `value`."
993 },
994 {
995 name: "semantic_ratio",
996 type: "`number`",
997 description: "How much the semantic ranking contributes to the result. `0` is keyword-only, `1` is semantic-only, and anything between is a hybrid search."
998 }
999 ]} sectionTitle="Vector and Hybrid Search" />