export const FIELD_TYPES = [ "TEXT", "U64", "I64", "F64", "BOOL", "DATE", "KEYWORD", "FACET", "HYBRID", ] as const; export type FieldType = (typeof FIELD_TYPES)[number]; export type TextField = { type: "TEXT"; noTokenize?: boolean; noStem?: boolean; from?: string; }; export type NumericField = { type: "U64" | "I64" | "F64"; fast: true; from?: string; }; export type BoolField = { type: "BOOL"; fast?: boolean; from?: string; }; export type DateField = { type: "DATE"; fast?: boolean; from?: string; }; export type KeywordField = { type: "KEYWORD"; }; export type FacetField = { type: "FACET"; }; /** * A TEXT field that also stores a vector embedding, so it can be searched by meaning with `$ann`. * * @see https://upstash.com/docs/redis/search/hybrid-search */ export type HybridField = { type: "HYBRID"; noStem?: boolean; from?: string; }; export type DetailedField = | TextField | HybridField | NumericField | BoolField | DateField | KeywordField | FacetField; export type NestedIndexSchema = { [key: string]: FieldType | DetailedField | NestedIndexSchema; }; export type FlatIndexSchema = { [key: string]: FieldType | DetailedField; }; export type SchemaPaths = { [K in keyof T]: K extends string ? T[K] extends FieldType | DetailedField ? Prefix extends "" ? K : `${Prefix}${K}` : T[K] extends object ? SchemaPaths : never : never; }[keyof T]; export type ExtractFieldType = T extends FieldType ? T : T extends { type: infer U } ? U extends FieldType ? U : never : never; export type GetFieldAtPath< TSchema, Path extends string, > = Path extends `${infer First}.${infer Rest}` ? First extends keyof TSchema ? GetFieldAtPath : never : Path extends keyof TSchema ? TSchema[Path] : never; type FieldValueType = T extends "TEXT" | "HYBRID" ? string : T extends "U64" | "I64" | "F64" ? number : T extends "BOOL" ? boolean : T extends "DATE" ? string : T extends "KEYWORD" ? string : T extends "FACET" ? string : never; type GetFieldValueType = GetFieldAtPath extends infer Field ? Field extends FieldType | DetailedField ? FieldValueType> : never : never; // Helper type to check if a field has a 'from' property type HasFrom = T extends { from: string } ? true : false; // Distributes field inference across unions so that // InferSchemaData does not collapse to never type InferSchemaDataField = T extends FieldType ? FieldValueType : T extends DetailedField ? FieldValueType> : T extends NestedIndexSchema ? InferSchemaData : unknown; type IsDefaultSchema = [T] extends [NestedIndexSchema | FlatIndexSchema] ? [NestedIndexSchema | FlatIndexSchema] extends [T] ? true : false : false; type AsAnyIfUnknown = unknown extends T ? any : T; export type InferSchemaData = IsDefaultSchema extends true ? any : { [K in keyof TSchema as TSchema[K] extends DetailedField ? HasFrom extends true ? never : K : K]: AsAnyIfUnknown>; }; // Query Options Types // These are the options that can be used for the query command // Short-circuit to permissive types when schema is the default (any) to avoid // excessively deep type instantiation. export type QueryOptions = IsDefaultSchema extends true ? { filter?: Record; limit?: number; offset?: number; select?: Record; highlight?: { fields: string[]; preTag?: string; postTag?: string; }; orderBy?: Record; scoreFunc?: ScoreBy; } : { filter?: RootQueryFilter | Retriever; /** Maximum number of results to return */ limit?: number; /** Number of results to skip */ offset?: number; select?: Partial<{ [K in SchemaPaths]: true }>; // {} highlight?: { fields: SchemaPaths[]; preTag?: string; postTag?: string; }; } & QueryOrderOption; type CombineMode = "multiply" | "sum"; type ScoreMode = "multiply" | "sum" | "replace"; type ScoreModifier = | "none" | "log" | "log1p" | "log2p" | "ln" | "ln1p" | "ln2p" | "square" | "sqrt" | "reciprocal"; export type ScoreBy = | ScoreByField | { fields: ScoreByField[]; combineMode?: CombineMode; scoreMode?: ScoreMode; }; type ScoreByField = | { field: TSchemaPaths; modifier?: ScoreModifier; factor?: number; missing?: number; scoreMode?: TMultiple extends true ? never : ScoreMode; } | TSchemaPaths; type QueryOrderOption = | { orderBy?: { [K in SchemaPaths]: { [P in K]: "ASC" | "DESC" }; }[SchemaPaths]; } | { scoreFunc?: ScoreBy>; }; /** * Converts dot notation paths to nested object structure type * e.g. "content.title" | "content.author" becomes { content: { title: ..., author: ... } } */ type PathToNestedObject< TSchema, Path extends string, Value, > = Path extends `${infer First}.${infer Rest}` ? { [K in First]: PathToNestedObject } : { [K in Path]: Value }; /** * Merges intersection of objects into a single object type with proper nesting */ type DeepMerge = T extends object ? { [K in keyof T]: T[K] extends object ? DeepMerge : T[K]; } : T; /** * Build nested result type from selected paths */ type BuildNestedResult = IsDefaultSchema extends true ? DeepMerge< UnionToIntersection< { [Path in keyof TFields & string]: PathToNestedObject; }[keyof TFields & string] > > : DeepMerge< UnionToIntersection< { [Path in keyof TFields & SchemaPaths]: PathToNestedObject< TSchema, Path & string, AsAnyIfUnknown> >; }[keyof TFields & SchemaPaths] > >; type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends ( k: infer I ) => void ? I : never; export type QueryResult< TSchema extends NestedIndexSchema | FlatIndexSchema, TOptions extends QueryOptions | undefined = undefined, > = TOptions extends { select: infer TFields } ? // eslint-disable-next-line @typescript-eslint/no-empty-object-type {} extends TFields ? { key: string; score: number } : { key: string; score: number; data: BuildNestedResult; } : { key: string; score: number; data: InferSchemaData; }; export type PublicQueryResult< TSchema extends NestedIndexSchema | FlatIndexSchema, TSelectFields extends SchemaPaths[] | undefined = undefined, > = QueryResult< TSchema, TSelectFields extends SchemaPaths[] ? { select: { [K in TSelectFields[number]]: true }; } : undefined >; // Query Filter Types // These are the operations that can be used for each field type type StringOperationMap = { $eq: T; $in: T[]; $fuzzy: T | { value: T; distance?: number; transpositionCostOne?: boolean; prefix?: boolean }; $phrase: | T | { value: T } | { value: T; slop: number; prefix?: never } | { value: T; prefix: boolean; slop?: never }; $regex: T; $smart: T; }; type NumberOperationMap = { $eq: T; $in: T[]; $gt: T; $gte: T; $lt: T; $lte: T; }; type KeywordOperationMap = { $eq: T; $in: T[]; $gt: T; $gte: T; $lt: T; $lte: T; }; type BooleanOperationMap = { $eq: T; $in: T[]; }; type DateOperationMap = { $eq: T; $in: T[]; $gt: T; $gte: T; $lte: T; $lt: T; }; type FacetOperationMap = { $eq: T; $in: T[]; }; // Create union types for each field type type StringOperations = { [K in keyof StringOperationMap]: { [P in K]: StringOperationMap[K] } & { $boost?: number; }; }[keyof StringOperationMap]; type NumberOperations = { [K in keyof NumberOperationMap]: { [P in K]: NumberOperationMap[K] } & { $boost?: number; }; }[keyof NumberOperationMap]; type BooleanOperations = { [K in keyof BooleanOperationMap]: { [P in K]: BooleanOperationMap[K] } & { $boost?: number; }; }[keyof BooleanOperationMap]; type DateOperations = { [K in keyof DateOperationMap]: { [P in K]: DateOperationMap[K] } & { $boost?: number; }; }[keyof DateOperationMap]; type KeywordOperations = { [K in keyof KeywordOperationMap]: { [P in K]: KeywordOperationMap[K] } & { $boost?: number; }; }[keyof KeywordOperationMap]; type FacetOperations = { [K in keyof FacetOperationMap]: { [P in K]: FacetOperationMap[K] } & { $boost?: number; }; }[keyof FacetOperationMap]; // Create a union type for all operations for a given field type type OperationsForFieldType = T extends "TEXT" | "HYBRID" ? StringOperations : T extends "U64" | "I64" | "F64" ? NumberOperations : T extends "BOOL" ? BooleanOperations : T extends "DATE" ? DateOperations : T extends "KEYWORD" ? KeywordOperations : T extends "FACET" ? FacetOperations : never; // Create a union type for all operations for a given path type PathOperations = GetFieldAtPath extends infer Field ? Field extends FieldType | DetailedField ? OperationsForFieldType> | FieldValueType> : never : never; // Create a type for a query leaf (only field paths, no boolean operators) type QueryLeaf = { // allowed schema paths [K in SchemaPaths]?: PathOperations; } & { $and?: never; $or?: never; $must?: never; $should?: never; $mustNot?: never; $boost?: number; }; type BoolBase = { [P in SchemaPaths]?: PathOperations; }; // $and: all conditions must match type AndNode = BoolBase & { $and: QueryFilter | QueryFilter[]; $boost?: number; $or?: never; $must?: never; $should?: never; $mustNot?: never; }; // $or: at least one condition must match type OrNode = BoolBase & { $or: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $must?: never; $should?: never; $mustNot?: never; }; // $must only type MustNode = BoolBase & { $must: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $or?: never; $should?: never; $mustNot?: never; }; // $should only type ShouldNode = BoolBase & { $should: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $or?: never; $must?: never; $mustNot?: never; }; // $must + $should combined type MustShouldNode = BoolBase & { $must: QueryFilter | QueryFilter[]; $should: QueryFilter | QueryFilter[]; $and?: never; $or?: never; }; // $mustNot only type NotNode = BoolBase & { $mustNot: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $or?: never; $must?: never; $should?: never; }; type AndNotNode = BoolBase & { $and: QueryFilter | QueryFilter[]; $mustNot: QueryFilter | QueryFilter[]; $boost?: number; $or?: never; $must?: never; $should?: never; }; type OrNotNode = BoolBase & { $or: QueryFilter | QueryFilter[]; $mustNot: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $must?: never; $should?: never; }; // $should + $mustNot combined type ShouldNotNode = BoolBase & { $should: QueryFilter | QueryFilter[]; $mustNot: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $or?: never; $must?: never; }; type MustNotNode = BoolBase & { $must: QueryFilter | QueryFilter[]; $mustNot: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $or?: never; $should?: never; }; // Full boolean node: $must + $should + $mustNot type BoolNode = BoolBase & { $must: QueryFilter | QueryFilter[]; $should: QueryFilter | QueryFilter[]; $mustNot: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $or?: never; }; // Create a type for a query filter // Short-circuit to Record when schema is the default (any) to avoid // excessively deep type instantiation from the recursive filter union types. export type QueryFilter = IsDefaultSchema extends true ? Record : | QueryLeaf | AndNode | OrNode | MustNode | ShouldNode | MustShouldNode | NotNode | AndNotNode | OrNotNode | ShouldNotNode | MustNotNode | BoolNode; // Create a type for root-level queries (restricts $or from mixing with fields) export type RootQueryFilter = IsDefaultSchema extends true ? Record : | QueryLeaf | AndNode | RootOrNode | MustNode | ShouldNode | MustShouldNode | AndNotNode | ShouldNotNode | BoolNode; // Restricted version of OrNode that doesn't allow field operations at root level type RootOrNode = { [P in SchemaPaths]?: never; // No field operations at root level with $or } & { $or: QueryFilter | QueryFilter[]; $boost?: number; $and?: never; $must?: never; $should?: never; $mustNot?: QueryFilter | QueryFilter[]; }; // Retrievers // @see https://upstash.com/docs/redis/search/retrievers/overview /** * Runs a semantic search on a HYBRID field. * * @see https://upstash.com/docs/redis/search/retrievers/ann */ export type AnnRetriever = { $ann: { /** The HYBRID field to search */ field: IsDefaultSchema extends true ? string : HybridPaths; /** The text to search for. Cannot be empty. */ query: string; /** Accuracy and speed trade-off. Defaults to `balanced`. */ profile?: "fast" | "balanced" | "precise"; /** Only documents that match this query are returned */ filter?: RootQueryFilter; /** Scales how much the results add to the `$rrf` score. Valid only inside `$rrf`. */ weight?: number; }; }; /** * Runs one query. Use it inside `$rrf` to set the weight of a query. * * @see https://upstash.com/docs/redis/search/retrievers/standard */ export type StandardRetriever = { $standard: { query: RootQueryFilter; /** Scales how much the query adds to the `$rrf` score. Valid only inside `$rrf`. */ weight?: number; }; }; /** * Merges the results of 2 to 10 retrievers with Reciprocal Rank Fusion. * * @see https://upstash.com/docs/redis/search/retrievers/rrf */ export type RrfRetriever< TSchema extends NestedIndexSchema | FlatIndexSchema, TAllowAnn extends boolean = true, > = { $rrf: { /** 2 to 10 retrievers to merge */ retrievers: ( | RootQueryFilter | StandardRetriever | (TAllowAnn extends true ? AnnRetriever : never) )[]; /** Higher values give lower-ranked results more influence. Defaults to `60`. */ rankConstant?: number; /** The number of results each retriever contributes. Defaults to `LIMIT`. */ window?: number; }; }; export type Retriever = | AnnRetriever | StandardRetriever | RrfRetriever; /** * Retrievers accepted by `SEARCH.COUNT` and `SEARCH.AGGREGATE`, which do not support `$ann`. */ export type CountRetriever = | StandardRetriever | RrfRetriever; // Helper type to extract only HYBRID field paths from schema export type HybridPaths = { [K in keyof T]: K extends string ? T[K] extends "HYBRID" | { type: "HYBRID" } ? Prefix extends "" ? K : `${Prefix}${K}` : T[K] extends FieldType | DetailedField ? never : T[K] extends object ? HybridPaths : never : never; }[keyof T]; export type DescribeFieldInfo = { type: FieldType; noTokenize?: boolean; noStem?: boolean; fast?: boolean; from?: string; }; export type IndexDescription = { name: string; dataType: "hash" | "string" | "json" | "stream"; /** * Key prefixes tracked by the index. For a stream index, this holds the single stream key. */ prefixes: string[]; language?: Language; schema: IsDefaultSchema extends true ? Record : Record, DescribeFieldInfo>; }; export type Language = | "english" | "arabic" | "danish" | "dutch" | "finnish" | "french" | "german" | "greek" | "hungarian" | "italian" | "norwegian" | "portuguese" | "romanian" | "russian" | "spanish" | "swedish" | "tamil" | "turkish"; // Helper type to extract only FACET field paths from schema export type FacetPaths = { [K in keyof T]: K extends string ? T[K] extends "FACET" | { type: "FACET" } ? Prefix extends "" ? K : `${Prefix}${K}` : T[K] extends FieldType | DetailedField ? never : T[K] extends object ? FacetPaths : never : never; }[keyof T]; // Aggregate Types export type AggregateOptions = IsDefaultSchema extends true ? { filter?: Record; aggregations: { [key: string]: Record; }; } : { filter?: RootQueryFilter | CountRetriever; aggregations: { [key: string]: Aggregation; }; }; export type Aggregation = IsDefaultSchema extends true ? Record : | TermsAggregation | RangeAggregation | HistogramAggregation | StatsAggregation | AvgAggregation | SumAggregation | MinAggregation | MaxAggregation | CountAggregation | ExtendedStatsAggregation | PercentilesAggregation | CardinalityAggregation | FacetAggregation; type BaseAggregation = { $aggs?: { [key: string]: Aggregation; }; }; export type TermsAggregation = BaseAggregation & { $terms: { field: SchemaPaths; size?: number; }; }; export type RangeAggregation = BaseAggregation & { $range: { field: SchemaPaths; ranges: { from?: number; to?: number }[]; }; }; export type HistogramAggregation = BaseAggregation & { $histogram: { field: SchemaPaths; interval: number; }; }; export type StatsAggregation = BaseAggregation & { $stats: { field: SchemaPaths; missing?: number; }; }; export type AvgAggregation = BaseAggregation & { $avg: { field: SchemaPaths; missing?: number; }; }; export type SumAggregation = BaseAggregation & { $sum: { field: SchemaPaths; missing?: number; }; }; export type MinAggregation = BaseAggregation & { $min: { field: SchemaPaths; missing?: number; }; }; export type MaxAggregation = BaseAggregation & { $max: { field: SchemaPaths; missing?: number; }; }; export type CountAggregation = BaseAggregation & { $count: { field: SchemaPaths; }; }; export type ExtendedStatsAggregation = BaseAggregation & { $extendedStats: { field: SchemaPaths; sigma?: number; missing?: number; }; }; export type PercentilesAggregation = BaseAggregation & { $percentiles: { field: SchemaPaths; percents?: number[]; keyed?: boolean; missing?: number; }; }; export type CardinalityAggregation = BaseAggregation & { $cardinality: { field: SchemaPaths; }; }; export type FacetAggregation = BaseAggregation & { $facet: { field: FacetPaths; path: string; depth?: number; size?: number; minDocCount?: number; order?: { count: "desc" | "asc" }; }; }; export type AggregateResult< TSchema extends NestedIndexSchema | FlatIndexSchema, TOpts extends AggregateOptions, > = IsDefaultSchema extends true ? Record : BuildAggregateResult< TSchema, Extract }> >; type BuildAggregateResult< TSchema extends NestedIndexSchema | FlatIndexSchema, TAggs extends { [key: string]: Aggregation }, > = { [K in keyof TAggs]: TAggs[K] extends TermsAggregation ? TermsResult : TAggs[K] extends RangeAggregation ? RangeResult : TAggs[K] extends HistogramAggregation ? HistogramResult : TAggs[K] extends StatsAggregation ? StatsResult : TAggs[K] extends AvgAggregation ? MetricValueResult : TAggs[K] extends SumAggregation ? MetricValueResult : TAggs[K] extends MinAggregation ? MetricValueResult : TAggs[K] extends MaxAggregation ? MetricValueResult : TAggs[K] extends CountAggregation ? MetricValueResult : TAggs[K] extends CardinalityAggregation ? MetricValueResult : TAggs[K] extends ExtendedStatsAggregation ? ExtendedStatsResult : TAggs[K] extends PercentilesAggregation ? PercentilesResult : TAggs[K] extends FacetAggregation ? FacetResult : never; }; type Bucket = { key: T; docCount: number; from?: number; to?: number; }; type TermsResult< TSchema extends NestedIndexSchema | FlatIndexSchema, TAgg extends TermsAggregation, > = TAgg["$aggs"] extends { [key: string]: Aggregation } ? { buckets: (Bucket> & BuildAggregateResult)[]; sumOtherDocCount: number; docCountErrorUpperBound: number; } : { buckets: Bucket>[]; sumOtherDocCount: number; docCountErrorUpperBound: number; }; type RangeResult< TSchema extends NestedIndexSchema | FlatIndexSchema, TAgg extends RangeAggregation, > = TAgg["$aggs"] extends { [key: string]: Aggregation } ? { buckets: (Bucket & BuildAggregateResult)[]; } : { buckets: Bucket[]; }; type HistogramResult< TSchema extends NestedIndexSchema | FlatIndexSchema, TAgg extends HistogramAggregation, > = TAgg["$aggs"] extends { [key: string]: Aggregation } ? { buckets: (Bucket & BuildAggregateResult)[]; } : { buckets: Bucket[]; }; type MetricValueResult = { value: number; }; type StatsResult = { count: number; min: number; max: number; sum: number; avg: number; }; type ExtendedStatsResult<_TAgg> = { count: number; min: number; max: number; avg: number; sum: number; sumOfSquares: number; variance: number; variancePopulation: number; varianceSampling: number; stdDeviation: number; stdDeviationPopulation: number; stdDeviationSampling: number; stdDeviationBounds: { upper: number; lower: number; upperSampling: number; lowerSampling: number; upperPopulation: number; lowerPopulation: number; }; }; type PercentilesResult = TAgg extends { $percentiles: { keyed: false } } ? { values: Array<{ key: number; value: number }>; } : { values: { [key: string]: number }; }; type FacetChildNode = { path: string; docCount: number; sumOtherDocCount: number; children?: FacetChildNode[]; }; type FacetResult = { path: string; sumOtherDocCount: number; children: FacetChildNode[]; };