@hyperse-hub/hps-plugin-smart-search
Overview
@hyperse-hub/hps-plugin-smart-search supports a ranking strategy group model.
Each ranking dimension is implemented as one RankingFactorStrategy, and all
registered strategies are composed into the final ranking score.
This design allows the plugin to avoid hard dependencies on feature packages
such as Review, Favorites, and Lens. External packages can implement and register
their own strategies.
Ranking Strategy Group
Core Concepts
- Each ranking field is one strategy implementation.
- The strategy outputs a raw numeric value via
compute() (unless the weight
for that key is 0; see below).
- The system multiplies the raw value by
rankingRate from
SearchIndexRankingConfig (per channel and language).
- Final
ranking is the sum of all weighted strategy values.
- Strategy not registered means effective value is
0.
Ranking factor calculation
This section matches the indexer logic in SearchRankingIndexerController when
building SearchIndexRankingItem for each product variant, channel, and
language code.
Weight lookup (rankingRate)
- Weights are read from
SearchIndexRankingConfig rows where rankingType
equals the strategy key, and channelId / languageCode match the current
indexing context.
- If no row exists for that triple, the weight defaults to 1 (same as
the bootstrap default for new config rows).
- If a row exists,
rankingRate is read as a number. Non-finite values fall
back to 1.
- On create/update via the admin API,
rankingRate is normalized to the
inclusive range 0–100 (invalid input is treated as 0 before clamping).
Per-strategy step
For each registered RankingFactorStrategy, in registration order:
- Resolve the weight
w as above.
- If
**w === 0**: compute() is not invoked. The raw factor stored in
factors[key] is 0, and the composite score gets **no*_ contribution
from this strategy (0 _ w).
- If
**w !== 0**: raw = await strategy.compute(ctx, product, variant).
Then factors[key] = raw and the running total is updated with
**ranking += raw \* w\*\*.
Stored fields
**SearchIndexRankingItem.ranking*_: sum of raw _ rankingRate over all
strategies for that variant / channel / language.
**SearchIndexRankingItem.factors**: map of raw values per strategy key
only; weights are not applied inside this map.
Strategy Contract
export interface RankingFactorStrategy {
readonly key: string;
init?(injector: Injector): void | Promise<void>;
compute(
ctx: RequestContext,
product: Product,
variant: ProductVariant
): Promise<number>;
}
Key Design
key is intentionally an open string, not a SearchIndexRankingType enum.
This allows external plugins to define unlimited ranking dimensions without
needing to modify the core plugin's enum or regenerate shared types first.
Recommended typing:
export interface RankingFactorStrategy {
readonly key: string;
}
Recommended naming rules:
- keep the key globally unique
- keep the key stable once data/config has been created
- use a descriptive suffix such as
Ranking
- use the exact same key in
SearchIndexRankingConfig.rankingType
Examples:
addToCartRanking
checkoutPaidRanking
checkoutWaitingPayRanking
reviewRanking
favoriteRanking
lensStepT1Ranking
lensStepT2Ranking
lensStepT3Ranking
lensStepT4Ranking
reviewUserShowRanking
customCampaignBoostRanking
Built-in Strategies
Built-in (no external plugin dependency):
AddToCartRankingFactor
CheckoutPaidRankingFactor
CheckoutWaitingPayRankingFactor
These are exported from:
import {
AddToCartRankingFactor,
CheckoutPaidRankingFactor,
CheckoutWaitingPayRankingFactor,
} from '@hyperse-hub/hps-plugin-smart-search';
External Strategy Integration
External plugins can provide strategies without introducing hard coupling in
this package.
Example (reviewRanking strategy in another package):
import type {
Injector,
Product,
ProductVariant,
RequestContext,
} from '@vendure/core';
import type { ProductReviewReportingService } from '@hyperse-hub/hps-plugin-review';
import type { RankingFactorStrategy } from '@hyperse-hub/hps-plugin-smart-search';
export class ReviewRankingFactor implements RankingFactorStrategy {
readonly key = 'reviewRanking';
private service: ProductReviewReportingService;
async init(injector: Injector) {
this.service = injector.get(ProductReviewReportingService);
}
async compute(
ctx: RequestContext,
product: Product,
variant: ProductVariant
): Promise<number> {
return this.service.calculateProductVariantTotalReviews(
ctx,
product,
variant
);
}
}
Register strategies:
import {
HpsPluginSmartSearch,
AddToCartRankingFactor,
CheckoutPaidRankingFactor,
CheckoutWaitingPayRankingFactor,
} from '@hyperse-hub/hps-plugin-smart-search';
plugins: [
HpsPluginSmartSearch.init({
rankingFactors: [
new AddToCartRankingFactor(),
new CheckoutPaidRankingFactor(),
new CheckoutWaitingPayRankingFactor(),
new ReviewRankingFactor(),
new FavoriteRankingFactor(),
new LensStepT1RankingFactor(),
],
}),
];
Data and Defaults
SearchIndexRankingItem.ranking stores the aggregated weighted score.
SearchIndexRankingItem.factors stores per-strategy raw values (weights
apply only when summing ranking; see Ranking factor calculation).
- Missing factor key is treated as
0 during ranking composition.
- Ranking config bootstrap seeds default
SearchIndexRankingConfig records for
all channels, each channel language, and each registered rankingFactors[].key.
SearchIndexItem.position uses this precedence order:
ProductVariant.customFields.ranking
Product.customFields.ranking
- computed strategy ranking (
SearchIndexRankingItem.ranking)
- For level (1) and (2), only non-zero values override lower-priority levels.
This means positive values can boost ranking and negative values can lower
ranking.
- If a level value is
0, null, or undefined, resolution falls through to
the next level.
Best Practices
- Keep strategy
compute() pure and focused on a single metric.
- Avoid cross-strategy coupling and combine only in ranking aggregator.
- Keep
key globally unique and stable over time.
- If introducing a new ranking dimension, define the strategy key and register
the strategy. Missing
SearchIndexRankingConfig rows are auto-seeded during
bootstrap for all channels/languages.
Custom Product Mappings
HpsPluginSmartSearch supports declarative custom mappings aligned with the
Typesense plugin API shape. Mappings write values into SearchIndexItem at index
time and expose them on the Shop/Admin search query.
Configuration
valueFn receives (ctx, context) and may return a value synchronously or as a
Promise. Product mappings get { product, productVariants, languageCode, injector };
variant mappings get { variant, languageCode, injector }.
HpsPluginSmartSearch.init({
hydrateProductRelations: ['facetValues.facet', 'customFields.icon'],
customProductMappings: {
reviewRating: {
graphQlType: 'Float',
filterable: true,
sortable: true,
valueFn: (_ctx, { product }) =>
(product.customFields as any).reviewRating ?? 0,
},
brandCode: {
graphQlType: 'String',
searchable: true,
valueFn: (_ctx, { product }) => (product.customFields as any).brandCode,
},
iconPreview: {
graphQlType: 'String',
public: true,
valueFn: async (ctx, { product, injector }) => {
const preview = product.customFields?.icon?.preview;
if (!preview) return null;
const cdn = injector.get(CdnService);
return cdn.toAbsoluteUrl(ctx, preview);
},
},
},
customProductVariantMappings: {
weight: {
graphQlType: 'Int',
sortable: true,
aggregate: 'min',
valueFn: (_ctx, { variant }) => (variant.customFields as any).weight ?? 0,
},
},
});
GraphQL
Shop API — typed public fields only:
query SearchProducts($input: SearchInput!) {
search(input: $input) {
items {
productId
customProductMappings {
reviewRating
brandCode
}
customProductVariantMappings {
weight
}
}
}
}
Admin API — additionally exposes full indexed JSON (including public: false):
query SearchProducts($input: SearchInput!) {
search(input: $input) {
items {
productId
customMappings
customProductMappings {
reviewRating
}
}
}
}
Index storage
- All mappings are stored in
SearchIndexItem.customMappings JSON.
- Mappings with
filterable, sortable, or searchable also populate typed
columns (cm_p_*, cm_v_*) for SQL filtering, sorting, and text matching.
- List types (e.g.
[String!]) are JSON-only: filterable / sortable /
searchable on list mappings throws at plugin init() time.
- Variant mappings support
aggregate: 'min' | 'max' when groupByProduct is
enabled.
public: false mappings are indexed but omitted from Shop API typed
fields (customProductMappings / customProductVariantMappings). Admin API
always exposes customMappings: JSON on SearchResult (returns null when
no custom mappings are configured; otherwise returns the full indexed
payload including private fields). Shop API does not expose customMappings.
- Prefer nullable GraphQL scalars (
Float, String) over Float! when
valueFn can return null — otherwise GraphQL may error at query time.
Configuration validation
HpsPluginSmartSearch.init() validates custom mapping options and throws if:
- A list
graphQlType uses filterable, sortable, or searchable.
- A filter/sort field name collides with built-in
SearchInput or
SearchResultSortParameter fields (e.g. term, price, inStock).
extendSearchInputType / extendSearchSortType keys collide with built-in or
auto-generated mapping fields.
Product and variant mappings with the same name automatically use
product_<name> / variant_<name> for filter and sort inputs.
groupByProduct filter semantics
When groupByProduct: true:
| Mapping scope | Filter behaviour |
|---|
Product (cm_p_*) | WHERE on each variant row (values are identical per product). |
Variant (cm_v_*) | HAVING MIN/MAX(cm_v_*) after grouping — controlled by aggregate. |
Example: weight: { filter: { gte: 100 } } with aggregate: 'min' means the
lightest variant must be ≥ 100g, not “any variant ≥ 100g”.
Plugin init behaviour
- Each
init() merges from default options + your config, not from the
previous init() call — avoids stale mappings in tests and reloads.
- Dynamic index columns are registered at
init() time; changing mappings
requires process restart, DB schema sync, and a full reindex.
Database notes
- MySQL / MariaDB: full-text (
searchable) and StringOperators.regex
filters are supported.
- SQLite: uses
LIKE instead of full-text; regex filters may not work
unless a REGEXP extension is loaded.
Reindex required
Adding or changing custom mapping configuration requires a full search reindex.
Use the Admin API reindex mutation after updating plugin options.
Escape hatches
extendSearchInputType adds arbitrary SearchInput fields to the GraphQL
schema only — the default MySQL/SQLite strategies do not read them unless
you provide a custom searchStrategy.
extendSearchSortType adds arbitrary SearchResultSortParameter fields under
the same constraint.
searchStrategy remains available for fully custom query behaviour.