### explainQuery Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/namespace.md Example of how to use the explainQuery method to get the query plan for a given query. ```typescript const explanation = await ns.explainQuery({ rank_by: ['embedding', 'ANN', [0.1, 0.2, 0.3]], top_k: 10, filters: ['category', 'Eq', 'electronics'] }); console.log(explanation.plan_text); ``` -------------------------------- ### Client Option Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Example of setting the log level via a client option. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', logLevel: 'debug' }); ``` -------------------------------- ### List Namespaces Examples Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/turbopuffer-client.md Examples demonstrating how to list namespaces, including auto-pagination, fetching a single page, and manual pagination. ```typescript // Fetch all namespaces with auto-pagination for await (const ns of client.namespaces({ prefix: 'prod_' })) { console.log(ns.id); } // Fetch a single page const page = await client.namespaces({ page_size: 20 }); for (const ns of page.namespaces) { console.log(ns.id); } // Manual pagination let page = await client.namespaces(); while (page.hasNextPage()) { page = await page.getNextPage(); console.log(page.namespaces); } ``` -------------------------------- ### Namespace Creation Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/turbopuffer-client.md Example of creating a namespace resource and performing a query. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; const client = new Turbopuffer({ apiKey: 'tpuf_A1...', region: 'us-east-1' }); const ns = client.namespace('products'); const result = await ns.query({ top_k: 10 }); ``` -------------------------------- ### Add and run an example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/CONTRIBUTING.md Instructions for adding a new example file and running it against the API. ```ts // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T ``` ```sh $ chmod +x examples/.ts # run the example against your api $ yarn tsn -T examples/.ts ``` -------------------------------- ### Environment Variable Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Example of setting the log level using an environment variable. ```bash export TURBOPUFFER_LOG=debug ``` -------------------------------- ### Install from git Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/CONTRIBUTING.md Installs the repository directly from a git URL. ```sh $ npm install git+ssh://git@github.com:turbopuffer/turbopuffer-typescript.git ``` -------------------------------- ### Namespace Explain Query Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Example of explaining a query on a namespace. ```typescript const plan = await ns.explainQuery({ rank_by: ['embedding', 'ANN', [0.1, 0.2]], top_k: 10 }); console.log(plan.plan_text); ``` -------------------------------- ### Get Metadata Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Example of retrieving metadata for a namespace. ```typescript const meta = await ns.metadata(); console.log(meta.approx_row_count); ``` -------------------------------- ### Get Schema Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Example of retrieving the schema for a namespace. ```typescript const schema = await ns.schema(); console.log(schema); ``` -------------------------------- ### Namespace Multi-Query Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Example of a multi-query on a namespace. ```typescript const results = await ns.multiQuery({ queries: [ { rank_by: ['embedding', 'ANN', [0.1, 0.2, 0.3]], top_k: 5 }, { rank_by: ['name', 'BM25', 'electronics'], top_k: 10 } ] }); ``` -------------------------------- ### Query Example: Product Search Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md A comprehensive query example for product search, including hybrid ranking, multiple filters, and attribute inclusion. ```typescript await ns.query({ rank_by: [ 'Sum', [ ['embedding', 'ANN', queryEmbedding], ['Product', 0.3, ['name', 'BM25', searchQuery]] ] ], filters: [ 'And', [ ['status', 'Eq', 'active'], ['stock', 'Gt', 0], ['price', 'Gte', minPrice], ['price', 'Lte', maxPrice], ['category', 'In', selectedCategories] ] ], top_k: 20, include_attributes: ['name', 'price', 'rating', 'image_url'] }); ``` -------------------------------- ### Namespace Query Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Example of a namespace query. ```typescript const result = await ns.query({ rank_by: ['embedding', 'ANN', [0.1, 0.2, 0.3]], top_k: 10, filters: ['status', 'Eq', 'active'], include_attributes: ['name', 'price'] }); ``` -------------------------------- ### Bun Configuration Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Example of configuring the Turbopuffer client for Bun. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', fetchOptions: { proxy: 'http://proxy:8080' } }); ``` -------------------------------- ### Query Example: Recommendation System Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example query for a recommendation system, using a weighted hybrid ranking and excluding previously purchased items. ```typescript await ns.query({ rank_by: [ 'Sum', [ ['embedding', 'ANN', userPreferenceVector], ['Product', 2, ['description', 'BM25', userQuery]], ['Attribute', 'user_rating_boost'] ] ], filters: [ 'And', [ ['Not', ['id', 'In', userPurchasedIds]], // Exclude bought items ['Not', ['status', 'Eq', 'out_of_stock']], ['popularity', 'Gte', 0.5] ] ], top_k: 10 }); ``` -------------------------------- ### Install dependencies and build Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/CONTRIBUTING.md Installs all required dependencies and builds output files to dist/. ```sh $ yarn $ yarn build ``` -------------------------------- ### InternalServerError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Example of handling an InternalServerError. ```typescript try { await client.namespaces(); } catch (err) { if (err instanceof Turbopuffer.InternalServerError) { console.error('Server error:', err.status); } } ``` -------------------------------- ### Deno Configuration Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Example of configuring the Turbopuffer client for Deno. ```typescript import Turbopuffer from 'npm:@turbopuffer/turbopuffer'; const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...' }); ``` -------------------------------- ### Handling Nullable Rows Field Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Demonstrates how to handle the nullable `rows` field in the query results, using a non-null assertion as an example. ```typescript const results = await tpuf.namespace('ns').query({ top_k: 10 }); const topDoc = results.rows[0]; ``` ```typescript const results = await tpuf.namespace('ns').query({ top_k: 10 }); const topDoc = results.rows![0]; // note non-null assertion ``` -------------------------------- ### Custom Requests Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Examples of making custom POST and GET requests to undocumented or custom endpoints. ```typescript const response = await client.post('/v2/namespaces/custom-endpoint', { body: { field: 'value' }, query: { param: 'value' } }); ``` ```typescript const data = await client.get('/custom-path', { query: { param: 'value' } }); ``` -------------------------------- ### exists Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/namespace.md Example of how to use the exists method to check if a namespace exists. ```typescript if (await ns.exists()) { console.log('Namespace exists'); } else { console.log('Namespace does not exist'); } ``` -------------------------------- ### Branch From Operation Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Example of branching a namespace from another. ```typescript const result = await ns.branchFrom({ source_namespace: 'products_main' }); ``` -------------------------------- ### Explain Query Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Get an explanation plan for a query without executing it. ```typescript const plan = await ns.explainQuery({ rank_by: ['embedding', 'ANN', vector], top_k: 10 }) ``` -------------------------------- ### RateLimitError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Example of handling a RateLimitError and checking the 'Retry-After' header. ```typescript try { await client.namespace('products').query(); } catch (err) { if (err instanceof Turbopuffer.RateLimitError) { const retryAfter = err.headers.get('retry-after'); console.error('Rate limited. Retry after:', retryAfter); } } ``` -------------------------------- ### Configuring proxies with Deno Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/README.md Example of configuring proxy options for Deno using Deno.createHttpClient. ```typescript import Turbopuffer from 'npm:@turbopuffer/turbopuffer'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new Turbopuffer({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### Turbopuffer Constructor - Old vs New Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Demonstrates the change in the Turbopuffer constructor, highlighting the shift from `baseUrl` to `region` and the default handling of `apiKey`. ```typescript const tpuf = new Turbopuffer({ apiKey: process.env.TURBOPUFFER_API_KEY, region: 'https://gcp-us-central1.turbopuffer.com', }); ``` ```typescript const tpuf = new Turbopuffer({ // Use `region` instead of `baseUrl` if possible. region: 'gcp-central1', // No need to pass `apiKey` if using the `TURBOPUFFER_API_KEY` environment // variable. }); ``` -------------------------------- ### Configuration Options Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Provides an example of initializing the Turbopuffer client with various configuration options, including API key, region, baseURL, timeout, retries, compression, default namespace, log level, custom fetch, fetch options, and default headers. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1...', // API key region: 'us-east-1', // Region baseURL: 'https://...', // Custom URL timeout: 30000, // Request timeout (ms) maxRetries: 4, // Retry attempts compression: true, // Enable gzip defaultNamespace: 'products', // Default namespace logLevel: 'debug', // Log verbosity fetch: customFetch, // Custom fetch fetchOptions: { /* ... */ }, // Fetch options defaultHeaders: { /* ... */ }, // Default headers }) ``` -------------------------------- ### Node.js Configuration Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Example of configuring the Turbopuffer client for Node.js, including custom fetch options with undici. ```typescript import * as undici from 'undici'; const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', fetchOptions: { dispatcher: new undici.ProxyAgent('http://proxy:8080') } }); ``` -------------------------------- ### List Namespaces Example 1 Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Fetch all namespaces with pagination. ```typescript // Fetch all namespaces with pagination for await (const ns of client.namespaces({ prefix: 'prod_' })) { console.log(ns.id); } ``` -------------------------------- ### Configuring proxies with Bun Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/README.md Example of configuring proxy options for Bun. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; const client = new Turbopuffer({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### v2.0 copy_from_namespace parameter replacement (New) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Demonstrates the new dedicated copyFrom method introduced in v2.0. ```typescript await tpuf.namespace('ns').copyFrom({ source_namespace: 'src', source_region: 'gcp-us-central1', }); ``` -------------------------------- ### Update Schema Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Example of updating the schema for a namespace. ```typescript const updated = await ns.updateSchema({ schema: { id: 'int', embedding: '[768]f32' } }); ``` -------------------------------- ### v2.0 branch_from_namespace parameter replacement (Old) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Illustrates the old way of branching from a namespace using the write method before v2.0. ```typescript await tpuf.namespace('ns').write({ branch_from_namespace: 'src' }); ``` -------------------------------- ### recall Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/namespace.md Example of how to use the recall method to evaluate the recall (accuracy) of approximate nearest neighbor searches. ```typescript const metrics = await ns.recall({ top_k: 10, num: 100, include_ground_truth: true }); console.log(metrics.avg_recall); // Average recall percentage console.log(metrics.avg_ann_count); ``` -------------------------------- ### Write Operation Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Example of performing a write operation to upsert rows and define schema. ```typescript const result = await ns.write({ upsert_rows: [ { id: 1, name: 'Product A', embedding: [0.1, 0.2] } ], schema: { name: 'string', embedding: '[2]f32' }, return_affected_ids: true }); ``` -------------------------------- ### NotFoundError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Triggered by HTTP 404 response (resource not found). ```typescript try { await client.namespace('nonexistent').schema(); } catch (err) { if (err instanceof Turbopuffer.NotFoundError) { console.error('Namespace not found'); const exists = await client.namespace('nonexistent').exists(); console.log('Exists:', exists); // false } } ``` -------------------------------- ### v2.0 branch_from_namespace parameter replacement (New) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Shows the new dedicated branchFrom method introduced in v2.0. ```typescript await tpuf.namespace('ns').branchFrom({ source_namespace: 'src' }); ``` -------------------------------- ### Browser Configuration Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Example of configuring the Turbopuffer client for use in a web browser, noting limitations on socket timeouts. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', timeout: 30000 // Request timeout (connectTimeout/idleTimeout ignored) }); ``` -------------------------------- ### v2.0 encryption parameter restructure (Old) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Illustrates the old structure of the encryption parameter before v2.0. ```typescript await tpuf.namespace('ns').write({ upsert_rows: [ /* ... */ ], encryption: { cmek: { key_name: '...' } }, }); ``` -------------------------------- ### Full-Text Search with Options Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/advanced-usage.md Example of full-text search using BM25 with options like `last_as_prefix`. ```typescript const results = await ns.query({ rank_by: [ 'description', 'BM25', 'wireless headphones', { last_as_prefix: true } ], top_k: 10, filters: ['active', 'Eq', true] }); ``` -------------------------------- ### Explain Query Plan Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/advanced-usage.md Get a textual explanation of the query execution plan to understand how Turbopuffer processes a query. ```typescript const explanation = await ns.explainQuery({ rank_by: ['embedding', 'ANN', vector], top_k: 10, filters: ['category', 'Eq', 'electronics'] }); console.log(explanation.plan_text); ``` -------------------------------- ### List Namespaces Example 2 Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md Fetch a single page of namespaces. ```typescript // Fetch single page const page = await client.namespaces({ page_size: 20 }); for (const ns of page.namespaces) { console.log(ns.id); } ``` -------------------------------- ### Ranking Example: Price-Boosted Search Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Boosting search results based on a 'discount_boost' attribute, in addition to vector similarity. ```typescript rank_by: [ 'Sum', [ ['embedding', 'ANN', vector], ['Attribute', 'discount_boost'] // Higher for discounted items ] ] ``` -------------------------------- ### Querying a namespace Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/namespace.md Example of how to query a namespace using different ranking methods and filters. ```typescript const ns = client.namespace('products'); // Vector search (ANN) const result = await ns.query({ rank_by: ['embedding', 'ANN', [0.1, 0.2, 0.3]], top_k: 10, filters: ['category', 'Eq', 'electronics'], include_attributes: ['name', 'price'] }); console.log(result.rows); // Array of matching documents console.log(result.billing.billable_logical_bytes_returned); console.log(result.performance.server_total_ms); // Full-text search (BM25) const ftsResult = await ns.query({ rank_by: ['description', 'BM25', 'wireless headphones'], top_k: 5 }); // Filter with aggregation const aggResult = await ns.query({ filters: ['in_stock', 'Eq', true], aggregate_by: { total_cost: ['Sum', 'price'], count: ['Count'] }, group_by: ['category'] }); console.log(aggResult.aggregations); ``` -------------------------------- ### Accessing Namespaces Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Get a specific namespace or list all available namespaces. ```typescript const ns = client.namespace('products'); const namespaces = await client.namespaces(); // List all ``` -------------------------------- ### Custom Headers via Environment Variable Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Example of setting custom headers using the TURBOPUFFER_CUSTOM_HEADERS environment variable, supporting multi-line format. ```bash export TURBOPUFFER_CUSTOM_HEADERS="X-Custom-Header: value1 X-Another-Header: value2" ``` -------------------------------- ### Executing multiple queries concurrently Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/namespace.md Example of how to execute multiple queries on the same namespace concurrently. ```typescript const results = await ns.multiQuery({ queries: [ { rank_by: ['embedding', 'ANN', [0.1, 0.2, 0.3]], top_k: 5, filters: ['category', 'Eq', 'electronics'] }, { rank_by: ['name', 'BM25', 'phone'], top_k: 10 } ] }); console.log(results.results[0].rows); // First query results console.log(results.results[1].rows); // Second query results ``` -------------------------------- ### v2.0 encryption parameter restructure (New) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Illustrates the new structure of the encryption parameter introduced in v2.0. ```typescript await tpuf.namespace('ns').write({ upsert_rows: [ /* ... */ ], encryption: { mode: 'customer-managed', key_name: '...' }, }); ``` -------------------------------- ### v2.0 copy_from_namespace parameter replacement (Old) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Shows the old way of copying from a namespace using the write method before v2.0. ```typescript await tpuf.namespace('ns').write({ copy_from_namespace: { source_namespace: 'src', source_region: 'gcp-us-central1', }, }); ``` -------------------------------- ### Full Configuration Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Demonstrates a comprehensive client initialization with all available configuration options. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; import pino from 'pino'; const client = new Turbopuffer({ // Auth apiKey: 'tpuf_A1xyz789...', region: 'us-east-1', // Timeouts timeout: 30000, connectTimeout: 5000, idleTimeout: 30000, // Retries and compression maxRetries: 4, compression: true, // Defaults defaultNamespace: 'products', defaultHeaders: { 'X-App-Version': '1.0.0' }, defaultQuery: { include_performance: 'true' }, // Logging logLevel: 'info', logger: pino().child({ name: 'Turbopuffer' }), // Custom fetch fetchOptions: { keepalive: true } }); ``` -------------------------------- ### Equality operators Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Examples of equality and inequality filters. ```typescript // Exact match ['status', 'Eq', 'active'] // Not equal ['status', 'NotEq', 'inactive'] ``` -------------------------------- ### Configuring proxies with Node.js Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/README.md Example of configuring proxy options for Node.js using undici's ProxyAgent. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new Turbopuffer({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` -------------------------------- ### Basic Usage Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/README.md Example of how to initialize the Turbopuffer client, create a namespace, and perform a query for nearest neighbors with filters and full-text search. ```javascript import Turbopuffer from '@turbopuffer/turbopuffer'; const tpuf = new Turbopuffer({ apiKey: process.env['TURBOPUFFER_API_KEY'], // This is the default and can be omitted }); const ns = tpuf.namespace("example"); // Query nearest neighbors with filter. const vectorResult = await ns.query({ rank_by: ["vector", "ANN", [0.1, 0.2]], top_k: 10, filters: [ "And", [ ["name", "Eq", "foo"], ["public", "Eq", 1], ], ], include_attributes: ["name"], }); console.log(vectorResult.rows); // [{ id: 1, attributes: { name: 'foo' }, dist: 0.009067952632904053 }] // Full-text search on an attribute. const ftsResult = await ns.query({ top_k: 10, filters: ["name", "Eq", "foo"], rank_by: ["text", "BM25", "quick walrus"], }); console.log(ftsResult.rows); // [{ id: 1, attributes: { name: 'foo' }, dist: 0.19 }] // [{ id: 2, attributes: { name: 'foo' }, dist: 0.168 }] // See https://turbopuffer.com/docs/quickstart for more. ``` -------------------------------- ### With Default Query Parameters Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Initialize the client with default query parameters. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', defaultQuery: { include_performance: 'true' } }); ``` -------------------------------- ### Example of handling APIUserAbortError Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Demonstrates how to catch and handle an APIUserAbortError when a request is aborted using an AbortController. ```typescript const controller = new AbortController(); setTimeout(() => controller.abort(), 1000); try { await client.namespace('products').query({ top_k: 100000 }, { signal: controller.signal }); } catch (err) { if (err instanceof Turbopuffer.APIUserAbortError) { console.error('Request was aborted'); } } ``` -------------------------------- ### Counting Documents in a Namespace Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Shows how to query for the number of documents in a namespace using a `count` aggregate query, replacing the removed `metadata` method. ```typescript const results = await tpuf.namespace('ns').query({ aggregate_by: { count: ['Count', 'id'] }, }); console.log(results.aggregations?.count); ``` -------------------------------- ### Get Schema Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Retrieve the schema of a namespace. ```typescript const schema = await ns.schema() ``` -------------------------------- ### With Default Headers Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Initialize the client with custom default headers. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', defaultHeaders: { 'X-Request-ID': 'my-app-1', 'X-Custom-Header': 'value' } }); ``` -------------------------------- ### AND logical operator Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of combining multiple conditions that must all be true. ```typescript [ 'And', [ ['status', 'Eq', 'active'], ['price', 'Gte', 50], ['stock', 'Gt', 0] ] ] ``` -------------------------------- ### AuthenticationError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Triggered by HTTP 401 response (authentication failed). ```typescript try { const client = new Turbopuffer({ apiKey: 'invalid_key' }); await client.namespaces(); } catch (err) { if (err instanceof Turbopuffer.AuthenticationError) { console.error('Authentication failed:', err.message); } } ``` -------------------------------- ### With Default Namespace Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Initialize the client with a default namespace. Queries will use this namespace if not explicitly specified. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', defaultNamespace: 'products' }); // These are equivalent: const ns1 = client.namespace('products'); const ns2 = client.namespace('products'); // When not specified, uses defaultNamespace: await ns1.query({ top_k: 10 }); ``` -------------------------------- ### APIConnectionTimeoutError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Example of handling an APIConnectionTimeoutError with a custom timeout. ```typescript try { const client = new Turbopuffer({ timeout: 5000 // 5 second timeout }); await client.namespace('large').query({ top_k: 1000000 }); } catch (err) { if (err instanceof Turbopuffer.APIConnectionTimeoutError) { console.error('Request timed out after 5 seconds'); } } ``` -------------------------------- ### Cloudflare Workers Configuration Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Example of configuring and using the Turbopuffer client within a Cloudflare Worker. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; export default { async fetch(request: Request) { const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...' }); const ns = client.namespace('products'); return new Response(JSON.stringify(await ns.query())); } }; ``` -------------------------------- ### Vector-Based Ranking: Exact k-NN Search Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of exact k-NN search ranking. ```typescript ['embedding', 'kNN', [0.1, 0.2, 0.3, 0.4]] ``` -------------------------------- ### APIConnectionError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Example of handling an APIConnectionError with an unreachable endpoint. ```typescript try { const client = new Turbopuffer({ baseURL: 'https://unreachable.example.com' }); await client.namespaces(); } catch (err) { if (err instanceof Turbopuffer.APIConnectionError) { console.error('Connection error:', err.message); if (err.cause) { console.error('Underlying cause:', err.cause); } } } ``` -------------------------------- ### Enabling gzip compression Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/README.md Example of enabling gzip compression for the Turbopuffer client. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; const client = new Turbopuffer({ compression: true, }); ``` -------------------------------- ### Vector Search + Filters Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md An example demonstrating a query that combines vector search (ANN) with attribute-based filtering using 'And' and comparison operators like 'Eq' and 'Gte'. ```typescript await ns.query({ rank_by: ['embedding', 'ANN', queryVector], filters: ['And', [ ['status', 'Eq', 'active'], ['price', 'Gte', 50] ]], top_k: 10 }) ``` -------------------------------- ### Full-Text Search (BM25) with parameters Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of BM25 full-text search ranking with additional parameters. ```typescript ['description', 'BM25', 'wireless headphones', { last_as_prefix: true }] ``` -------------------------------- ### Ranking Example: Vector Search with Fallback Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Using a 'Max' strategy to prioritize a primary vector search and fall back to a secondary if needed. ```typescript rank_by: [ 'Max', [ ['primary_embedding', 'ANN', vector], ['secondary_embedding', 'ANN', vector] // Use if primary fails ] ] ``` -------------------------------- ### ConflictError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Example of handling a ConflictError during high concurrency writes. ```typescript try { // High concurrency scenario await Promise.all([ ns.write({ upsert_rows: [...] }), ns.write({ upsert_rows: [...] }) ]); } catch (err) { if (err instanceof Turbopuffer.ConflictError) { console.error('Lock timeout, will be retried'); } } ``` -------------------------------- ### Batch Write with Return IDs Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md An example of performing a batch write operation (upsert) and requesting the affected IDs to be returned in the response. ```typescript await ns.write({ upsert_rows: largeArray, return_affected_ids: true }) ``` -------------------------------- ### Direct Invocation Installation Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/packages/mcp-server/README.md Command to run the MCP Server directly using npx, including setting necessary environment variables. ```sh export TURBOPUFFER_API_KEY="tpuf_A1..." export TURBOPUFFER_REGION="gcp-us-central1" export TURBOPUFFER_DEFAULT_NAMESPACE="My Default Namespace" npx -y @turbopuffer/turbopuffer-mcp@latest ``` -------------------------------- ### UnprocessableEntityError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Example of handling an UnprocessableEntityError due to invalid vector dimensions. ```typescript try { await ns.write({ upsert_rows: [ { id: 1, embedding: [0.1, 0.2] } // Wrong dimension ] }); } catch (err) { if (err instanceof Turbopuffer.UnprocessableEntityError) { console.error('Semantic error:', err.error); } } ``` -------------------------------- ### MCP Client Configuration JSON Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/packages/mcp-server/README.md Example configuration JSON for integrating the MCP server with a client, including environment variables. ```json { "mcpServers": { "turbopuffer_turbopuffer_api": { "command": "npx", "args": ["-y", "@turbopuffer/turbopuffer-mcp"], "env": { "TURBOPUFFER_API_KEY": "tpuf_A1...", "TURBOPUFFER_REGION": "gcp-us-central1", "TURBOPUFFER_DEFAULT_NAMESPACE": "My Default Namespace" } } } } ``` -------------------------------- ### Ranking Example: Hybrid Vector + Text Search Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Combining vector similarity search with BM25 text relevance scoring. ```typescript rank_by: [ 'Sum', [ ['embedding', 'ANN', vector], // Vector similarity ['description', 'BM25', 'headphones'] // Text relevance ] ] ``` -------------------------------- ### Update Metadata (Pinning) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Update namespace metadata, for example, to configure pinning with a specific number of replicas. ```typescript await ns.updateMetadata({ pinning: { replicas: 3 } }) ``` -------------------------------- ### Minimal Configuration Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Initializes the Turbopuffer client with minimal configuration, relying on environment variables for API key. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; const client = new Turbopuffer(); // Uses TURBOPUFFER_API_KEY env var or throws error ``` -------------------------------- ### UpdateSchema Method - Old vs New Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/UPGRADING.md Illustrates the change in the `updateSchema` method, where the schema is now passed as a nested object property instead of directly. ```typescript await tpuf.namespace('ns').updateSchema({ attr1: 'val1', attr2: 'val2', // ... }); ``` ```typescript await tpuf.namespace('ns').updateSchema({ schema: { attr1: 'val1', attr2: 'val2', // ... }, }); ``` -------------------------------- ### Retry Customization Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Shows how to disable automatic retries by setting maxRetries to 0 or override it for a specific request. ```typescript // Disable retries const client = new Turbopuffer({ maxRetries: 0 }); // Override per-request await client.namespace('products').query( { top_k: 10 }, { maxRetries: 10 } ); ``` -------------------------------- ### Ranking Example: Multi-Attribute Sorting Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Defining a multi-level sorting strategy based on multiple attributes in specified orders. ```typescript rank_by: [ ['price', 'asc'], // First sort by price ['rating', 'desc'], // Then by rating ['created_at', 'desc'] // Then by creation date ] ``` -------------------------------- ### Specific Error Handling Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Demonstrates handling various specific API errors like NotFoundError, BadRequestError, RateLimitError, and APIConnectionError. ```typescript try { await ns.write({ upsert_rows: [...] }); } catch (err) { if (err instanceof Turbopuffer.NotFoundError) { console.error('Namespace does not exist'); } else if (err instanceof Turbopuffer.BadRequestError) { console.error('Invalid write request:', err.error); } else if (err instanceof Turbopuffer.RateLimitError) { const retryAfter = err.headers.get('retry-after'); console.error('Rate limited, retry after:', retryAfter); } else if (err instanceof Turbopuffer.APIConnectionError) { console.error('Network error, will be retried'); } else { throw err; } } ``` -------------------------------- ### withOptions() Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/turbopuffer-client.md Create a new client instance with the same configuration, optionally overriding specific options. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1...', timeout: 30000 }); const highTimeoutClient = client.withOptions({ timeout: 120000 }); ``` -------------------------------- ### Query Example: Recent Content with Relevance Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Query for recent content, combining vector search with a time-decay ranking and limiting results per author. ```typescript await ns.query({ rank_by: [ 'Sum', [ ['embedding', 'ANN', contentVector], [ 'Decay', ['Attribute', 'engagement_score'], { midpoint: 7, exponent: 1.5 } // Recent content scores higher ] ] ], filters: [ 'And', [ ['published', 'Eq', true], ['category', 'In', ['tech', 'science']], ['created_at', 'Gte', sevenDaysAgo] ] ], limit: { total: 20, per: { attributes: ['author_id'], limit: 3 // Max 3 articles per author } } }); ``` -------------------------------- ### Get Metadata Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Retrieve metadata for a namespace, including approximate row count and creation time. ```typescript const meta = await ns.metadata() // meta.approx_row_count, meta.created_at, meta.index.status ``` -------------------------------- ### Full-Text Search (BM25) with array of terms Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of BM25 full-text search ranking with an array of query terms. ```typescript ['description', 'BM25', ['wireless', 'headphones']] ``` -------------------------------- ### Ranking Example: Weighted Hybrid Search Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Applying specific weights to vector and text search components in a hybrid approach. ```typescript rank_by: [ 'Sum', [ ['Product', 0.7, ['embedding', 'ANN', vector]], // 70% weight on vector ['Product', 0.3, ['description', 'BM25', 'wireless']] // 30% weight on text ] ] ``` -------------------------------- ### Ranking Example: Time-Aware Ranking Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Combining vector search with a decay function based on a relevance attribute, emphasizing recent content. ```typescript rank_by: [ 'Sum', [ ['embedding', 'ANN', vector], [ 'Decay', ['Attribute', 'relevance'], { midpoint: new Date().toISOString(), exponent: 2.0 } ] ] ] ``` -------------------------------- ### Request & Response Types Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/README.md Example demonstrating how to import and use TypeScript definitions for request parameters and response fields. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; const client = new Turbopuffer({ apiKey: process.env['TURBOPUFFER_API_KEY'], // This is the default and can be omitted }); const params: Turbopuffer.NamespacesParams = { prefix: 'foo' }; const [namespaceSummary]: [Turbopuffer.NamespaceSummary] = await client.namespaces(params); ``` -------------------------------- ### Remote Server Configuration JSON (Environment Variables) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/packages/mcp-server/README.md Example configuration JSON for a hosted MCP server, including setting environment variables via the x-stainless-mcp-client-envs header. ```json { "mcpServers": { "turbopuffer_turbopuffer_api": { "url": "https://turbopuffer.stlmcp.com", "headers": { "x-turbopuffer-api-key": "tpuf_A1...", "x-stainless-mcp-client-envs": "{\"TURBOPUFFER_REGION\": \"gcp-us-central1\"}" } } } } ``` -------------------------------- ### Initialization Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Initialize the Turbopuffer client with your API key and region. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; const client = new Turbopuffer({ apiKey: 'tpuf_A1...', region: 'us-east-1' }); ``` -------------------------------- ### Auto-pagination with `for await...of` Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/README.md Provides an example of using the `for await...of` loop to iterate through all items across paginated API results, automatically fetching subsequent pages. ```typescript async function fetchAllNamespaceSummaries(params) { const allNamespaceSummaries = []; // Automatically fetches more pages as needed. for await (const namespaceSummary of client.namespaces({ prefix: 'products' })) { allNamespaceSummaries.push(namespaceSummary); } return allNamespaceSummaries; } ``` -------------------------------- ### Get Metadata Endpoint Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md TypeScript client method for the GET /v2/namespaces/{namespace}/metadata endpoint. ```typescript namespace.metadata(params?, options?) ``` -------------------------------- ### Get Schema Endpoint Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md TypeScript client method for the GET /v1/namespaces/{namespace}/schema endpoint. ```typescript namespace.schema(params?, options?) ``` -------------------------------- ### Manual Pagination Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates manual pagination by fetching the first page of results and then explicitly requesting the next page if it exists. ```typescript let page = await client.namespaces({ page_size: 20 }) if (page.hasNextPage()) { page = await page.getNextPage() } ``` -------------------------------- ### Range operators Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Examples of range-based filters. ```typescript // Less than ['price', 'Lt', 100] // Less than or equal ['price', 'Lte', 100] // Greater than ['price', 'Gt', 50] // Greater than or equal ['price', 'Gte', 50] ``` -------------------------------- ### NOT logical operator Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of negating a filter condition. ```typescript ['Not', ['status', 'Eq', 'inactive']] ``` -------------------------------- ### With Explicit API Key Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Initializes the Turbopuffer client with an explicitly provided API key. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...' }); ``` -------------------------------- ### Complex filter: Multi-level logic Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of nested AND and OR conditions. ```typescript // Active products from electronics or computers category with price between 100-1000 [ 'And', [ ['status', 'Eq', 'active'], [ 'Or', [ ['category', 'Eq', 'electronics'], ['category', 'Eq', 'computers'] ] ], ['price', 'Gte', 100], ['price', 'Lte', 1000] ] ] ``` -------------------------------- ### Constructor Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/turbopuffer-client.md Instantiate the Turbopuffer client with optional configuration options. ```typescript constructor(options?: ClientOptions): Turbopuffer ``` -------------------------------- ### PermissionDeniedError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Triggered by HTTP 403 response (insufficient permissions). ```typescript try { await client.namespace('restricted').query(); } catch (err) { if (err instanceof Turbopuffer.PermissionDeniedError) { console.error('Permission denied:', err.message); } } ``` -------------------------------- ### OR logical operator Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of combining multiple conditions where any one can be true. ```typescript [ 'Or', [ ['status', 'Eq', 'featured'], ['rating', 'Gte', 4.5], ['stock', 'Eq', 0] // Out of stock items ] ] ``` -------------------------------- ### With Proxy (Bun) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Configures the Turbopuffer client to use a proxy for Bun environments. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', fetchOptions: { proxy: 'http://localhost:8888' } }); ``` -------------------------------- ### BadRequestError Example Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/errors.md Triggered by HTTP 400 response (invalid request parameters). ```typescript try { await client.namespace('products').query({ rank_by: ['invalid_syntax'] // Invalid rank_by format }); } catch (err) { if (err instanceof Turbopuffer.BadRequestError) { console.error('Bad request:', err.status, err.error); } } ``` -------------------------------- ### Complex filter: Optional Features Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of using OR to check for optional features. ```typescript // Products with either feature A or feature B (optional) [ 'Or', [ ['features', 'Contains', 'wireless'], ['features', 'Contains', 'waterproof'] ] ] ``` -------------------------------- ### With Region Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Initializes the Turbopuffer client with an API key and specifies the region, which affects the baseURL. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', region: 'us-east-1' }); // baseURL becomes: https://us-east-1.turbopuffer.com ``` -------------------------------- ### Vector-Based Ranking: Sparse Vector Search Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of sparse vector search ranking. ```typescript ['sparse_embedding', 'SparseKNN', { '0': 0.5, '42': 0.3, '156': 0.2 }] ``` -------------------------------- ### Complex filter: Exclude with NOT Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of excluding multiple statuses using nested NOT operators. ```typescript // All products except inactive or discontinued [ 'And', [ ['Not', ['status', 'Eq', 'inactive']], ['Not', ['status', 'Eq', 'discontinued']] ] ] ``` -------------------------------- ### Namespace Explain Query SDK Method Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/endpoints.md SDK method to explain a query on a namespace. ```typescript namespace.explainQuery(params?, options?) ``` -------------------------------- ### Basic Query Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Perform a basic query to retrieve documents. ```typescript await ns.query({ top_k: 10 }) ``` -------------------------------- ### With Custom Fetch Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Integrates a custom fetch implementation with the Turbopuffer client, shown using 'node-fetch'. ```typescript import fetch from 'node-fetch'; const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', fetch: fetch // Use custom fetch implementation }); ``` -------------------------------- ### Mock Namespace for Testing Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/advanced-usage.md A mock implementation of a namespace for use in unit tests, providing a simplified query response. ```typescript // Use in-memory data for unit tests class MockNamespace { async query() { return { rows: [{ id: 1, name: 'Test' }], billing: { billable_logical_bytes_queried: 0, billable_logical_bytes_returned: 0 }, performance: { /* ... */ } }; } } ``` -------------------------------- ### Auto-Pagination Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Shows how to use async iterators to automatically paginate through results, such as all namespaces available from the client. ```typescript for await (const ns of client.namespaces()) { console.log(ns.id) } ``` -------------------------------- ### Full-Text Search (BM25) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of BM25 full-text search ranking with a single query string. ```typescript ['description', 'BM25', 'search query'] ``` -------------------------------- ### Environment Variables Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Lists common environment variables used to configure the Turbopuffer client, such as API key, region, and base URL. ```bash export TURBOPUFFER_API_KEY="tpuf_A1..." export TURBOPUFFER_REGION="us-east-1" export TURBOPUFFER_BASE_URL="https://custom.url" export TURBOPUFFER_LOG="debug" ``` -------------------------------- ### With Logging Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Configures the Turbopuffer client with a specific log level for debugging. ```typescript const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', logLevel: 'debug' // Show all log messages including HTTP details }); ``` -------------------------------- ### Basic Usage Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/README.md Initializes the Turbopuffer client, accesses a namespace, and performs a query. ```typescript import Turbopuffer from '@turbopuffer/turbopuffer'; // Initialize client const client = new Turbopuffer({ apiKey: 'tpuf_A1...', region: 'us-east-1' }); // Access a namespace const ns = client.namespace('products'); // Query documents const results = await ns.query({ rank_by: ['embedding', 'ANN', [0.1, 0.2, 0.3]], top_k: 10, filters: ['status', 'Eq', 'active'] }); console.log(results.rows); ``` -------------------------------- ### Access Raw Response with Data Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/advanced-usage.md Use `.withResponse()` to get both parsed data and the raw `Response`. ```typescript const { data: namespaces, response: raw } = await client .namespaces({ prefix: 'prod_' }) .withResponse(); console.log(raw.headers.get('X-My-Header')); // Can still iterate the pageable result for await (const ns of namespaces) { console.log(ns.id); } ``` -------------------------------- ### With Custom Logger Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/configuration.md Integrates a custom logger implementation, such as Pino, with the Turbopuffer client. ```typescript import pino from 'pino'; const logger = pino(); const client = new Turbopuffer({ apiKey: 'tpuf_A1xyz789...', logger: logger.child({ name: 'Turbopuffer' }), logLevel: 'info' }); ``` -------------------------------- ### Multiple Queries Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Execute multiple queries simultaneously. ```typescript await ns.multiQuery({ queries: [ { rank_by: ['embedding', 'ANN', vector], top_k: 5 }, { rank_by: ['name', 'BM25', 'query'], top_k: 10 } ] }) ``` -------------------------------- ### Vector-Based Ranking: Approximate Nearest Neighbor (ANN) Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/filters-and-ranking.md Example of ANN ranking for approximate vector search. ```typescript ['embedding', 'ANN', [0.1, 0.2, 0.3, 0.4]] ``` -------------------------------- ### Access Raw Response Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/advanced-usage.md Use `.asResponse()` to get the underlying `Response` object without consuming the body. ```typescript const response = await client.namespaces({ prefix: 'prod_' }).asResponse(); console.log(response.headers.get('X-My-Header')); console.log(response.status); // Body is not consumed, handle as needed ``` -------------------------------- ### With Filters Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Include filters in your query to narrow down results. ```typescript await ns.query({ rank_by: ['embedding', 'ANN', vector], filters: ['status', 'Eq', 'active'], top_k: 10 }) ``` -------------------------------- ### Catch All Errors Source: https://github.com/turbopuffer/turbopuffer-typescript/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to catch and handle any errors that occur during a Turbopuffer query, specifically checking for Turbopuffer.APIError. ```typescript try { await ns.query({ top_k: 10 }) } catch (err) { if (err instanceof Turbopuffer.APIError) { console.error(`${err.status}: ${err.message}`) } } ```