Skip to content

Build hybrid search for your docs

Search Knotkit’s module docs by API name or by describing what you need.

Try

Looking for knotkit/graph

Keyword

BM25

  1. graph

Semantic

Embedding similarity

  1. graph
  2. trie
  3. prng
  4. scalar-sketch
  5. sampling

Hybrid

Rank fusion

  1. graph
  2. trie
  3. prng
  4. scalar-sketch
  5. sampling

Showing up to 5 results from 32 module summaries.

Type a task you’re working on or a function name, then press Search. Compare the results under Keyword, Semantic, and Hybrid. Keyword results appear while a worker loads the embedding model for the first custom query. The worker encodes your text in your browser and reuses the model for later searches.

Use API name to find compressedSparseRowGraph. Try Customer quotas to find the rate-limit module by meaning. Sample a stream shows a query where both methods put the same module first.

Knotkit builds the keyword index once. NumPyTS multiplies the document matrix by the query vector to score every document. With unit-length embeddings, the dot product is cosine similarity. Reciprocal rank fusion combines the first ten hits from each method. A document gets more credit for appearing higher in either list.

Use Knotkit from source and install numpy-ts@1.8.0. Pass documents and query vectors produced by the same embedding model.

The demo bundles BGE-small embeddings for the module summaries and example queries. The first custom search downloads the 34 MB model and the WebAssembly runtime. The fixture generator at apps/docs/scripts/embed-hybrid-search.py records the model revision and reads the module summaries and API names from the capability catalog.

hybrid-docs-search.ts
import {
function termIndex<R>(records: Iterable<R>, termsOf: (record: R, id: number) => readonly string[]): TermIndex

Build a read-only counted index from caller-tokenized documents. The selector runs once per input record. The index retains terms, counts, and document positions. It can discard the source records after construction.

Expected O(n + t) build time for n documents and t token occurrences, plus the selector's work. Build workspace and retained storage are O(n + v + p) for v vocabulary terms and p distinct postings.

@throws ― {TermIndexInvalidInputError} With INVALID_TERMS for a selector result other than an array of strings or MAX_CAPACITY_EXCEEDED when corpus counts or packed storage exceed their bounds. Errors thrown by the input iterable and selector propagate.

termIndex
} from 'knotkit/term-index'
import {
function array(data: unknown, dtype?: DType): NDArrayCore

Create array from nested JavaScript arrays

array
,
function matmul(a: NDArrayCore, b: NDArrayCore): NDArrayCore

Matrix multiplication

matmul
} from 'numpy-ts/core'
interface
interface SearchDocument
SearchDocument
{
readonly
SearchDocument.text: string
text
: string
readonly
SearchDocument.embedding: ArrayLike<number>
embedding
:
interface ArrayLike<T>
ArrayLike
<number>
}
const
const shortlistSize: 10
shortlistSize
= 10
const
const rankOffset: 60
rankOffset
= 60
const
const stopWords: Set<string>
stopWords
= new
var Set: SetConstructor
new <string>(iterable?: Iterable<string> | null | undefined) => Set<string> (+1 overload)
Set
(
'a an and are as at be by can do each for from give how i in into is it of on or please that the to with you'.
String.split(separator: string | RegExp, limit?: number): string[] (+1 overload)

Split a string into substrings using the specified separator and return them as an array.

@param ― separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.

@param ― limit A value used to limit the number of elements returned in the array.

split
(
' ',
),
)
const
const terms: (text: string) => string[]
terms
= (
text: string
text
: string): string[] =>
(
text: string
text
.
String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
().
String.match(matcher: {
[Symbol.match](string: string): RegExpMatchArray | null;
}): RegExpMatchArray | null (+1 overload)

Matches a string or an object that supports being matched against, and returns an array containing the results of that search, or null if no matches are found.

@param ― matcher An object that supports being matched against.

match
(/[\p{L}\p{N}]+/gu) ?? []).
Array<T>.filter(predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): string[]

Returns the elements of an array that meet the condition specified in a callback function.

@param ― predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

