### Run Example Server and Script Source: https://github.com/typesense/typesense-js/blob/master/README.md Commands to run the Typesense server and an example JavaScript script from the repository root. ```bash pnpm typesenseServer node doc/examples/server/bulkImport.js ``` -------------------------------- ### Install typesense via npm Source: https://github.com/typesense/typesense-js/blob/master/README.md Install the typesense JavaScript client library using npm. ```sh npm install --save typesense ``` -------------------------------- ### Install and Run np for Releasing Source: https://github.com/typesense/typesense-js/blob/master/README.md Install the np package globally and then run it to manage the release process. Follow the interactive prompts provided by np to complete the release. ```shell npm install --global np np ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/typesense/typesense-js/blob/master/README.md Install the required peer dependency for the typesense-js library. ```sh npm install --save @babel/runtime ``` -------------------------------- ### Create Alias for Blue-Green Deployment Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Aliases.md This example demonstrates how to set up a blue-green deployment strategy by creating a new collection, pointing an alias to it, and then using the alias for application queries. ```typescript // Create new collection await client.collections().create({ name: 'books_v2', fields: [ { name: 'id', type: 'string' }, { name: 'title', type: 'string' } ] }); // Point alias to new collection await client.aliases().upsert('books-latest', { collection_name: 'books_v2' }); // Application code can use the alias const results = await client .collections('books-latest') .documents() .search({ q: 'harry' }); ``` -------------------------------- ### Handle MissingConfigurationError Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md Example of catching a MissingConfigurationError when initializing a Typesense client with incomplete configuration. ```typescript try { const client = new Typesense.Client({ apiKey: 'xyz' // Missing 'nodes' property }); } catch (err) { if (err instanceof Typesense.Errors.MissingConfigurationError) { console.log('Configuration error:', err.message); } } ``` -------------------------------- ### NodeConfigurationWithUrl Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/types.md Represents a node configuration using a full URL, simplifying connection setup when a complete URL is available. ```APIDOC ## NodeConfigurationWithUrl ### Description Represents a node configuration using a full URL, simplifying connection setup when a complete URL is available. ### Interface ```typescript interface NodeConfigurationWithUrl { url: string; } ``` ``` -------------------------------- ### List and Manage Aliases Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Aliases.md This example shows how to retrieve a list of all aliases, find a specific alias by name, update an existing alias, and delete an old alias. ```typescript const { aliases } = await client.aliases().retrieve(); // Find alias by name const booksAlias = aliases.find(a => a.name === 'books-latest'); if (booksAlias) { console.log(`books-latest points to: ${booksAlias.collection_name}`); } // Update alias await client.aliases().upsert('books-latest', { collection_name: 'books_v4' }); // Delete old alias await client.aliases('books-old').delete(); ``` -------------------------------- ### Constrained Document Schema Example Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/types.md Example of how to define a specific document schema for a 'Book' type and use it with the generic `documents` function. ```typescript interface Book { id: string; title: string; author: string; price: number; } // Usage documents() ``` -------------------------------- ### Search Multiple Collections Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/MultiSearch.md This example demonstrates how to search across multiple collections and retrieve separate results for each. ```APIDOC ## Search Multiple Collections ### Description Perform searches across multiple collections and receive distinct results for each. ### Method `client.multiSearch.perform` ### Parameters #### Searches An array of search requests, each specifying a collection and search parameters. - **collection** (string) - The name of the collection to search. - **q** (string) - The search query. - **query_by** (string) - The fields to search within. ### Request Example ```typescript const results = await client.multiSearch.perform({ searches: [ { collection: 'books', q: 'harry', query_by: 'title' }, { collection: 'authors', q: 'harry', query_by: 'name' } ] }); ``` ### Response #### Success Response The response contains a `results` array, where each element corresponds to the search results of a specific collection. - **results** (array) - An array of `SearchResponse` objects, one for each search performed. ### Response Example ```json { "results": [ { "hits": [ { "document": { "title": "Harry Potter and the Sorcerer's Stone" } }, { "document": { "title": "Harry Potter and the Chamber of Secrets" } } ], "found": 2 }, { "hits": [ { "document": { "name": "J.K. Rowling" } } ], "found": 1 } ] } ``` ``` -------------------------------- ### Browser Search Client Setup Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/README.md Initialize a Typesense SearchClient for use in a browser environment, specifying the search nodes and API key. Demonstrates a basic search function. ```typescript import Typesense from 'typesense'; const searchClient = new Typesense.SearchClient({ nodes: [{ host: 'search.example.com', port: 443, protocol: 'https' }], apiKey: 'search-key-xyz' }); async function search(q) { const results = await searchClient .collections('products') .documents() .search({ q, query_by: 'name,description' }); return results.hits?.map(h => h.document) || []; } ``` -------------------------------- ### Union Search Across Collections Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/MultiSearch.md This example shows how to perform a union search, merging results from multiple collections into a single response. ```APIDOC ## Union Search Across Collections ### Description Perform a union search across multiple collections, merging all results into a single `SearchResponse` object. ### Method `client.multiSearch.perform` with `union: true` ### Parameters #### Union (boolean) Set to `true` to enable union search. #### Searches An array of search requests, similar to the standard multi-search. ### Request Example ```typescript const results = await client.multiSearch.perform({ union: true, searches: [ { collection: 'books', q: 'harry', query_by: 'title' }, { collection: 'authors', q: 'harry', query_by: 'name' } ] }); ``` ### Response #### Success Response The response contains a single `SearchResponse` object with merged results. - **results** (`object`) - A single `SearchResponse` object containing merged hits from all searched collections. ### Response Example ```json { "results": { "hits": [ { "document": { "title": "Harry Potter and the Sorcerer's Stone" } }, { "document": { "name": "J.K. Rowling" } }, { "document": { "title": "Harry Potter and the Chamber of Secrets" } } ], "found": 3 } } ``` ``` -------------------------------- ### Get All Collections Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance to manage all collections. This is useful for operations that apply to all collections. ```typescript const allCollections = await client.collections().retrieve(); ``` -------------------------------- ### Get Synonym Sets Management Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for managing all synonym sets. This interface allows for operations on synonym configurations. ```typescript synonymSets(): SynonymSets ``` -------------------------------- ### Get Presets Management Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for managing all search presets. This interface is used for operations on search presets. ```typescript presets(): Presets ``` -------------------------------- ### Get Specific Preset Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for a specific preset by its ID. Use this to manage individual preset configurations. ```typescript presets(id: string): Preset ``` -------------------------------- ### Zero-Downtime Schema Updates Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Aliases.md This example illustrates how to perform zero-downtime schema updates by creating a new collection with updated fields, migrating data, switching the alias to the new collection, and then cleaning up the old collection. ```typescript // Create updated collection with new fields await client.collections().create({ name: 'books_v3', fields: [ { name: 'id', type: 'string' }, { name: 'title', type: 'string' }, { name: 'isbn', type: 'string' } // New field ] }); // Import data from old collection const data = await client .collections('books_v2') .documents() .export(); await client .collections('books_v3') .documents() .import(data, { action: 'create' }); // Switch alias to new collection await client.aliases().upsert('books-latest', { collection_name: 'books_v3' }); // Old collection can now be deleted await client.collections('books_v2').delete(); ``` -------------------------------- ### Get Keys Management Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for managing all API keys. Use this to perform operations related to API key management. ```typescript keys(): Keys ``` -------------------------------- ### Get Specific Synonym Set Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for a specific synonym set by its name. Use this to manage individual synonym sets. ```typescript synonymSets(synonymSetName: string): SynonymSet ``` -------------------------------- ### Search Documents in a Collection Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Provides an example of searching for documents within a collection. Specify the query string and the fields to search within. ```typescript // Search const results = await booksCollection.documents().search({ q: 'Harry', query_by: 'title' }); ``` -------------------------------- ### Typical MultiSearch Usage with Union Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/MultiSearch.md Shows a typical setup for performing a federated search across multiple collections using the `union: true` option. Includes client initialization and result processing. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }], apiKey: 'xyz' }); // Federated search with union const results = await client.multiSearch.perform({ union: true, searches: [ { collection: 'books', q: 'harry potter', query_by: 'title,author' }, { collection: 'reviews', q: 'harry potter', query_by: 'text' } ] }); console.log(`Found ${results.results.found} total results`); results.results.hits?.forEach(hit => { console.log(hit.document); }); ``` -------------------------------- ### Initialize Typesense Client and Create Collection Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/README.md Demonstrates initializing the Typesense client with connection details and API key, then creating a new collection named 'books'. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [ { host: 'localhost', port: 8108, protocol: 'http' } ], apiKey: 'your-api-key' }); // Create collection await client.collections().create({ name: 'books', fields: [ { name: 'id', type: 'string' }, { name: 'title', type: 'string' }, { name: 'author', type: 'string' } ] }); ``` -------------------------------- ### Initialize Typesense Client Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Demonstrates how to initialize the Typesense client with connection details and an API key. Ensure your Typesense instance is running and accessible. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [ { host: 'localhost', port: 8108, protocol: 'http' } ], apiKey: 'your-api-key' }); ``` -------------------------------- ### Catching TypesenseError Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md Example of how to catch and inspect a generic TypesenseError, checking for HTTP status and message. ```typescript try { await client.collections().retrieve(); } catch (err) { if (err instanceof Typesense.Errors.TypesenseError) { console.log(err.httpStatus); console.log(err.message); } } ``` -------------------------------- ### Initialize Typesense Client Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/00-START-HERE.md Set up a new Typesense client instance by providing the server node details and API key. Ensure the host, port, and protocol are correctly configured for your Typesense instance. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }], apiKey: 'xyz' }); ``` -------------------------------- ### collections() - Get All Collections Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/SearchClient.md Retrieves a Collections instance that provides read-only access to collection information. ```APIDOC ## collections() ```typescript collections(): Collections ``` Returns a Collections instance for retrieving collection information. ### Returns - `Collections` — Collections management interface (read-only) ``` -------------------------------- ### Create and Use Typesense.js Keys Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Keys.md Demonstrates creating a search-only key for frontend use, initializing a search client with it, and generating a scoped search key with a filter and expiration. Also shows creating a short-lived import key and retrieving all keys. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }], apiKey: 'master-api-key' }); // Create a search-only key for frontend use const frontendKey = await client.keys().create({ actions: ['documents:search'], collections: ['books'] }); // Use in frontend const searchClient = new Typesense.Client({ nodes: [{ host: 'search.example.com', port: 443, protocol: 'https' }], apiKey: frontendKey.value }); // Generate scoped key with filter const scopedKey = client.keys().generateScopedSearchKey( frontendKey.value, { filter_by: 'category:fiction', expires_at: Math.floor(Date.now() / 1000) + 86400 // 24 hours } ); // Create short-lived import key const importKey = await client.keys().create({ actions: ['documents:import'], collections: ['*'], expires_at: Math.floor(Date.now() / 1000) + 3600, description: 'Temporary import key' }); // List all keys const allKeys = await client.keys().retrieve(); console.log(`Total keys: ${allKeys.keys.length}`); ``` -------------------------------- ### Initialize and Use SearchClient in Browser Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/SearchClient.md This snippet demonstrates how to include the Typesense JavaScript library via CDN, initialize a SearchClient with node and API key details, and perform a search operation within a browser environment. It shows how to configure search parameters like 'q', 'query_by', and 'per_page', and how to process the search results. ```html ``` -------------------------------- ### Client Configuration with URL String Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/configuration.md Configure the client using a URL string for the node, simplifying configuration when a full URL is available. ```typescript const client = new Typesense.Client({ apiKey: 'xyz', nodes: [ { url: 'https://search.example.com:443' } ] }); ``` -------------------------------- ### retrieve() Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Aliases.md Retrieves all aliases currently configured in the Typesense instance. This is useful for getting an overview of all alias mappings. ```APIDOC ## retrieve() ### Description Retrieves all aliases. ### Method `async retrieve(): Promise` ### Response #### Success Response (200) - **aliases** (`CollectionAliasSchema[]`) - Array of all aliases ### Response Example ```typescript const response = await client.aliases().retrieve(); response.aliases.forEach(alias => { console.log(`${alias.name} → ${alias.collection_name}`); }); ``` ```json { "aliases": [ { "name": "books-latest", "collection_name": "books_v3" } ] } ``` ``` -------------------------------- ### Retrieve Health Status Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Health.md Get the current health status of the Typesense server. This is useful for basic checks. ```typescript const health = await client.health.retrieve(); if (health.ok) { console.log('Server is healthy'); } else { console.log('Server is not responding'); } ``` -------------------------------- ### Initialize Typesense Client and Check Health Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Health.md Demonstrates how to initialize the Typesense client and perform an initial health check. Includes basic error handling for connection issues. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }], apiKey: 'xyz' }); // Check if server is running try { const health = await client.health.retrieve(); if (health.ok) { console.log('Typesense server is ready'); } } catch (err) { console.error('Server is not responding:', err); } ``` -------------------------------- ### Get Conversations Management Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for managing all conversations. This interface is used for operations on conversation data. ```typescript conversations(): Conversations ``` -------------------------------- ### Client Constructor Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Initializes a Typesense client with the given configuration options. This is the primary way to create an instance of the Client class. ```APIDOC ## Constructor ```typescript constructor(options: ConfigurationOptions) ``` ### Description Initializes a Typesense client with the given configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | `ConfigurationOptions` | Yes | — | Client configuration options | ### Request Example ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [ { host: 'localhost', port: 8108, protocol: 'http' } ], apiKey: 'xyz', connectionTimeoutSeconds: 30 }); ``` ``` -------------------------------- ### Initialize Typesense Client in Browser Source: https://github.com/typesense/typesense-js/blob/master/doc/examples/browser/search.html Sets up a Typesense client instance for browser usage. It configures connection details, API key, and retry mechanisms. Note that using Typesense.Client is for demonstration; typically, Typesense.SearchClient is preferred for browser-only search operations. ```javascript var typesense = new Typesense.Client({ 'nodes': [ { 'host': 'localhost', 'port': '8108', 'protocol': 'http' } ], 'apiKey': 'xyz', 'numRetries': 3, 'connectionTimeoutSeconds': 10, 'retryIntervalSeconds': 0.1, 'healthcheckIntervalSeconds': 2, 'logLevel': 'debug' }) ``` -------------------------------- ### Get Specific Alias Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for a specific alias by its name. This allows for operations on a single alias. ```typescript aliases(aliasName: string): Alias ``` -------------------------------- ### Create Collection with Fields Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Collections.md Demonstrates how to create a new collection by defining its name and fields directly. ```APIDOC ## Create Collection with Fields ### Description Creates a new collection by specifying its name and an array of field definitions. ### Method `POST` (implied by `create` operation on a collection resource) ### Endpoint `/collections` ### Request Body - **name** (string) - Required - The name of the collection. - **fields** (array) - Required - An array of field objects, each defining a field's name, type, and other properties. - **name** (string) - Required - The name of the field. - **type** (string) - Required - The data type of the field (e.g., 'string', 'float'). - **facet** (boolean) - Optional - Whether the field should be faceted. - **num_dim** (integer) - Optional - The number of dimensions for vector fields. ### Request Example ```json { "name": "products", "fields": [ { "name": "id", "type": "string" }, { "name": "name", "type": "string" }, { "name": "category", "type": "string", "facet": true }, { "name": "price", "type": "float" } ] } ``` ### Response #### Success Response (200) - **name** (string) - The name of the created collection. - **fields** (array) - The fields defined for the collection. #### Response Example ```json { "name": "products", "fields": [ { "name": "id", "type": "string" }, { "name": "name", "type": "string" }, { "name": "category", "type": "string", "facet": true }, { "name": "price", "type": "float" } ] } ``` ``` -------------------------------- ### Get Specific Conversation Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for a specific conversation by its ID. Use this to manage individual conversation threads. ```typescript conversations(id: string): Conversation ``` -------------------------------- ### Get Stopwords Management Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for managing all stopword sets. This interface allows for operations on stopword lists. ```typescript stopwords(): Stopwords ``` -------------------------------- ### Client Configuration with Logging Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/configuration.md Configure the client with logging enabled. You can set the `logLevel` or provide a custom logger instance. ```typescript const client = new Typesense.Client({ apiKey: 'xyz', nodes: [ { host: 'localhost', port: 8108, protocol: 'http' } ], logLevel: 'debug', // Or use custom logger: logger: customLoggerInstance }); ``` -------------------------------- ### Client Class Documentation Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/MANIFEST.txt Documentation for the main Client class, which serves as the primary entry point for interacting with Typesense. It includes all available methods for managing collections, documents, and performing searches. ```APIDOC ## Client Class ### Description The `Client` class is the main entry point for the typesense-js library, providing access to all Typesense API functionalities. It is suitable for both Node.js and browser environments. ### Methods All public methods of the `Client` class are documented, including their signatures, parameter types with descriptions, return types, and error conditions. ### Usage Examples Real-world code examples are provided throughout the documentation, covering basic usage, advanced features, and specific patterns like multi-search and federated search. ``` -------------------------------- ### SearchClient Constructor Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/SearchClient.md Initializes a new SearchClient instance with the provided configuration options. This client is optimized for search-only operations. ```APIDOC ## Constructor ```typescript constructor(options: ConfigurationOptions) ``` Initializes a search-only Typesense client. Similar to Client but with only search endpoints available. ### Parameters - **options** (`ConfigurationOptions`) - Required - Client configuration options **Note:** SearchClient automatically sets `sendApiKeyAsQueryParam` to `true` to support browser CORS requests. ### Example ```typescript import Typesense from 'typesense'; const searchClient = new Typesense.SearchClient({ nodes: [ { host: 'search.example.com', port: 443, protocol: 'https' } ], apiKey: 'search-key-xyz' }); ``` ``` -------------------------------- ### Initialize SearchClient Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/SearchClient.md Instantiate the SearchClient with connection nodes, API key, and other configuration options. Use this for search-only operations. ```typescript const searchClient = new Typesense.SearchClient({ nodes: [ { host: 'search-1.example.com', port: 443, protocol: 'https' }, { host: 'search-2.example.com', port: 443, protocol: 'https' } ], apiKey: 'search-key-xyz', connectionTimeoutSeconds: 15, numRetries: 3, cacheSearchResultsForSeconds: 300 }); ``` -------------------------------- ### Get Aliases Management Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for managing all aliases. This interface allows for operations related to alias management. ```typescript aliases(): Aliases ``` -------------------------------- ### Frontend Search with Typesense.js Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/SearchClient.md Demonstrates how to create a Typesense.js SearchClient for frontend use and perform a search query with filtering and sorting. Ensure you use a 'search-only-key' for frontend security. ```typescript import Typesense from 'typesense'; // Create search client for frontend const searchClient = new Typesense.SearchClient({ nodes: [{ host: 'search.example.com', port: 443, protocol: 'https' }], apiKey: 'search-only-key' }); // Search in component async function performSearch(query) { try { const results = await searchClient .collections('products') .documents() .search({ q: query, query_by: 'name,description', filter_by: 'in_stock:true', sort_by: 'popularity:desc', per_page: 20 }); return results; } catch (err) { console.error('Search failed:', err); } } ``` -------------------------------- ### Initialize Typesense Client Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Initializes a Typesense client with the provided configuration options, including server nodes, API key, and connection timeout. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [ { host: 'localhost', port: 8108, protocol: 'http' } ], apiKey: 'xyz', connectionTimeoutSeconds: 30 }); ``` -------------------------------- ### Get Specific Stopword Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for a specific stopword set by its ID. Use this to manage individual stopword configurations. ```typescript stopwords(id: string): Stopword ``` -------------------------------- ### Node Configuration with URL Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/configuration.md Configure a Typesense server node using a complete URL. This is a simpler alternative when the full URL is known. ```typescript { url: 'https://search.example.com:443' } ``` -------------------------------- ### Get Curation Sets Management Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for managing all curation sets. This interface is used for operations on curation set data. ```typescript curationSets(): CurationSets ``` -------------------------------- ### Create Collection, Index Documents, and Search Source: https://github.com/typesense/typesense-js/blob/master/doc/examples/browser/search.html Orchestrates the creation of a Typesense collection, indexing of documents, and setting up a search function. It includes error handling for collection deletion and creation, and uses Promise.all for efficient document indexing. The search function retrieves results based on user input. ```javascript typesense.collections('companies').delete() .finally(function () { // create a collection typesense.collections().create(schema) .then(function () { // create a couple of documents Promise.all(documents.map(function (document) { return typesense.collections('companies').documents().create(document) })) }).catch(function (error) { console.log(error) }) }).catch(function (error) { // do nothing }) function search () { var searchTerm = document.getElementById('search-input').value typesense.collections('companies').documents().search({ 'q': searchTerm, 'query_by': 'company_name' }).then(function (searchResults) { document.getElementById('search-results').innerHTML = JSON.stringify(searchResults, null, 2) }).catch(function (error) { document.getElementById('search-results').innerHTML = error }) } ``` -------------------------------- ### Create Collection from Schema Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Collections.md Shows how to create a new collection based on the schema of an existing collection, with potential modifications. ```APIDOC ## Create Collection from Schema ### Description Creates a new collection using the schema of an existing collection, allowing for new fields to be added. ### Method `POST` (implied by `create` operation on a collection resource) ### Endpoint `/collections` ### Parameters #### Request Body - **name** (string) - Required - The name of the new collection. - **fields** (array) - Required - An array of field objects for the new collection. Can include fields from the source collection and new fields. - **name** (string) - Required - The name of the field. - **type** (string) - Required - The data type of the field. - **num_dim** (integer) - Optional - The number of dimensions for vector fields. - **src_name** (string) - Required - The name of the existing collection to copy the schema from. ### Request Example ```json { "name": "books_v2", "fields": [ { "name": "embedding", "type": "object", "num_dim": 768 } ], "src_name": "books" } ``` ### Response #### Success Response (200) - **name** (string) - The name of the created collection. - **fields** (array) - The fields defined for the collection. #### Response Example ```json { "name": "books_v2", "fields": [ { "name": "embedding", "type": "object", "num_dim": 768 } ] } ``` ``` -------------------------------- ### Node Configuration with Host, Port, and Protocol Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/configuration.md Configure a Typesense server node using its hostname, port, and protocol. The 'path' field is optional for URL path prefixes. ```typescript { host: 'localhost', port: 8108, protocol: 'http' } ``` -------------------------------- ### ObjectNotFound Error (HTTP 404) Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md Thrown when attempting to access a resource that does not exist, such as a non-existent collection or document. This example shows how to specifically catch this error. ```typescript class ObjectNotFound extends TypesenseError {} ``` ```typescript try { await client.collections('nonexistent').retrieve(); } catch (err) { if (err instanceof Typesense.Errors.ObjectNotFound) { console.log('Collection does not exist'); } } ``` -------------------------------- ### Typical Usage of Document Class Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Document.md Demonstrates the typical workflow for interacting with a single document using the Typesense.js client, including initialization, retrieval, partial retrieval, updates, and deletion. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }], apiKey: 'xyz' }); interface Book { id: string; title: string; author: string; price: number; rating: number; } const bookDoc = client.collections('books').documents('1'); // Retrieve document const book = await bookDoc.retrieve(); console.log(book.title); // Get only certain fields const basic = await bookDoc.retrieve({ include_fields: ['title', 'author'] }); // Update rating await bookDoc.update({ rating: 4.8 }); // Delete document await bookDoc.delete(); ``` -------------------------------- ### Get Specific Collection Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for a specific collection by its name. Use this to perform operations on a single collection, such as searching documents within it. ```typescript const booksCollection = client.collections('books'); const book = await booksCollection.documents().search({ q: 'harry' }); ``` -------------------------------- ### Client Configuration with Custom Axios Adapter Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/configuration.md Configure the client with a custom Axios adapter, useful for environments like edge functions where the default adapter may not be suitable. ```typescript const client = new Typesense.Client({ apiKey: 'xyz', nodes: [ { host: 'localhost', port: 8108, protocol: 'http' } ], axiosAdapter: customAdapter // For edge functions, etc. }); ``` -------------------------------- ### ServerError Error (HTTP 5xx) Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md Thrown when the Typesense server encounters an internal error, such as a service unavailability or timeout. This example shows how to catch server-side errors. ```typescript class ServerError extends TypesenseError {} ``` ```typescript try { await client.collections().retrieve(); } catch (err) { if (err instanceof Typesense.Errors.ServerError) { console.log('Server error:', err.message); } } ``` -------------------------------- ### Basic Single Node Configuration Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/configuration.md Configure the client to connect to a single Typesense node. Ensure the API key and node details are correct. ```typescript const client = new Typesense.Client({ apiKey: 'xyz', nodes: [ { host: 'localhost', port: 8108, protocol: 'http' } ] }); ``` -------------------------------- ### Multi-Search with Filters - TypeScript Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/MultiSearch.md Utilize `filter_by` to refine search results within each collection during a multi-search. This example demonstrates filtering books by different price ranges. ```typescript const results = await client.multiSearch.perform({ searches: [ { collection: 'books', q: '*', query_by: 'title', filter_by: 'price:<20' }, { collection: 'books', q: '*', query_by: 'title', filter_by: 'price:>=20' } ] }); // Separate price ranges console.log('Cheap books:', results.results[0].found); console.log('Expensive books:', results.results[1].found); ``` -------------------------------- ### collections(collectionName) - Get Specific Collection Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/SearchClient.md Returns a Collection instance for a specific collection identified by its name. This instance is optimized for search-only operations within that collection. ```APIDOC ## collections(collectionName) ```typescript collections = object>(collectionName: string): Collection ``` Returns a Collection instance for a specific collection by name (search-only). ### Parameters - **collectionName** (`string`) - Required - The name of the collection ### Type Parameters - `T` — Document schema type (defaults to `object`) ### Returns - `Collection` — Collection instance (search-only) ### Example ```typescript const booksCollection = searchClient.collections('books'); const book = await booksCollection.documents().search({ q: 'harry' }); ``` ``` -------------------------------- ### Manage Documents in Typesense Collection Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Documents.md This snippet demonstrates the full lifecycle of document management, including creation, bulk import, searching, updating, deleting, and exporting. Ensure you have initialized the Typesense client with your cluster details and API key. ```typescript import Typesense from 'typesense'; const client = new Typesense.Client({ nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }], apiKey: 'xyz' }); const docs = client.collections('books').documents(); // Create single document await docs.create({ id: '1', title: 'Harry Potter', author: 'J.K. Rowling', price: 9.99 }); // Bulk import await docs.import([ { id: '2', title: 'The Hobbit', author: 'J.R.R. Tolkien', price: 8.99 }, { id: '3', title: '1984', author: 'George Orwell', price: 7.99 } ]); // Search const results = await docs.search({ q: 'harry', query_by: 'title', sort_by: 'price:asc' }); // Update await docs.update({ id: '1', price: 7.99 }); // Delete await docs.delete({ filter_by: 'price:<5' }); // Export const jsonl = await docs.export(); ``` -------------------------------- ### Get Specific API Key Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for a specific API key by its ID. This allows for operations on a single API key, such as retrieval or deletion. ```typescript const apiKey = await client.keys(1).retrieve(); await client.keys(1).delete(); ``` -------------------------------- ### Create a Collection Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Shows how to create a new collection in Typesense, defining its name and fields. This is a prerequisite for adding documents. ```typescript // Create a collection await client.collections().create({ name: 'books', fields: [ { name: 'id', type: 'string' }, { name: 'title', type: 'string' }, { name: 'author', type: 'string' } ] }); ``` -------------------------------- ### Handle ImportError during Bulk Import Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md Example of catching an ImportError when documents fail during a bulk import operation. It logs the number of successful imports and details about any failed documents. ```typescript try { await client.collections('books').documents().import([ { id: '1', title: 'Book 1' }, { id: '2', title: 'Book 2', price: 'invalid' } // Invalid data ]); } catch (err) { if (err instanceof Typesense.Errors.ImportError) { console.log(`Imported ${err.payload.successCount} documents`); err.importResults.forEach((result, index) => { if (!result.success) { console.log(`Document ${index} failed: ${result.error}`); } }); } } ``` -------------------------------- ### Initialize Typesense SearchClient Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/00-START-HERE.md Instantiate the browser-safe SearchClient for search-only operations. Requires nodes and a search API key. ```typescript const searchClient = new Typesense.SearchClient({ nodes: [...], apiKey: 'search-key' }); ``` -------------------------------- ### Perform a Search with All Options Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/00-START-HERE.md Use this to perform a search query with various parameters like query_by, filter_by, sort_by, and faceting. Ensure the collection and fields are configured correctly. ```typescript const results = await client.collections('books').documents().search({ q: 'harry potter', query_by: 'title,author', filter_by: 'price:<20', sort_by: 'rating:desc', facet_by: 'genre', page: 1, per_page: 20 }); ``` -------------------------------- ### HTTPError Generic Error Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md A generic HTTP error class for status codes not covered by specific error classes. This example demonstrates catching any unhandled HTTP errors. ```typescript class HTTPError extends TypesenseError {} ``` ```typescript try { await client.collections().retrieve(); } catch (err) { if (err instanceof Typesense.Errors.HTTPError) { console.log(`HTTP ${err.httpStatus}: ${err.message}`); } } ``` -------------------------------- ### RequestMalformed Error (HTTP 400) Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md Thrown when a request is malformed or contains invalid data, such as an incomplete collection schema. This example shows how to catch this error and log the message. ```typescript class RequestMalformed extends TypesenseError {} ``` ```typescript try { await client.collections().create({ name: 'books' // Missing required 'fields' property }); } catch (err) { if (err instanceof Typesense.Errors.RequestMalformed) { console.log('Invalid request:', err.message); } } ``` -------------------------------- ### Searching with All Options Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/README.md Perform a search query on a collection with various parameters including query_by, filter_by, sort_by, facets, pagination, and prefix matching. ```typescript const results = await client .collections('books') .documents() .search({ q: 'harry potter', query_by: 'title,author', filter_by: 'price:<20 && in_stock:true', sort_by: 'rating:desc,price:asc', facet_by: 'author,genre', page: 1, per_page: 20, prefix: true }); console.log(`Found ${results.found} books`); results.facet_counts?.forEach(facet => { console.log(`${facet.field_name}: ${facet.counts.length} options`); }); ``` -------------------------------- ### ObjectAlreadyExists Error (HTTP 409) Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md Thrown when attempting to create a resource that already exists, like a collection with a duplicate name. This example demonstrates catching this specific error. ```typescript class ObjectAlreadyExists extends TypesenseError {} ``` ```typescript try { await client.collections().create({ name: 'books', fields: [{ name: 'id', type: 'string' }] }); // Duplicate collection name await client.collections().create({ name: 'books', fields: [{ name: 'id', type: 'string' }] }); } catch (err) { if (err instanceof Typesense.Errors.ObjectAlreadyExists) { console.log('Collection already exists'); } } ``` -------------------------------- ### Initialize SearchClient Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/SearchClient.md Instantiate a search-only Typesense client with configuration options. This client is optimized for search operations and automatically sets `sendApiKeyAsQueryParam` to `true` for browser CORS compatibility. ```typescript import Typesense from 'typesense'; const searchClient = new Typesense.SearchClient({ nodes: [ { host: 'search.example.com', port: 443, protocol: 'https' } ], apiKey: 'search-key-xyz' }); ``` -------------------------------- ### Create API Key Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Keys.md Creates a new API key with specified permissions and actions. You can define allowed actions, collections, and set expiration or description. ```APIDOC ## POST /keys ### Description Creates a new API key with specified permissions and actions. ### Method POST ### Endpoint /keys ### Parameters #### Request Body - **params** (KeyCreateSchema) - Required - Key creation parameters **KeyCreateSchema Properties:** - **actions** (Actions[]) - Required - Allowed actions/permissions - **collections** (string[]) - Required - Collections this key can access - **description** (string) - Optional - Human-readable description - **value** (string) - Optional - Custom key value (if not provided, auto-generated) - **value_prefix** (string) - Optional - Prefix for auto-generated key - **expires_at** (number) - Optional - Unix timestamp when key expires - **autodelete** (boolean) - Optional - Auto-delete when expired ### Response #### Success Response (200) - **id** (number) - Unique key ID - **actions** (Actions[]) - Allowed actions - **collections** (string[]) - Accessible collections - **description** (string) - Key description - **value** (string) - The actual key value - **value_prefix** (string) - Key prefix - **expires_at** (number) - Expiration timestamp - **autodelete** (boolean) - Auto-delete flag ### Request Example ```typescript // Create search-only key const searchKey = await client.keys().create({ actions: ['documents:search'], collections: ['books', 'authors'] }); console.log(`Key created: ${searchKey.value}`); // Create key with expiration const tempKey = await client.keys().create({ actions: ['documents:*'], collections: ['books'], description: 'Temporary key for demo', expires_at: Math.floor(Date.now() / 1000) + 3600 // 1 hour }); // Create key with specific value const customKey = await client.keys().create({ value: 'my-custom-key-xyz', actions: ['documents:search', 'collections:get'], collections: ['*'] }); ``` ``` -------------------------------- ### Get NL Search Models Management Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for managing all Natural Language search models. This interface is used for operations on NL search models. ```typescript nlSearchModels(): NLSearchModels ``` -------------------------------- ### Get Specific NL Search Model Instance Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Client.md Retrieve an instance for a specific Natural Language search model by its ID. Use this to manage individual NL search models. ```typescript nlSearchModels(id: string): NLSearchModel ``` -------------------------------- ### Create Collection with Fields Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/Collections.md Use this to create a new collection and define its schema, including field names and types. ```typescript const collection = await client.collections().create({ name: 'products', fields: [ { name: 'id', type: 'string' }, { name: 'name', type: 'string' }, { name: 'category', type: 'string', facet: true }, { name: 'price', type: 'float' } ] }); ``` -------------------------------- ### Autocomplete Search with Typesense.js Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/api-reference/SearchClient.md Shows how to implement an autocomplete feature by searching with the 'prefix' option enabled. This is useful for providing real-time suggestions as a user types. ```typescript const searchClient = new Typesense.SearchClient({ nodes: [{ host: 'search.example.com', port: 443, protocol: 'https' }], apiKey: 'search-key' }); async function autocomplete(prefix) { const results = await searchClient .collections('products') .documents() .search({ q: prefix, query_by: 'name', prefix: true, per_page: 10, include_fields: 'name,id' }); return results.hits?.map(h => h.document.name) || []; } // Usage const suggestions = await autocomplete('iphone'); ``` -------------------------------- ### RequestUnauthorized Error (HTTP 401) Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/errors.md Thrown when authentication fails due to invalid or missing API keys, or insufficient permissions. This example demonstrates catching this error with an invalid API key. ```typescript class RequestUnauthorized extends TypesenseError {} ``` ```typescript try { const client = new Typesense.Client({ apiKey: 'invalid-key', nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }] }); await client.collections().retrieve(); } catch (err) { if (err instanceof Typesense.Errors.RequestUnauthorized) { console.log('Invalid API key'); } } ``` -------------------------------- ### Project Documentation Structure Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/00-START-HERE.md Overview of the directory structure for the typesense-js project documentation. This helps in navigating and understanding the organization of different documentation files. ```text output/ ├── 00-START-HERE.md (you are here) ├── README.md # Overview & quick start ├── INDEX.md # Complete reference index ├── configuration.md # Configuration options ├── types.md # TypeScript types ├── errors.md # Error handling ├── MANIFEST.txt # Documentation manifest └── api-reference/ ├── Client.md # Main client ├── SearchClient.md # Browser client ├── Collections.md # Multiple collections ├── Collection.md # Single collection ├── Documents.md # Document operations ├── Document.md # Single document ├── MultiSearch.md # Multi-collection search ├── Aliases.md # Aliases ├── Overrides.md # Overrides ├── Keys.md # API keys └── Health.md # Health checks ``` -------------------------------- ### Override Search Cache Per Request Source: https://github.com/typesense/typesense-js/blob/master/_autodocs/configuration.md You can override the client's default cache configuration for individual search requests. This example sets the cache duration to 600 seconds for a specific search. ```typescript const results = await collection.documents().search( { q: 'query' }, { cacheSearchResultsForSeconds: 600, // Override client config abortSignal: controller.signal // Cancel request } ); ```