import {z} from 'zod' export type ReadConsistencyType = 'majority' | 'quorum' | 'all'; export type ReadConsistency = number | ReadConsistencyType; export type ShardKey = string | number; export type ShardKeyWithFallback = {target: ShardKey, fallback: ShardKey}; export type ShardKeySelector = ShardKey | Array | ShardKeyWithFallback; export type SparseVector = {indices: Array, values: Array}; export type ExtendedPointId = number | string; export type TokenizerType = 'prefix' | 'whitespace' | 'word' | 'multilingual' | 'code'; export type Language = 'arabic' | 'azerbaijani' | 'basque' | 'bengali' | 'catalan' | 'chinese' | 'danish' | 'dutch' | 'english' | 'finnish' | 'french' | 'german' | 'greek' | 'hebrew' | 'hinglish' | 'hungarian' | 'indonesian' | 'italian' | 'japanese' | 'kazakh' | 'nepali' | 'norwegian' | 'portuguese' | 'romanian' | 'russian' | 'slovene' | 'spanish' | 'swedish' | 'tajik' | 'turkish'; export type StopwordsSet = {languages?: (Array | null) | undefined, custom?: (Array | null) | undefined}; export type StopwordsInterface = Language | StopwordsSet; export type Snowball = 'snowball'; export type SnowballLanguage = 'arabic' | 'armenian' | 'danish' | 'dutch' | 'english' | 'finnish' | 'french' | 'german' | 'greek' | 'hungarian' | 'italian' | 'norwegian' | 'portuguese' | 'romanian' | 'russian' | 'spanish' | 'swedish' | 'tamil' | 'turkish'; export type SnowballParams = {type: Snowball, language: SnowballLanguage}; export type NoStemmer = 'none'; export type DisabledStemmerParams = {type: NoStemmer}; export type StemmingAlgorithm = SnowballParams | DisabledStemmerParams; export type Bm25Config = {k?: number | undefined, b?: number | undefined, avg_len?: number | undefined, tokenizer?: TokenizerType | undefined, language?: (string | null) | undefined, lowercase?: (boolean | null) | undefined, ascii_folding?: (boolean | null) | undefined, stopwords?: (StopwordsInterface | unknown) | undefined, stemmer?: (StemmingAlgorithm | unknown) | undefined, min_token_len?: (number | null) | undefined, max_token_len?: (number | null) | undefined}; export type DocumentOptions = {[key: string]: unknown} | Bm25Config; export type Document = {text: string, model: string, options?: (DocumentOptions | unknown) | undefined}; export type Image = {image: string, model: string, options?: ({[key: string]: unknown} | null) | undefined}; export type InferenceObject = {object: unknown, model: string, options?: ({[key: string]: unknown} | null) | undefined}; export type VectorInput = Array | SparseVector | Array> | ExtendedPointId | Document | Image | InferenceObject; export type Mmr = {diversity?: (number | null) | undefined, candidates_limit?: (number | null) | undefined}; export type NearestQuery = {nearest: VectorInput, mmr?: (Mmr | unknown) | undefined}; export type RecommendStrategy = 'average_vector' | 'best_score' | 'sum_scores'; export type RecommendInput = {positive?: (Array | null) | undefined, negative?: (Array | null) | undefined, strategy?: (RecommendStrategy | unknown) | undefined}; export type RecommendQuery = {recommend: RecommendInput}; export type ContextPair = {positive: VectorInput, negative: VectorInput}; export type DiscoverInput = {target: VectorInput, context: ContextPair | Array | unknown}; export type DiscoverQuery = {discover: DiscoverInput}; export type ContextInput = ContextPair | Array | unknown; export type ContextQuery = {context: ContextInput}; export type Direction = 'asc' | 'desc'; export type StartFrom = number | number | string; export type OrderBy = {key: string, direction?: (Direction | unknown) | undefined, start_from?: (StartFrom | unknown) | undefined}; export type OrderByInterface = string | OrderBy; export type OrderByQuery = {order_by: OrderByInterface}; export type Fusion = 'rrf' | 'dbsf'; export type FusionQuery = {fusion: Fusion}; export type Rrf = {k?: (number | null) | undefined, weights?: (Array | null) | undefined}; export type RrfQuery = {rrf: Rrf}; export type ValueVariants = string | number | boolean; export type MatchValue = {value: ValueVariants}; export type MatchText = {text: string}; export type MatchTextAny = {text_any: string}; export type MatchPhrase = {phrase: string}; export type MatchPrefix = {prefix: string}; export type MatchSubstring = {substring: string}; export type AnyVariants = Array | Array; export type MatchAny = {any: AnyVariants}; export type MatchExcept = {except: AnyVariants}; export type Match = MatchValue | MatchText | MatchTextAny | MatchPhrase | MatchPrefix | MatchSubstring | MatchAny | MatchExcept; export type Range = {lt?: (number | null) | undefined, gt?: (number | null) | undefined, gte?: (number | null) | undefined, lte?: (number | null) | undefined}; export type DatetimeRange = {lt?: (string | null) | undefined, gt?: (string | null) | undefined, gte?: (string | null) | undefined, lte?: (string | null) | undefined}; export type RangeInterface = Range | DatetimeRange; export type GeoPoint = {lon: number, lat: number}; export type GeoBoundingBox = {top_left: GeoPoint, bottom_right: GeoPoint}; export type GeoRadius = {center: GeoPoint, radius: number}; export type GeoLineString = {points: Array}; export type GeoPolygon = {exterior: GeoLineString, interiors?: (Array | null) | undefined}; export type ValuesCount = {lt?: (number | null) | undefined, gt?: (number | null) | undefined, gte?: (number | null) | undefined, lte?: (number | null) | undefined}; export type FieldCondition = {key: string, match?: (Match | unknown) | undefined, range?: (RangeInterface | unknown) | undefined, geo_bounding_box?: (GeoBoundingBox | unknown) | undefined, geo_radius?: (GeoRadius | unknown) | undefined, geo_polygon?: (GeoPolygon | unknown) | undefined, values_count?: (ValuesCount | unknown) | undefined, is_empty?: (boolean | null) | undefined, is_null?: (boolean | null) | undefined}; export type PayloadField = {key: string}; export type IsEmptyCondition = {is_empty: PayloadField}; export type IsNullCondition = {is_null: PayloadField}; export type HasIdCondition = {has_id: Array}; export type HasVectorCondition = {has_vector: string}; export type Slice = {total: number, index: number}; export type SliceCondition = {slice: Slice}; export type MinShould = {conditions: Array, min_count: number}; export type Filter = {should?: (Condition | Array | unknown) | undefined, min_should?: (MinShould | unknown) | undefined, must?: (Condition | Array | unknown) | undefined, must_not?: (Condition | Array | unknown) | undefined}; export type Nested = {key: string, filter: Filter}; export type NestedCondition = {nested: Nested}; export type Condition = FieldCondition | IsEmptyCondition | IsNullCondition | HasIdCondition | HasVectorCondition | SliceCondition | NestedCondition | Filter; export type GeoDistanceParams = {origin: GeoPoint, to: string}; export type GeoDistance = {geo_distance: GeoDistanceParams}; export type DatetimeExpression = {datetime: string}; export type DatetimeKeyExpression = {datetime_key: string}; export type MultExpression = {mult: Array}; export type SumExpression = {sum: Array}; export type MaxExpression = {max: Array}; export type MinExpression = {min: Array}; export type NegExpression = {neg: Expression}; export type AbsExpression = {abs: Expression}; export type DivParams = {left: Expression, right: Expression, by_zero_default?: (number | null) | undefined}; export type DivExpression = {div: DivParams}; export type SqrtExpression = {sqrt: Expression}; export type PowParams = {base: Expression, exponent: Expression}; export type PowExpression = {pow: PowParams}; export type ExpExpression = {exp: Expression}; export type Log10Expression = {log10: Expression}; export type LnExpression = {ln: Expression}; export type AcoshExpression = {acosh: Expression}; export type DecayParamsExpression = {x: Expression, target?: (Expression | unknown) | undefined, scale?: (number | null) | undefined, midpoint?: (number | null) | undefined}; export type LinDecayExpression = {lin_decay: DecayParamsExpression}; export type ExpDecayExpression = {exp_decay: DecayParamsExpression}; export type GaussDecayExpression = {gauss_decay: DecayParamsExpression}; export type Expression = number | string | Condition | GeoDistance | DatetimeExpression | DatetimeKeyExpression | MultExpression | SumExpression | MaxExpression | MinExpression | NegExpression | AbsExpression | DivExpression | SqrtExpression | PowExpression | ExpExpression | Log10Expression | LnExpression | AcoshExpression | LinDecayExpression | ExpDecayExpression | GaussDecayExpression; export type FormulaQuery = {formula: Expression, defaults?: {[key: string]: unknown} | undefined}; export type Sample = 'random'; export type SampleQuery = {sample: Sample}; export type FeedbackItem = {example: VectorInput, score: number}; export type NaiveFeedbackStrategyParams = {a: number, b: number, c: number}; export type FeedbackStrategy = {naive: NaiveFeedbackStrategyParams}; export type RelevanceFeedbackInput = {target: VectorInput, feedback: Array, strategy: FeedbackStrategy}; export type RelevanceFeedbackQuery = {relevance_feedback: RelevanceFeedbackInput}; export type Bm25Params = {k?: (number | null) | undefined, b?: (number | null) | undefined}; export type TextQueryScoring = {bm25: Bm25Params}; export type TextQueryInput = {query: string, scoring?: (TextQueryScoring | unknown) | undefined}; export type TextInterface = string | TextQueryInput; export type TextQuery = {text: TextInterface}; export type Query = NearestQuery | RecommendQuery | DiscoverQuery | ContextQuery | OrderByQuery | FusionQuery | RrfQuery | FormulaQuery | SampleQuery | RelevanceFeedbackQuery | TextQuery; export type QueryInterface = VectorInput | Query; export type QuantizationSearchParams = {ignore?: boolean | undefined, rescore?: (boolean | null) | undefined, oversampling?: (number | null) | undefined}; export type AcornSearchParams = {enable?: boolean | undefined, max_selectivity?: (number | null) | undefined}; export type IdfScope = 'global'; export type IdfCorpusParams = {corpus: Filter}; export type IdfParams = IdfScope | IdfCorpusParams; export type SearchParams = {hnsw_ef?: (number | null) | undefined, exact?: boolean | undefined, quantization?: (QuantizationSearchParams | unknown) | undefined, indexed_only?: boolean | undefined, acorn?: (AcornSearchParams | unknown) | undefined, idf?: (IdfParams | unknown) | undefined}; export type LookupLocation = {collection: string, vector?: (string | null) | undefined, shard_key?: (ShardKeySelector | unknown) | undefined}; export type Prefetch = {prefetch?: (Prefetch | Array | unknown) | undefined, query?: (QueryInterface | unknown) | undefined, using?: (string | null) | undefined, filter?: (Filter | unknown) | undefined, params?: (SearchParams | unknown) | undefined, score_threshold?: (number | null) | undefined, limit?: (number | null) | undefined, lookup_from?: (LookupLocation | unknown) | undefined}; export type WithVector = boolean | Array; export type PayloadSelectorInclude = {include: Array}; export type PayloadSelectorExclude = {exclude: Array}; export type PayloadSelector = PayloadSelectorInclude | PayloadSelectorExclude; export type WithPayloadInterface = boolean | Array | PayloadSelector; export type QueryRequest = {shard_key?: (ShardKeySelector | unknown) | undefined, prefetch?: (Prefetch | Array | unknown) | undefined, query?: (QueryInterface | unknown) | undefined, using?: (string | null) | undefined, filter?: (Filter | unknown) | undefined, params?: (SearchParams | unknown) | undefined, score_threshold?: (number | null) | undefined, limit?: (number | null) | undefined, offset?: (number | null) | undefined, with_vector?: (WithVector | unknown) | undefined, with_payload?: (WithPayloadInterface | unknown) | undefined, lookup_from?: (LookupLocation | unknown) | undefined}; export type CreateApiCollectionsCollectionNamePointsQueryArgs = {collection_name: string, consistency?: ReadConsistency | undefined, timeout?: number | undefined, body: QueryRequest}; export type CreateApiCollectionsCollectionNamePointsQueryOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const hardwareUsage = z.object({cpu: z.number().int().gte(0), payload_io_read: z.number().int().gte(0), payload_io_write: z.number().int().gte(0), payload_index_io_read: z.number().int().gte(0), payload_index_io_write: z.number().int().gte(0), vector_io_read: z.number().int().gte(0), vector_io_write: z.number().int().gte(0)}); export const modelUsage = z.object({tokens: z.number().int().gte(0)}); export const inferenceUsage = z.object({models: z.record(z.string(), modelUsage)}); export const usage = z.object({hardware: z.union([hardwareUsage, z.unknown()]).optional(), inference: z.union([inferenceUsage, z.unknown()]).optional()}); export const extendedPointId = z.union([z.number().int().gte(0), z.string()]); export const payload = z.record(z.string(), z.unknown()); export const sparseVector = z.object({indices: z.array(z.number().int().gte(0)), values: z.array(z.number())}); export const vectorOutput = z.union([z.array(z.number()), sparseVector, z.array(z.array(z.number()))]); export const vectorStructOutput = z.union([z.array(z.number()), z.array(z.array(z.number())), z.record(z.string(), vectorOutput)]); export const shardKey = z.union([z.string(), z.number().int().gte(0)]); export const orderValue = z.union([z.number().int(), z.number()]); export const scoredPoint = z.object({id: extendedPointId, version: z.number().int().gte(0), score: z.number(), payload: z.union([payload, z.unknown()]).optional(), vector: z.union([vectorStructOutput, z.unknown()]).optional(), shard_key: z.union([shardKey, z.unknown()]).optional(), order_value: z.union([orderValue, z.unknown()]).optional()}); export const queryResponse = z.object({points: z.array(scoredPoint)}); export const createApiCollectionsCollectionNamePointsQueryResponse = z.object({usage: z.union([usage, z.unknown()]).optional(), time: z.number().optional(), status: z.string().optional(), result: queryResponse.optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Query points * * POST /collections/{collection_name}/points/query * * Also accepts auth: bearerAuth */ export const createApiCollectionsCollectionNamePointsQuery = async (args: CreateApiCollectionsCollectionNamePointsQueryArgs, options?: CreateApiCollectionsCollectionNamePointsQueryOptions) => { const {baseUrl = "http://localhost:6333", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.consistency != null) query.append("consistency", String(args.consistency)) if (args.timeout != null) query.append("timeout", String(args.timeout)) if (apiKey !== undefined) headers.set("api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/collections/${encodeURIComponent(String(args.collection_name))}/points/query${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiCollectionsCollectionNamePointsQueryResponse, await res.json()) };