* Creates an index on a collection for faster queries. * * @example * ```ts * // With explicit index type (recommended for tree-shaking) * import { BasicIndex } from '@tanstack/db' * collection.createIndex((row) => row.userId, { indexType: BasicIndex }) * * // With collection
(
indexCallback: (row: SingleRowRefProxy<TOutput>) => any,
config: IndexOptions<TIndexType> = {},
)
| 249 | * ``` |
| 250 | */ |
| 251 | public createIndex<TIndexType extends IndexConstructor<TKey>>( |
| 252 | indexCallback: (row: SingleRowRefProxy<TOutput>) => any, |
| 253 | config: IndexOptions<TIndexType> = {}, |
| 254 | ): BaseIndex<TKey> { |
| 255 | this.lifecycle.validateCollectionUsable(`createIndex`) |
| 256 | |
| 257 | const indexId = ++this.indexCounter |
| 258 | const singleRowRefProxy = createSingleRowRefProxy<TOutput>() |
| 259 | const indexExpression = indexCallback(singleRowRefProxy) |
| 260 | const expression = toExpression(indexExpression) |
| 261 | |
| 262 | // Use provided index type, or fall back to collection's default |
| 263 | const IndexType = config.indexType ?? this.defaultIndexType |
| 264 | if (!IndexType) { |
| 265 | throw new CollectionConfigurationError( |
| 266 | `No index type specified and no defaultIndexType set on collection. ` + |
| 267 | `Either pass indexType in config, or set defaultIndexType on the collection:\n` + |
| 268 | ` import { BasicIndex } from '@tanstack/db'\n` + |
| 269 | ` createCollection({ defaultIndexType: BasicIndex, ... })`, |
| 270 | ) |
| 271 | } |
| 272 | |
| 273 | // Create index synchronously |
| 274 | const index = new IndexType( |
| 275 | indexId, |
| 276 | expression, |
| 277 | config.name, |
| 278 | config.options, |
| 279 | ) |
| 280 | |
| 281 | // Build with current data |
| 282 | index.build(this.state.entries()) |
| 283 | |
| 284 | this.indexes.set(indexId, index) |
| 285 | |
| 286 | // Track metadata and emit event |
| 287 | const metadata = createCollectionIndexMetadata( |
| 288 | indexId, |
| 289 | expression, |
| 290 | config.name, |
| 291 | IndexType, |
| 292 | config.options, |
| 293 | ) |
| 294 | this.indexMetadata.set(indexId, metadata) |
| 295 | this.events.emitIndexAdded(metadata) |
| 296 | |
| 297 | return index |
| 298 | } |
| 299 | |
| 300 | /** |
| 301 | * Removes an index from this collection. |
nothing calls this directly
no test coverage detected