### Install MiniSearch with npm Source: https://lucaong.github.io/minisearch/index.html Use npm to add MiniSearch to your project dependencies. ```bash npm install minisearch Copy ``` -------------------------------- ### Install MiniSearch with yarn Source: https://lucaong.github.io/minisearch/index.html Use yarn to add MiniSearch to your project dependencies. ```bash yarn add minisearch Copy ``` -------------------------------- ### Basic MiniSearch Setup and Usage Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Demonstrates how to create a MiniSearch instance, add documents, and perform a search. Configure fields for indexing and storing search results. ```javascript const documents = [ { id: 1, title: 'Moby Dick', text: 'Call me Ishmael. Some years ago...', category: 'fiction' }, { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', text: 'I can see by my watch...', category: 'fiction' }, { id: 3, title: 'Neuromancer', text: 'The sky above the port was...', category: 'fiction' }, { id: 4, title: 'Zen and the Art of Archery', text: 'At first sight it must seem...', category: 'non-fiction' }, // ...and more ] // Create a search engine that indexes the 'title' and 'text' fields for // full-text search. Search results will include 'title' and 'category' (plus the // id field, that is always stored and returned) const miniSearch = new MiniSearch({ fields: ['title', 'text'], storeFields: ['title', 'category'] }) // Add documents to the index miniSearch.addAll(documents) // Search for documents: let results = miniSearch.search('zen art motorcycle') // => [ // { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', category: 'fiction', score: 2.77258 }, // { id: 4, title: 'Zen and the Art of Archery', category: 'non-fiction', score: 1.38629 } // ] ``` -------------------------------- ### Prefix Search in MiniSearch Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Enable prefix matching for search terms. This finds documents where terms start with the provided characters. ```javascript miniSearch.search('moto neuro', { prefix: true }) ``` -------------------------------- ### Custom Term Processing for Indexing Source: https://lucaong.github.io/minisearch/index.html Use the `processTerm` option during Minisearch initialization to customize how terms are processed for indexing. This example demonstrates discarding stop words and downcasing terms. ```javascript let stopWords = new Set(['and', 'or', 'to', 'in', 'a', 'the', /* ...and more */ ]) // Perform custom term processing (here discarding stop words and downcasing) let miniSearch = new MiniSearch({ fields: ['title', 'text'], processTerm: (term, _fieldName) => stopWords.has(term) ? null : term.toLowerCase() }) ``` -------------------------------- ### Basic Auto-Suggestion Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Get suggestions for a single word query. The result includes suggested queries and their relevance scores. ```javascript miniSearch.autoSuggest('neuro') ``` -------------------------------- ### get Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Retrieves the value associated with the specified key from the map. Returns undefined if the key is not found. ```APIDOC ## get ### Description Retrieves the value associated with the specified key from the map. ### Parameters #### Path Parameters - **key** (string) - Required - Key to get. ### Returns undefined | T - Value associated to the key, or `undefined` if the key is not found. ### See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get ``` -------------------------------- ### Get Default MiniSearch Option Value Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Retrieves the default value for a specified MiniSearch option. Passing an unknown option name will result in an error. ```javascript MiniSearch.getDefault('tokenize') MiniSearch.getDefault('processTerm') MiniSearch.getDefault('notExisting') ``` -------------------------------- ### Custom stringifyField for Date Formatting Source: https://lucaong.github.io/minisearch/types/MiniSearch.Options.html Use a custom stringifyField function to format specific field values into strings for indexing. This example formats Date objects into a readable string. ```javascript const miniSearch = new MiniSearch({ fields: ['title', 'date'], stringifyField: ((fieldValue, _fieldName) => { if (fieldValue instanceof Date) { return fieldValue.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) } else { return fieldValue.toString() } }) }) ``` -------------------------------- ### MiniSearch Constructor with All Options Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Illustrates the full set of configuration options available for the MiniSearch constructor, including default values. ```javascript // The full set of options (here with their default value) is: const miniSearch = new MiniSearch({ // idField: field that uniquely identifies a document idField: 'id', // extractField: function used to get the value of a field in a document. // By default, it assumes the document is a flat object with field names as // property keys and field values as string property values, but custom logic // can be implemented by setting this option to a custom extractor function. extractField: (document, fieldName) => document[fieldName], // tokenize: function used to split fields into individual terms. By // default, it is also used to tokenize search queries, unless a specific // `tokenize` search option is supplied. When tokenizing an indexed field, // the field name is passed as the second argument. tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION), // processTerm: function used to process each tokenized term before // indexing. It can be used for stemming and normalization. Return a falsy // value in order to discard a term. By default, it is also used to process // search queries, unless a specific `processTerm` option is supplied as a // search option. When processing a term from a indexed field, the field // name is passed as the second argument. processTerm: (term, _fieldName) => term.toLowerCase(), // searchOptions: default search options, see the `search` method for // details searchOptions: undefined, // fields: document fields to be indexed. Mandatory, but not set by default fields: undefined // storeFields: document fields to be stored and returned as part of the // search results. storeFields: [] }) ``` -------------------------------- ### Options Source: https://lucaong.github.io/minisearch/types/MiniSearch.Options.html Configuration options passed to the MiniSearch constructor. ```APIDOC ## Type alias Options Options: { autoSuggestOptions?: SearchOptions; autoVacuum?: boolean | AutoVacuumOptions; extractField?: ((document: T, fieldName: string) => any); fields: string[]; idField?: string; logger?: ((level: LogLevel, message: string, code?: string) => void); processTerm?: ((term: string, fieldName?: string) => string | string[] | null | undefined | false); searchOptions?: SearchOptions; storeFields?: string[]; stringifyField?: ((fieldValue: any, fieldName: string) => string); tokenize?: ((text: string, fieldName?: string) => string[]); } ### Type Parameters * T = any The type of documents being indexed. ### Properties * `Optional` autoSuggestOptions?: SearchOptions Default auto suggest options (see the SearchOptions type and the MiniSearch#autoSuggest method for details). * `Optional` autoVacuum?: boolean | AutoVacuumOptions If `true` (the default), vacuuming is performed automatically as soon as MiniSearch#discard is called a certain number of times, cleaning up obsolete references from the index. If `false`, no automatic vacuuming is performed. Custom settings controlling auto vacuuming thresholds, as well as batching behavior, can be passed as an object (see the AutoVacuumOptions type). * `Optional` extractField?: ((document: T, fieldName: string) => any) Function used to extract the value of each field in documents. By default, the documents are assumed to be plain objects with field names as keys, but by specifying a custom `extractField` function one can completely customize how the fields are extracted. The function takes as arguments the document, and the name of the field to extract from it. It should return the field value as a string. #### Remarks The returned string is fed into the `tokenize` function to split it up into tokens. * * (document, fieldName): any * #### Parameters * document: T * fieldName: string #### Returns any * fields: string[] Names of the document fields to be indexed. * `Optional` idField?: string Name of the ID field, uniquely identifying a document. * `Optional` logger?: ((level: LogLevel, message: string, code?: string) => void) Function called to log messages. Arguments are a log level ('debug', 'info', 'warn', or 'error'), a log message, and an optional string code that identifies the reason for the log. The default implementation uses `console`, if defined. * * (level, message, code?): void * #### Parameters * level: LogLevel * message: string * `Optional` code: string #### Returns void * `Optional` processTerm?: ((term: string, fieldName?: string) => string | string[] | null | undefined | false) Function used to process a term before indexing or search. This can be used for normalization (such as stemming). By default, terms are downcased, and otherwise no other normalization is performed. The function takes as arguments a term to process, and the name of the field it comes from. It should return the processed term as a string, or a falsy value to reject the term entirely. It can also return an array of strings, in which case each string in the returned array is indexed as a separate term. #### Remarks During the document indexing phase, the first step is to call the `extractField` function to fetch the requested value/field from the document. This is then passed off to the `tokenizer`, which will break apart each value into "terms". These terms are then individually passed through the `processTerm` function to compute each term individually. A term might for example be something like "lbs", in which case one would likely want to return `[ "lbs", "lb", "pound", "pounds" ]`. You may also return a single string value, or a falsy value if you would like to skip indexing entirely for a specific term. Truthy return value(s) are then fed to the indexer as positive matches for this document. In our example above, all four of the `[ "lbs", "lb", "pound", "pounds" ]` terms would be added to the indexing engine, matching against the current document being computed. _Note: Whatever values are returned from this function will receive no further processing before being indexed. This means for example, if you include whitespace at the beginning or end of a word, it will also be indexed that way, with the included whitespace._ * * (term, fieldName?): string | string[] | null | undefined | false * #### Parameters * term: string * `Optional` fieldName: string * `Optional` searchOptions?: SearchOptions Default search options (see the SearchOptions type and the MiniSearch#search method for details). * `Optional` storeFields?: string[] Fields to be stored with documents. By default, only the document IDs are stored. If you want to retrieve documents from the search results, you must specify which fields to store. * `Optional` stringifyField?: ((fieldValue: any, fieldName: string) => string) Function used to stringify field values before they are passed to the `tokenize` function. By default, field values are converted to strings using `String()`. * `Optional` tokenize?: ((text: string, fieldName?: string) => string[]) Function used to tokenize text. By default, text is split into words using a regular expression that matches sequences of alphanumeric characters. ``` -------------------------------- ### Basic MiniSearch Usage Source: https://lucaong.github.io/minisearch/index.html Demonstrates initializing MiniSearch, indexing documents, and performing a search query. Configure fields to index and fields to store with results. ```javascript // A collection of documents for our examples const documents = [ { id: 1, title: 'Moby Dick', text: 'Call me Ishmael. Some years ago...', category: 'fiction' }, { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', text: 'I can see by my watch...', category: 'fiction' }, { id: 3, title: 'Neuromancer', text: 'The sky above the port was...', category: 'fiction' }, { id: 4, title: 'Zen and the Art of Archery', text: 'At first sight it must seem...', category: 'non-fiction' }, // ...and more ] let miniSearch = new MiniSearch({ fields: ['title', 'text'], // fields to index for full-text search storeFields: ['title', 'category'] // fields to return with search results }) // Index all documents miniSearch.addAll(documents) // Search with default options let results = miniSearch.search('zen art motorcycle') // => [ // { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', category: 'fiction', score: 2.77258, match: { ... } }, // { id: 4, title: 'Zen and the Art of Archery', category: 'non-fiction', score: 1.38629, match: { ... } } // ] Copy ``` -------------------------------- ### Filtered Auto-Suggestion Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Get suggestions for a query, but only include results that match a specific filter condition. This is useful for narrowing down suggestions based on document properties. ```javascript miniSearch.autoSuggest('zen ar', { filter: (result) => result.category === 'fiction' }) ``` -------------------------------- ### MiniSearch Constructor with Fields Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Instantiate MiniSearch by specifying which document fields to index for searching. ```javascript // Create a search engine that indexes the 'title' and 'text' fields of your // documents: const miniSearch = new MiniSearch({ fields: ['title', 'text'] }) ``` -------------------------------- ### Fetch or Create a Value with `fetch` Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html The `fetch` method retrieves a value by key. If the key doesn't exist, it calls the provided `initial` function to create and insert a new value, which is then returned. ```javascript const map = searchableMap.fetch('somekey', () => new Map()) map.set('foo', 'bar') ``` -------------------------------- ### Static loadJSONAsync(json, options) Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Asynchronously deserializes a JSON index and instantiates a MiniSearch instance. ```APIDOC ## Static loadJSONAsync(json, options) ### Description Async equivalent of MiniSearch.loadJSON. This function is an alternative to MiniSearch.loadJSON that returns a promise, and loads the index in batches, leaving pauses between them to avoid blocking the main thread. It tends to be slower than the synchronous version, but does not block the main thread, so it can be a better choice when deserializing very large indexes. ### Parameters #### Path Parameters - **json** (string) - Required - JSON-serialized index - **options** (Options) - Required - configuration options, same as the constructor ### Returns Promise>: A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON. ``` -------------------------------- ### MiniSearch Constructor Source: https://lucaong.github.io/minisearch/index.html Initializes a new MiniSearch instance. You can configure which fields to index and which fields to store with the search results. ```APIDOC ## new MiniSearch(options) ### Description Initializes a new MiniSearch instance with specified configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Required - Configuration options for MiniSearch. - **fields** (array of strings) - Required - The fields to index for full-text search. - **storeFields** (array of strings) - Optional - The fields to return with search results. ### Request Example ```javascript let miniSearch = new MiniSearch({ fields: ['title', 'text'], storeFields: ['title', 'category'] }); ``` ### Response #### Success Response (200) Returns a new MiniSearch instance. #### Response Example (Instance of MiniSearch) ``` -------------------------------- ### Static loadJSON(json, options) Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Deserializes a JSON index and instantiates a MiniSearch instance. ```APIDOC ## Static loadJSON(json, options) ### Description Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`) and instantiates a MiniSearch instance. It should be given the same options originally used when serializing the index. ### Parameters #### Path Parameters - **json** (string) - Required - JSON-serialized index - **options** (Options) - Required - configuration options, same as the constructor ### Returns MiniSearch: An instance of MiniSearch deserialized from the given JSON. ### Usage: ```javascript // If the index was serialized with: let miniSearch = new MiniSearch({ fields: ['title', 'text'] }) miniSearch.addAll(documents) const json = JSON.stringify(miniSearch) // It can later be deserialized like this: miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] }) ``` ``` -------------------------------- ### constructor Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Initializes a new SearchableMap. Typically called without arguments for an empty map. Arguments are for internal use when creating derived views. ```APIDOC ## constructor * new SearchableMap(tree?, prefix?): SearchableMap * The constructor is normally called without arguments, creating an empty map. In order to create a SearchableMap from an iterable or from an object, check SearchableMap.from and SearchableMap.fromObject. The constructor arguments are for internal use, when creating derived mutable views of a map at a prefix. #### Type Parameters * T = any #### Parameters * tree: RadixTree = ... * prefix: string = '' #### Returns SearchableMap ``` -------------------------------- ### MiniSearch Search Options Source: https://lucaong.github.io/minisearch/index.html Demonstrates various search options including field searching, boosting, prefix search, filtering, and fuzzy search. Can also set default search options during initialization. ```javascript // Search only specific fields miniSearch.search('zen', { fields: ['title'] }) ``` ```javascript // Boost some fields (here "title") miniSearch.search('zen', { boost: { title: 2 } }) ``` ```javascript // Prefix search (so that 'moto' will match 'motorcycle') miniSearch.search('moto', { prefix: true }) ``` ```javascript // Search within a specific category miniSearch.search('zen', { filter: (result) => result.category === 'fiction' }) ``` ```javascript // Fuzzy search, in this example, with a max edit distance of 0.2 * term length, // rounded to nearest integer. The mispelled 'ismael' will match 'ishmael'. miniSearch.search('ismael', { fuzzy: 0.2 }) ``` ```javascript // You can set the default search options upon initialization miniSearch = new MiniSearch({ fields: ['title', 'text'], searchOptions: { boost: { title: 2 }, fuzzy: 0.2 } }) miniSearch.addAll(documents) // It will now by default perform fuzzy search and boost "title": miniSearch.search('zen and motorcycles') ``` -------------------------------- ### Import MiniSearch in JavaScript Source: https://lucaong.github.io/minisearch/index.html Import MiniSearch into your project using either ES6 import syntax or CommonJS require. ```javascript // If you are using import: import MiniSearch from 'minisearch' // If you are using require: const MiniSearch = require('minisearch') Copy ``` -------------------------------- ### Serialize and Deserialize MiniSearch Index Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Demonstrates how to serialize a MiniSearch index to JSON using JSON.stringify and deserialize it back into a MiniSearch instance using MiniSearch.loadJSON. Ensure the same options are used for both operations. ```javascript let miniSearch = new MiniSearch({ fields: ['title', 'text'] }) miniSearch.addAll(documents) const json = JSON.stringify(miniSearch) miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] }) ``` -------------------------------- ### fetch Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Fetches the value of the given key. If the value does not exist, it creates a new value using the provided function, inserts it, and then returns it. ```APIDOC ## fetch * fetch(key, initial): T * Fetches the value of the given key. If the value does not exist, calls the given function to create a new value, which is inserted at the given key and subsequently returned. ### Example: ``` const map = searchableMap.fetch('somekey', () => new Map()) map.set('foo', 'bar') ``` #### Parameters * key: string The key to update * initial: (() => T) A function that creates a new value if the key does not exist * * (): T * #### Returns T #### Returns T The existing or new value at the given key ``` -------------------------------- ### Methods Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Methods available on the MiniSearch class for managing and querying the search index. ```APIDOC ## add * add(document): void * Adds a document to the index #### Parameters * document: T The document to be indexed #### Returns void ## addAll * addAll(documents): void * Adds all the given documents to the index #### Parameters * documents: readonly T[] An array of documents to be indexed #### Returns void ## addAllAsync * addAllAsync(documents, options?): Promise * Adds all the given documents to the index asynchronously. Returns a promise that resolves (to `undefined`) when the indexing is done. This method is useful when index many documents, to avoid blocking the main thread. The indexing is performed asynchronously and in chunks. #### Parameters * documents: readonly T[] An array of documents to be indexed * options: { chunkSize?: number; } = {} Configuration options * ##### `Optional` chunkSize?: number #### Returns Promise A promise resolving to `undefined` when the indexing is done ## autoSuggest * autoSuggest(queryString, options?): Suggestion[] * Provide suggestions for the given search query The result is a list of suggested modified search queries, derived from the given search query, each with a relevance score, sorted by descending score. By default, it uses the same options used for search, except that by default it performs prefix search on the last term of the query, and combine terms with `'AND'` (requiring all query terms to match). Custom options can be passed as a second argument. Defaults can be changed upon calling the MiniSearch constructor, by passing a `autoSuggestOptions` option. ### Basic usage: ``` // Get suggestions for 'neuro': miniSearch.autoSuggest('neuro') // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ] ``` ### Multiple words: ``` // Get suggestions for 'zen ar': miniSearch.autoSuggest('zen ar') // => [ // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 }, // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 } // ] ``` ### Fuzzy suggestions: ``` // Correct spelling mistakes using fuzzy search: miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 }) // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ] ``` ### Filtering: ``` // Get suggestions for 'zen ar', but only within the 'fiction' category // (assuming that 'category' is a stored field): miniSearch.autoSuggest('zen ar', { filter: (result) => result.category === 'fiction' }) // => [ // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 }, // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 } // ] ``` #### Parameters * queryString: string Query string to be expanded into suggestions * options: SearchOptions = {} Search options. The supported options and default values are the same as for the MiniSearch#search method, except that by default prefix search is performed on the last term in the query, and terms are combined with `'AND'`. #### Returns Suggestion[] A sorted array of suggestions sorted by relevance score. ``` -------------------------------- ### Static from Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Creates a new SearchableMap instance from an iterable of key-value entries. ```APIDOC ## `Static` from ### Description Creates a SearchableMap from an `Iterable` of entries. ### Type Parameters - **T** = any ### Parameters - **entries** (Iterable, any, any> | Entry[]) - Required - Entries to be inserted in the SearchableMap. ### Returns SearchableMap - A new SearchableMap with the given entries. ``` -------------------------------- ### Include MiniSearch from CDN Source: https://lucaong.github.io/minisearch/index.html Include MiniSearch in your HTML using a script tag to access it as a global variable. ```html Copy ``` -------------------------------- ### Create a SearchableMap View with a Prefix Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Use `atPrefix` to create a new SearchableMap that only contains entries sharing a specific prefix. This is useful for creating filtered views of the map. ```javascript let map = new SearchableMap() map.set("unicorn", 1) map.set("universe", 2) map.set("university", 3) map.set("unique", 4) map.set("hello", 5) let uni = map.atPrefix("uni") uni.get("unique") // => 4 uni.get("unicorn") // => 1 uni.get("hello") // => undefined let univer = map.atPrefix("univer") univer.get("unique") // => undefined univer.get("universe") // => 2 univer.get("university") // => 3 ``` -------------------------------- ### Advanced Prefix and Fuzzy Search in MiniSearch Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Conditionally apply prefix and fuzzy search based on term length. This provides fine-grained control over search behavior. ```javascript miniSearch.search('ismael mob', { prefix: term => term.length > 3, fuzzy: term => term.length > 3 ? 0.2 : null }) ``` -------------------------------- ### Combining Search Strategies in MiniSearch Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Combine multiple search strategies like prefix and fuzzy search in a single query. This allows for more nuanced search results. ```javascript miniSearch.search('ismael mob', { prefix: true, fuzzy: 0.2 }) ``` -------------------------------- ### Combine Search Terms with AND in MiniSearch Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Use the AND combinator to ensure all specified search terms are present in the matching documents. ```javascript miniSearch.search('motorcycle art', { combineWith: 'AND' }) ``` -------------------------------- ### vacuum(options?) Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Triggers a manual vacuuming of the index to clean up references to discarded documents. ```APIDOC ## vacuum(options?) ### Description Triggers a manual vacuuming, cleaning up references to discarded documents from the inverted index. Vacuuming is only useful for applications that use the MiniSearch#discard or MiniSearch#replace methods. By default, vacuuming is performed automatically when needed (controlled by the `autoVacuum` field in Options), so there is usually no need to call this method, unless one wants to make sure to perform vacuuming at a specific moment. Vacuuming traverses all terms in the inverted index in batches, and cleans up references to discarded documents from the posting list, allowing memory to be released. The method takes an optional object as argument with the following keys: `batchSize`: the size of each batch (1000 by default), `batchWait`: the number of milliseconds to wait between batches (10 by default). On large indexes, vacuuming could have a non-negligible cost: batching avoids blocking the thread for long, diluting this cost so that it is not negatively affecting the application. Nonetheless, this method should only be called when necessary, and relying on automatic vacuuming is usually better. ### Parameters #### Path Parameters - **options** (VacuumOptions) - Optional - Configuration options for the batch size and delay. See VacuumOptions. ### Returns Promise: A promise that resolves (to undefined) when the clean up is completed. If vacuuming is already ongoing at the time this method is called, a new one is enqueued immediately after the ongoing one, and a corresponding promise is returned. However, no more than one vacuuming is enqueued on top of the ongoing one, even if this method is called more times (enqueuing multiple ones would be useless). ``` -------------------------------- ### forEach Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Executes a provided function once for each key-value pair in the map. ```APIDOC ## forEach * forEach(fn): void * #### Parameters * fn: ((key, value, map) => void) Iteration function * * (key, value, map): void * #### Parameters * key: string * value: T * map: SearchableMap #### Returns void #### Returns void #### See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach ``` -------------------------------- ### Auto-Suggest Multiple Words Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Provide suggestions for a multi-word query. Results show combined suggestions with relevance scores. ```javascript miniSearch.autoSuggest('zen ar') ``` -------------------------------- ### Static getDefault(optionName) Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Returns the default value of a MiniSearch option. ```APIDOC ## Static getDefault(optionName) ### Description Returns the default value of an option. It will throw an error if no option with the given name exists. ### Parameters #### Path Parameters - **optionName** (string) - Required - Name of the option ### Returns any: The default value of the given option ### Usage: ```javascript // Get default tokenizer MiniSearch.getDefault('tokenize') // Get default term processor MiniSearch.getDefault('processTerm') // Unknown options will throw an error MiniSearch.getDefault('notExisting') // => throws 'MiniSearch: unknown option "notExisting"' ``` ``` -------------------------------- ### search(query, options) Source: https://lucaong.github.io/minisearch/index.html Searches the index for documents matching the given query. Options can be provided to customize the search behavior. ```APIDOC ## search(query, options) ### Description Searches the MiniSearch index for documents matching the provided query string. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **query** (string) - Required - The search query string. - **options** (object) - Optional - Options to customize the search behavior. - **boost** (object) - Optional - Field boosting configuration. - **fuzzy** (number | boolean) - Optional - Controls fuzzy matching. - **prefix** (boolean) - Optional - Enables prefix search. - **enrich** (boolean) - Optional - If true, returns `match` data for each result. ### Request Example ```javascript let results = miniSearch.search('search terms', { fuzzy: true, prefix: true }); ``` ### Response #### Success Response (200) Returns an array of search results. Each result object contains the stored fields and optionally a `score` and `match` object. #### Response Example ```json [ { "id": 2, "title": "Zen and the Art of Motorcycle Maintenance", "category": "fiction", "score": 2.77258, "match": { ... } } ] ``` ``` -------------------------------- ### size Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Returns the number of key-value entries in the map. ```APIDOC ## size * get size(): number * #### Returns number #### See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size ``` -------------------------------- ### Fuzzy Search with SearchableMap Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Use fuzzyGet to find entries with keys similar to the search key within a specified edit distance. The result includes the matching key, its value, and the calculated edit distance. ```javascript let map = new SearchableMap() map.set('hello', 'world') map.set('hell', 'yeah') map.set('ciao', 'mondo') // Get all entries that match the key 'hallo' with a maximum edit distance of 2 map.fuzzyGet('hallo', 2) // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] } // In the example, the "hello" key has value "world" and edit distance of 1 // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2 // (change "e" to "a", delete "o") ``` -------------------------------- ### Static fromObject Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Creates a new SearchableMap instance from the properties of a JavaScript object. ```APIDOC ## `Static` fromObject ### Description Creates a SearchableMap from the iterable properties of a JavaScript object. ### Type Parameters - **T** = any ### Parameters - **object** ({ [key: string]: T }) - Required - Object of entries for the SearchableMap. ### Returns SearchableMap - A new SearchableMap with the given entries. ``` -------------------------------- ### addAll(documents) Source: https://lucaong.github.io/minisearch/index.html Adds multiple documents to the search index. This is an efficient way to index a collection of documents at once. ```APIDOC ## addAll(documents) ### Description Adds an array of documents to the MiniSearch index. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **documents** (array of objects) - Required - An array of documents to be added to the index. Each document should have a unique `id` field. ### Request Example ```javascript const documents = [ { id: 1, title: 'Document 1', text: 'Content of document 1' }, { id: 2, title: 'Document 2', text: 'Content of document 2' } ]; miniSearch.addAll(documents); ``` ### Response #### Success Response (200) This method does not return a value, but updates the index in place. #### Response Example None ``` -------------------------------- ### replace Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Replaces an existing document with a new version. This is functionally equivalent to discarding the old version and adding the new one. ```APIDOC ## replace ### Description It replaces an existing document with the given updated version. It works by discarding the current version and adding the updated one, so it is functionally equivalent to calling `MiniSearch#discard` followed by `MiniSearch#add`. The ID of the updated document should be the same as the original one. ### Method `replace(updatedDocument: T): void` ### Parameters #### Path Parameters - **updatedDocument** (T) - Required - The updated document to replace the old version with. ### Returns void ``` -------------------------------- ### atPrefix Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Creates and returns a mutable view of this SearchableMap, containing only entries that share the given prefix. ```APIDOC ## atPrefix * atPrefix(prefix): SearchableMap * Creates and returns a mutable view of this SearchableMap, containing only entries that share the given prefix. ### Usage: ``` let map = new SearchableMap() map.set("unicorn", 1) map.set("universe", 2) map.set("university", 3) map.set("unique", 4) map.set("hello", 5) let uni = map.atPrefix("uni") uni.get("unique") // => 4 uni.get("unicorn") // => 1 uni.get("hello") // => undefined let univer = map.atPrefix("univer") univer.get("unique") // => undefined univer.get("universe") // => 2 univer.get("university") // => 3 ``` #### Parameters * prefix: string The prefix #### Returns SearchableMap A SearchableMap representing a mutable view of the original Map at the given prefix ``` -------------------------------- ### Basic Search in MiniSearch Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Perform a basic search for terms. Terms are joined with OR by default and must match exactly. ```javascript miniSearch.search('zen art motorcycle') // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ] ``` -------------------------------- ### Advanced Query Expression Tree (AND_NOT/OR) Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Build complex queries using a query expression tree, combining terms with AND_NOT and OR logic. ```javascript miniSearch.search({ combineWith: 'AND_NOT', queries: [ { combineWith: 'OR', queries: ['apple', 'pear'] }, 'juice', 'tree' ] }) ``` -------------------------------- ### Wildcard Search in MiniSearch Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Perform a wildcard search to retrieve all documents. This is achieved by passing `MiniSearch.wildcard` as the query. ```javascript miniSearch.search(MiniSearch.wildcard) ``` -------------------------------- ### Properties Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Properties of the MiniSearch class that provide information about the search index. ```APIDOC ## dirtFactor * get dirtFactor(): number * A number between 0 and 1 giving an indication about the proportion of documents that are discarded, and can therefore be cleaned up by vacuuming. A value close to 0 means that the index is relatively clean, while a higher value means that the index is relatively dirty, and vacuuming could release memory. #### Returns number ## documentCount * get documentCount(): number * Total number of documents available to search #### Returns number ## isVacuuming * get isVacuuming(): boolean * Is `true` if a vacuuming operation is ongoing, `false` otherwise #### Returns boolean ## termCount * get termCount(): number * Number of terms in the index #### Returns number ``` -------------------------------- ### toJSON() Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Serializes the MiniSearch index to a plain object. This method is typically called internally by JSON.stringify(). ```APIDOC ## toJSON() ### Description Allows serialization of the index to JSON, to possibly store it and later deserialize it with MiniSearch.loadJSON. Normally one does not directly call this method, but rather call the standard JavaScript `JSON.stringify()` passing the MiniSearch instance, and JavaScript will internally call this method. Upon deserialization, one must pass to MiniSearch.loadJSON the same options used to create the original instance that was serialized. ### Returns AsPlainObject: A plain-object serializable representation of the search index. ``` -------------------------------- ### Asynchronously Deserialize MiniSearch Index Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Provides an asynchronous alternative to MiniSearch.loadJSON for deserializing a JSON-serialized index. This method loads the index in batches to avoid blocking the main thread, making it suitable for very large indexes. ```javascript miniSearch = await MiniSearch.loadJSONAsync(json, { fields: ['title', 'text'] }) ``` -------------------------------- ### has Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Checks if a key exists in the map. Returns true if the key is present, false otherwise. ```APIDOC ## has ### Description Checks if a key exists in the map. ### Parameters #### Path Parameters - **key** (string) - Required - Key. ### Returns boolean - True if the key is in the map, false otherwise. ### See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has ``` -------------------------------- ### fuzzyGet Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Returns a Map of entries whose keys are within a specified edit distance from the search key. The returned Map's keys are the matching keys, and values are `[original_value, edit_distance]` pairs. ```APIDOC ## fuzzyGet * fuzzyGet(key, maxEditDistance): FuzzyResults * Returns a Map of all the entries that have a key within the given edit distance from the search key. The keys of the returned Map are the matching keys, while the values are two-element arrays where the first element is the value associated to the key, and the second is the edit distance of the key to the search key. ``` -------------------------------- ### MiniSearch Custom Tokenization Source: https://lucaong.github.io/minisearch/index.html Allows changing the default tokenization logic by providing a custom tokenizer function. The search-time tokenizer can also be specified separately. ```javascript // Tokenize splitting by hyphen let miniSearch = new MiniSearch({ fields: ['title', 'text'], tokenize: (string, _fieldName) => string.split('-') }) ``` ```javascript // Tokenize splitting by hyphen let miniSearch = new MiniSearch({ fields: ['title', 'text'], tokenize: (string) => string.split('-'), // indexing tokenizer searchOptions: { tokenize: (string) => string.split(/[\\s-]+/) // search query tokenizer } }) ``` -------------------------------- ### entries Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Returns an iterator that yields `[key, value]` pairs for all entries in the map. ```APIDOC ## entries * entries(): TreeIterator * #### Returns TreeIterator An iterator iterating through `[key, value]` entries. #### See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries ``` -------------------------------- ### Separate Term Processing for Indexing and Searching Source: https://lucaong.github.io/minisearch/index.html Configure Minisearch to use different `processTerm` functions for indexing and searching. The `searchOptions.processTerm` allows for distinct query processing, such as only downcasing search terms without discarding stop words. ```javascript let miniSearch = new MiniSearch({ fields: ['title', 'text'], processTerm: (term) => stopWords.has(term) ? null : term.toLowerCase(), // index term processing searchOptions: { processTerm: (term) => term.toLowerCase() // search query processing } }) ``` -------------------------------- ### fuzzyGet Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Retrieves all entries that approximately match the given key within a specified maximum edit distance. This is useful for implementing features like type-ahead search or correcting minor typos. ```APIDOC ## fuzzyGet ### Description Retrieves all entries that approximately match the given key within a specified maximum edit distance. ### Parameters #### Query Parameters - **key** (string) - Required - The search key. - **maxEditDistance** (number) - Required - The maximum edit distance (Levenshtein). ### Returns FuzzyResults - A Map of the matching keys to their value and edit distance. ### Example ```javascript let map = new SearchableMap() map.set('hello', 'world') map.set('hell', 'yeah') map.set('ciao', 'mondo') // Get all entries that match the key 'hallo' with a maximum edit distance of 2 map.fuzzyGet('hallo', 2) // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] } ``` ``` -------------------------------- ### Wildcard Search with Filtering in MiniSearch Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Combine a wildcard search with filtering options to retrieve all documents that match specific criteria. ```javascript miniSearch.search(MiniSearch.wildcard, { filter: (result) => result.category === 'fiction' }) ``` -------------------------------- ### discardAll Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Discards multiple documents by their IDs. It's an optimization over calling `discard` repeatedly, triggering at most one automatic vacuuming. ```APIDOC ## discardAll ### Description Discards the documents with the given IDs, so they won't appear in search results. It is equivalent to calling `MiniSearch#discard` for all the given IDs, but with the optimization of triggering at most one automatic vacuuming at the end. ### Method `discardAll(ids: readonly any[]): void` ### Parameters #### Path Parameters - **ids** (readonly any[]) - Required - An array of document IDs to be discarded. ### Returns void ``` -------------------------------- ### keys Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Returns an iterable iterator for the keys in the map. ```APIDOC ## keys ### Description Returns an iterable iterator for the keys in the map. ### Returns TreeIterator - An `Iterable` iterating through keys. ### See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys ``` -------------------------------- ### QueryCombination Type Declaration Source: https://lucaong.github.io/minisearch/types/MiniSearch.QueryCombination.html This snippet shows the type declaration for QueryCombination, highlighting its composition with SearchOptions and its specific 'queries' property. ```APIDOC ## Type alias QueryCombination QueryCombination: SearchOptions & { queries: Query[]; } ### Type declaration * ##### queries: Query[] ``` -------------------------------- ### set Source: https://lucaong.github.io/minisearch/classes/SearchableMap_SearchableMap.SearchableMap.html Associates a value with a key in the map. If the key already exists, the value is updated. Returns the SearchableMap instance for chaining. ```APIDOC ## set ### Description Associates a value with a key in the map. Returns the SearchableMap instance for chaining. ### Parameters #### Path Parameters - **key** (string) - Required - Key to set. - **value** (T) - Required - Value to associate to the key. ### Returns SearchableMap - The SearchableMap itself, to allow chaining. ### See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set ``` -------------------------------- ### MiniSearch Constructor with Custom ID Field Source: https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html Configure MiniSearch to use a custom field for document identification instead of the default 'id'. ```javascript // Your documents are assumed to include a unique 'id' field, but if you want // to use a different field for document identification, you can set the // 'idField' option: const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] }) ```