filter
((
term: string
term
) => !
const stopWords: Set<string>
stopWords
.
Set<string>.has(value: string): boolean

@returns ― a boolean indicating whether an element with the specified value exists in the Set or not.

has
(
term: string
term
))
export function
function hybridDocSearch(documents: readonly SearchDocument[]): (query: string, embedding?: ArrayLike<number>) => {
keyword: number[];
semantic: number[];
hybrid: number[];
}
hybridDocSearch
(
documents: readonly SearchDocument[]
documents
: readonly
interface SearchDocument
SearchDocument
[]) {
const
const index: TermIndex
index
=
termIndex<SearchDocument>(records: Iterable<SearchDocument>, termsOf: (record: SearchDocument, id: number) => readonly string[]): TermIndex

Build a read-only counted index from caller-tokenized documents. The selector runs once per input record. The index retains terms, counts, and document positions. It can discard the source records after construction.

Expected O(n + t) build time for n documents and t token occurrences, plus the selector's work. Build workspace and retained storage are O(n + v + p) for v vocabulary terms and p distinct postings.

@throws ― {TermIndexInvalidInputError} With INVALID_TERMS for a selector result other than an array of strings or MAX_CAPACITY_EXCEEDED when corpus counts or packed storage exceed their bounds. Errors thrown by the input iterable and selector propagate.

termIndex
(
documents: readonly SearchDocument[]
documents
, ({
text: string
text
}) =>
const terms: (text: string) => string[]
terms
(
text: string
text
))
const
const matrix: NDArrayCore<"float64" | "float32" | "float16" | "complex128" | "complex64" | "int64" | "int32" | "int16" | "int8" | "uint64" | "uint32" | "uint16" | "uint8" | "bool">
matrix
=
function array(data: unknown, dtype?: DType): NDArrayCore

Create array from nested JavaScript arrays

array
(
documents: readonly SearchDocument[]
documents
.
ReadonlyArray<SearchDocument>.map<number[]>(callbackfn: (value: SearchDocument, index: number, array: readonly SearchDocument[]) => number[], thisArg?: any): number[][]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(({
embedding: ArrayLike<number>
embedding
}) =>
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<number>(iterable: ArrayLike<number> | Iterable<number>): number[] (+3 overloads)

Creates an array from an iterable object.

@param ― iterable An iterable object to convert to an array.

from
(
embedding: ArrayLike<number>
embedding
)),
'float64',
)
return (
query: string
query
: string,
embedding: ArrayLike<number> | undefined
embedding
?:
interface ArrayLike<T>
ArrayLike
<number>) => {
const
const keyword: number[]
keyword
=
const index: TermIndex
index
.
TermIndex.search: (terms: readonly string[], options?: TermSearchOptions) => readonly TermHit[]

Rank documents matching any supplied exact term. Ties in score favor lower IDs. Repeated query terms contribute once. The returned array and hits are independent of the index.

@throws ― {TermIndexInvalidInputError} With INVALID_LIMIT for a limit outside the nonnegative safe integers or INVALID_TERMS for an argument other than an array of strings. Eligibility accessor errors propagate.

search
(
const terms: (text: string) => string[]
terms
(
query: string
query
), {
TermSearchOptions.limit?: number | undefined

Maximum number of hits. Defaults to 10. Zero yields no hits.

limit
:
const shortlistSize: 10
shortlistSize
}).
ReadonlyArray<TermHit>.map<number>(callbackfn: (value: TermHit, index: number, array: readonly TermHit[]) => number, thisArg?: any): number[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(({
id: number
id
}) =>
id: number
id
)
if (
embedding: ArrayLike<number> | undefined
embedding
===
var undefined
undefined
) {
return {
keyword: number[]
keyword
,
semantic: never[]
semantic
: [],
hybrid: never[]
hybrid
: [] }
}
const
const queryVector: NDArrayCore<"float64" | "float32" | "float16" | "complex128" | "complex64" | "int64" | "int32" | "int16" | "int8" | "uint64" | "uint32" | "uint16" | "uint8" | "bool">
queryVector
=
function array(data: unknown, dtype?: DType): NDArrayCore

Create array from nested JavaScript arrays

array
(
var Float64Array: Float64ArrayConstructor

A typed array of 64-bit float values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Float64Array
.
Float64ArrayConstructor.from(arrayLike: ArrayLike<number>): Float64Array<ArrayBuffer> (+3 overloads)

Creates an array from an array-like or iterable object.

@param ― arrayLike An array-like object to convert to an array.

from
(
embedding: ArrayLike<number>
embedding
), 'float64')
const
const similarities: Float64Array<ArrayBuffer>
similarities
= new
var Float64Array: Float64ArrayConstructor
new <ArrayBuffer>(buffer: ArrayBuffer, byteOffset?: number, length?: number) => Float64Array<ArrayBuffer> (+6 overloads)
Float64Array
(
function matmul(a: NDArrayCore, b: NDArrayCore): NDArrayCore

Matrix multiplication

matmul
(
const matrix: NDArrayCore<"float64" | "float32" | "float16" | "complex128" | "complex64" | "int64" | "int32" | "int16" | "int8" | "uint64" | "uint32" | "uint16" | "uint8" | "bool">
matrix
,
const queryVector: NDArrayCore<"float64" | "float32" | "float16" | "complex128" | "complex64" | "int64" | "int32" | "int16" | "int8" | "uint64" | "uint32" | "uint16" | "uint8" | "bool">
queryVector
).
NDArrayCore<"float64" | "float32" | "float16" | "complex128" | "complex64" | "int64" | "int32" | "int16" | "int8" | "uint64" | "uint32" | "uint16" | "uint8" | "bool">.tobytes(): ArrayBuffer

Return the raw bytes of the array data

tobytes
())
const
const semantic: number[]
semantic
=
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<number>(iterable: ArrayLike<number> | Iterable<number>): number[] (+3 overloads)

Creates an array from an iterable object.

@param ― iterable An iterable object to convert to an array.

from
(
const similarities: Float64Array<ArrayBuffer>
similarities
.
Float64Array<ArrayBuffer>.keys(): ArrayIterator<number>

Returns an list of keys in the array

keys
())
.
Array<number>.toSorted(compareFn?: ((a: number, b: number) => number) | undefined): number[]

Returns a copy of an array with its elements sorted.

@param ―

compareFn Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.

[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]

toSorted
((
a: number
a
,
b: number
b
) =>
const similarities: Float64Array<ArrayBuffer>
similarities
[
b: number
b
] -
const similarities: Float64Array<ArrayBuffer>
similarities
[
a: number
a
] ||
a: number
a
-
b: number
b
)
.
Array<number>.slice(start?: number, end?: number): number[]

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

@param ― start The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.

@param ― end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

slice
(0,
const shortlistSize: 10
shortlistSize
)
const
const scores: Map<number, number>
scores
= new
var Map: MapConstructor
new <number, number>(iterable?: Iterable<readonly [number, number]> | null | undefined) => Map<number, number> (+3 overloads)
Map
<number, number>()
for (const
const ranking: number[]
ranking
of [
const keyword: number[]
keyword
,
const semantic: number[]
semantic
]) {
for (const [
const rank: number
rank
,
const id: number
id
] of
const ranking: number[]
ranking
.
Array<number>.entries(): ArrayIterator<[number, number]>

Returns an iterable of key, value pairs for every entry in the array

entries
()) {
const scores: Map<number, number>
scores
.
Map<number, number>.set(key: number, value: number): Map<number, number>

Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.

set
(
const id: number
id
, (
const scores: Map<number, number>
scores
.
Map<number, number>.get(key: number): number | undefined

Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.

@returns ― Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.

get
(
const id: number
id
) ?? 0) + 1 / (
const rankOffset: 60
rankOffset
+
const rank: number
rank
+ 1))
}
}
const
const hybrid: number[]
hybrid
=
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<[number, number]>(iterable: Iterable<[number, number]> | ArrayLike<[number, number]>): [number, number][] (+3 overloads)

Creates an array from an iterable object.

@param ― iterable An iterable object to convert to an array.

from
(
const scores: Map<number, number>
scores
.
Map<number, number>.entries(): MapIterator<[number, number]>

Returns an iterable of key, value pairs for every entry in the map.

entries
())
.
Array<[number, number]>.toSorted(compareFn?: ((a: [number, number], b: [number, number]) => number) | undefined): [number, number][]

Returns a copy of an array with its elements sorted.

@param ―

compareFn Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.

[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]

toSorted
(([
a: number
a
,
left: number
left
], [
b: number
b
,
right: number
right
]) =>
right: number
right
-
left: number
left
||
a: number
a
-
b: number
b
)
.
Array<[number, number]>.map<number>(callbackfn: (value: [number, number], index: number, array: [number, number][]) => number, thisArg?: any): number[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(([
id: number
id
]) =>
id: number
id
)
return {
keyword: number[]
keyword
,
semantic: number[]
semantic
,
hybrid: number[]
hybrid
}
}
}

Modules: knotkit/term-index · API reference