FlexSearch

Next-Generation full text search library for Browser and Node.js

README



FlexSearch.js: Next-Generation full text search library for Browser and Node.js

Web's fastest and most memory-flexible full-text search library with zero dependencies.

Basic Start  •  API Reference  •  Document Indexes  •  Using Worker  •  Changelog

FlexSearch v0.7.0


The new version is finally available. FlexSearch v0.7.0 is a modern re-implementation and was newly developed from the ground up. The result is an improvement in every single aspect and covers tons of enhancements and improvements which was collected over the last 3 years.

This new version has a good compatibility with the old generation, but it might require some migrations steps in your code.

Read the documentation of new features and changes:
https://github.com/nextapps-de/flexsearch/blob/master/doc/0.7.0.md

Read the documentation of new language encoding features:
https://github.com/nextapps-de/flexsearch/blob/master/doc/0.7.0-lang.md


When it comes to raw search speed FlexSearch outperforms every single searching library out there and also provides flexible search capabilities like multi-field search, phonetic transformations or partial matching.

Depending on the used options it also provides the most memory-efficient index. FlexSearch introduce a new scoring algorithm called "contextual index" based on a pre-scored lexical dictionary architecture which actually performs queries up to 1,000,000 times faster compared to other libraries.
FlexSearch also provides you a non-blocking asynchronous processing model as well as web workers to perform any updates or queries on the index in parallel through dedicated balanced threads.

<!--
FlexSearch Server is available here:
https://github.com/nextapps-de/flexsearch-server.
-->

Supported Platforms:
- Browser
- Node.js

<!--
Demos:
- Auto-Complete
-->

Library Comparison "Gulliver's Travels":
- Performance Benchmark- Scoring Benchmark- Memory Consumption

Plugins (extern projects):
- https://github.com/angeloashmore/react-use-flexsearch
- https://www.gatsbyjs.org/packages/gatsby-plugin-flexsearch/

Get Latest Stable Build (Recommended)


Build File CDN
flexsearch.bundle.js Download https://rawcdn.githack.com/nextapps-de/flexsearch/0.7.31/dist/flexsearch.bundle.js
flexsearch.light.js Download https://rawcdn.githack.com/nextapps-de/flexsearch/0.7.31/dist/flexsearch.light.js
flexsearch.compact.js Download https://rawcdn.githack.com/nextapps-de/flexsearch/0.7.31/dist/flexsearch.compact.js
flexsearch.es5.js * Download https://rawcdn.githack.com/nextapps-de/flexsearch/0.7.31/dist/flexsearch.es5.js
ES6 Modules Download The /dist/module/ folder of this Github repository
* The bundle "flexsearch.es5.js" includes polyfills for EcmaScript 5 Support.

Get Latest (NPM)


  1. ```cmd
  2. npm install flexsearch
  3. ```

Get Latest Nightly (Do not use for production!)


Just exchange the version number from the URLs above with "master", e.g.: "/flexsearch/__0.7.31__/dist/" into "/flexsearch/__master__/dist".

Compare Web-Bundles


The Node.js package includes all features from flexsearch.bundle.js.


Feature flexsearch.bundle.js flexsearch.compact.js flexsearch.light.js
Presets -
Async Search -
Workers (Web + Node.js) - -
Contextual Indexes
Index Documents (Field-Search) -
Document Store -
Partial Matching
            Relevance Scoring
Auto-Balanced Cache by Popularity - -
Tags - -
Suggestions -
Phonetic Matching -
Customizable Charset/Language (Matcher, Encoder, Tokenizer, Stemmer, Filter, Split, RTL)
Export / Import Indexes - -
File Size (gzip) 6.8 kb 5.3 kb 2.9 kb

Performance Benchmark (Ranking)


Run Comparison: Performance Benchmark "Gulliver's Travels"

Operation per seconds, higher is better, except the test "Memory" on which lower is better.

Rank Library Memory Query (Single Term) Query (Multi Term) Query (Long) Query (Dupes) Query (Not Found)
1 FlexSearch 17 7084129 1586856 511585 2017142 3202006
2 JSii 27 6564 158149 61290 95098 534109
3 Wade 424 20471 78780 16693 225824 213754
4 JS Search 193 8221 64034 10377 95830 167605
5 Elasticlunr.js 646 5412 7573 2865 23786 13982
6 BulkSearch 1021 3069 3141 3333 3265 21825569
7 MiniSearch 24348 4406 10945 72 39989 17624
8 bm25 15719 1429 789 366 884 1823
9 Lunr.js 2219 255 271 272 266 267
10 FuzzySearch 157373 53 38 15 32 43
11 Fuse 7641904 6 2 1 2 3

Contextual Search


__Note:__ This feature is disabled by default because of its extended memory usage. Read <a href="#contextual_enable">here</a> get more information about and how to enable.


FlexSearch introduce a new scoring mechanism called __Contextual Search__ which was invented by Thomas Wilkerling, the author of this library. A Contextual Search incredibly boost up queries to a complete new level but also requires some additional memory (depending on ___depth___).
The basic idea of this concept is to limit relevance by its context instead of calculating relevance through the whole distance of its corresponding document.
This way contextual search also improves the results of relevance-based queries on a large amount of text data.

Load Library


There are 3 types of indexes:

1. Index is a flat high performance index which stores id-content-pairs.
2. Worker / WorkerIndex is also a flat index which stores id-content-pairs but runs in background as a dedicated worker thread.
3. Document is multi-field index which can store complex JSON documents (could also exist of worker indexes).

The most of you probably need just one of them according to your scenario.

ES6 Modules (Browser):


  1. ``` js
  2. import Index from "./index.js";
  3. import Document from "./document.js";
  4. import WorkerIndex from "./worker/index.js";

  5. const index = new Index(options);
  6. const document = new Document(options);
  7. const worker = new WorkerIndex(options);
  8. ```

Bundle (Browser)


  1. ``` html
  2. <html>
  3. <head>
  4.     <script src="js/flexsearch.bundle.js"></script>
  5. </head>
  6. ...
  7. ```

Or via CDN:
  1. ``` html
  2. <script src="https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.7.31/dist/flexsearch.bundle.js"></script>
  3. ```

AMD:

  1. ``` js
  2. var FlexSearch = require("./flexsearch.js");
  3. ```

Load one of the builds from the folder dist within your html as a script and use as follows:

  1. ``` js
  2. var index = new FlexSearch.Index(options);
  3. var document = new FlexSearch.Document(options);
  4. var worker = new FlexSearch.Worker(options);
  5. ```

Node.js


  1. ```npm
  2. npm install flexsearch
  3. ```

In your code include as follows:

  1. ``` js
  2. const { Index, Document, Worker } = require("flexsearch");

  3. const index = new Index(options);
  4. const document = new Document(options);
  5. const worker = new Worker(options);
  6. ```

Basic Usage and Variants


  1. ``` js
  2. index.add(id, text);
  3. index.search(text);
  4. index.search(text, limit);
  5. index.search(text, options);
  6. index.search(text, limit, options);
  7. index.search(options);
  8. ```

  1. ``` js
  2. document.add(doc);
  3. document.add(id, doc);
  4. document.search(text);
  5. document.search(text, limit);
  6. document.search(text, options);
  7. document.search(text, limit, options);
  8. document.search(options);
  9. ```

  1. ``` js
  2. worker.add(id, text);
  3. worker.search(text);
  4. worker.search(text, limit);
  5. worker.search(text, options);
  6. worker.search(text, limit, options);
  7. worker.search(text, limit, options, callback);
  8. worker.search(options);
  9. ```

The worker inherits from type Index and does not inherit from type Document. Therefore, a WorkerIndex basically works like a standard FlexSearch Index. Worker-Support in documents needs to be enabled by just passing the appropriate option during creation { worker: true }.

Every method called on a Worker index is treated as async. You will get back a Promise or you can provide a callback function as the last parameter alternatively.


API Overview


Global methods:

- FlexSearch.__registerCharset__(name, charset)- FlexSearch.__registerLanguage__(name, language)

Index methods:

- Index.__add__(id, string) *- Index.__append__(id, string) *- Index.__update__(id, string) *- Index.__remove__(id) *- Index.__search__(string, \, \) *- Index.__search__(options) *- _async_ Index.__export__(handler)- _async_ Index.__import__(key, data)

WorkerIndex methods:

- _async_ Index.__add__(id, string)- _async_ Index.__append__(id, string)- _async_ Index.__update__(id, string)- _async_ Index.__remove__(id)- _async_ Index.__search__(string, \, \)- _async_ Index.__search__(options)- _async_ ~~Index.__export__(handler)~~ (WIP)- _async_ ~~Index.__import__(key, data)~~ (WIP)

Document methods:

- Document.__add__(\, document) *- Document.__append__(\, document) *- Document.__update__(\, document) *- Document.__remove__(id || document) *- Document.__search__(string, \, \) *- Document.__search__(options) *- _async_ Document.__export__(handler)- _async_ Document.__import__(key, data)* For each of those methods there exist an asynchronous equivalent:

Async Version:

- _async_ .__addAsync__( ... , \)- _async_ .__appendAsync__( ... , \)- _async_ .__updateAsync__( ... , \)- _async_ .__removeAsync__( ... , \)- _async_ .__searchAsync__( ... , \)

Async methods will return a Promise, alternatively you can pass a callback function as the last parameter.

Methods export and also import are always async as well as every method you call on a Worker-based Index.

Options


FlexSearch is highly customizable. Make use of the right options can really improve your results as well as memory economy and query time.

Index Options


Option Values Description Default
preset "memory"
"performance"
"match"
"score"
            "default"
The configuration profile as a shortcut or as a base for your custom settings.
"default"
tokenize "strict"
"forward"
"reverse"
            "full"
The indexing mode (tokenizer).

Choose one of the built-ins or pass a custom tokenizer function.
"strict"
cache Boolean
            Number
Enable/Disable and/or set capacity of cached entries.

When passing a number as a limit the cache automatically balance stored entries related to their popularity.

Note: When just using "true" the cache has no limits and growth unbounded.
false
resolution
            Number
Sets the scoring resolution (default: 9). 9
context Boolean
            Context Options
Enable/Disable contextual indexing. When passing "true" as value it will take the default values for the context. false
optimize
            Boolean
When enabled it uses a memory-optimized stack flow for the index. true
boost
            function(arr, str, int) => float
A custom boost function used when indexing contents to the index. The function has this signature: Function(words[], term, index) => Float. It has 3 parameters where you get an array of all words, the current term and the current index where the term is placed in the word array. You can apply your own calculation e.g. the occurrences of a term and return this factor (<1 means relevance is lowered, >1 means relevance is increased).

Note: this feature is currently limited by using the tokenizer "strict" only.
null
            Language-specific Options and Encoding:
charset

Charset Payload
            String (key)
            Provide a custom charset payload or pass one of the keys of built-in charsets.
"latin"
language

Language Payload
            String (key)
            Provide a custom language payload or pass in language shorthand flag (ISO-3166) of built-in languages.
null
encode






false
"default"
"simple"
"balance"
"advanced"
"extra"
            function(str) => [words]
The encoding type.

Choose one of the built-ins or pass a custom encoding function.
"default"
stemmer


false
String
            Function
false
filter


false
String
            Function
false
matcher


false
String
            Function
false
            Additional Options for Document Indexes:
worker
            Boolean
Enable/Disable and set count of running worker threads. false
document
Document Descriptor
            Includes definitions for the document index and storage.

Context Options


Option Values Description Default
resolution
            Number
Sets the scoring resolution for the context (default: 1). 1
depth

false
            Number
Enable/Disable contextual indexing and also sets contextual distance of relevance. Depth is the maximum number of words/tokens away a term to be considered as relevant. 1
bidirectional
            Boolean
Sets the scoring resolution (default: 9). true

Document Options


Option Values Description Default
id
String "id""
tag

false
String
"tag"
index


String
Array<String>
Array<Object>
store


Boolean
String
Array<String>
false

Charset Options


Option Values Description Default
split

false
RegExp
            String
The rule to split words when using non-custom tokenizer (built-ins e.g. "forward"). Use a string/char or use a regular expression (default: /\W+/).
/[\W_]+/
rtl
            Boolean
Enables Right-To-Left encoding. false
encode
            function(str) => [words]
The custom encoding function. /lang/latin/default.js

Language Options


Option Values Description
stemmer


false
String
            Function
Disable or pass in language shorthand flag (ISO-3166) or a custom object.
filter


false
String
            Function
Disable or pass in language shorthand flag (ISO-3166) or a custom array.
matcher


false
String
            Function
Disable or pass in language shorthand flag (ISO-3166) or a custom array.

Search Options


Option Values Description Default
limit number Sets the limit of results. 100
offset number Apply offset (skip items). 0
suggest Boolean Enables suggestions in results. false

Document Search Options


Additionally, to the Index search options above.

Option Values Description Default
index String
Array<String>
Array<Object>
Sets the document fields which should be searched. When no field is set, all fields will be searched. Custom options per field are also supported.
tag String
Array<String>
Sets the document fields which should be searched. When no field is set, all fields will be searched. Custom options per field are also supported. false
enrich Boolean Enrich IDs from the results with the corresponding documents. false
bool "and"
"or"
Sets the used logical operator when searching through multiple fields or tags. "or"

Tokenizer (Prefix Search)


Tokenizer affects the required memory also as query time and flexibility of partial matches. Try to choose the most upper of these tokenizer which fits your needs:

Option Description Example Memory Factor (n = length of word)
"strict" index whole words foobar * 1
"forward" incrementally index words in forward direction foobar
foobar
* n
"reverse" incrementally index words in both directions foobar
foobar
* 2n - 1
"full" index every possible combination foobar
foobar
* n * (n - 1)

Encoders


Encoding affects the required memory also as query time and phonetic matches. Try to choose the most upper of these encoders which fits your needs, or pass in a custom encoder:

Option Description False-Positives Compression
false Turn off encoding no 0%
"default" Case in-sensitive encoding no 0%
"simple" Case in-sensitive encoding
Charset normalizations
no ~ 3%
"balance" Case in-sensitive encoding
Charset normalizations
Literal transformations
no ~ 30%
"advanced" Case in-sensitive encoding
Charset normalizations
Literal transformations
Phonetic normalizations
no ~ 40%
"extra" Case in-sensitive encoding
Charset normalizations
Literal transformations
Phonetic normalizations
Soundex transformations
yes ~ 65%
function() Pass custom encoding via function(string):[words]

Usage


Create a new index


  1. ``` js
  2. var index = new Index();
  3. ```

Create a new index and choosing one of the presets:

  1. ``` js
  2. var index = new Index("performance");
  3. ```

Create a new index with custom options:

  1. ``` js
  2. var index = new Index({
  3.     charset: "latin:extra",
  4.     tokenize: "reverse",
  5.     resolution: 9
  6. });
  7. ```

Create a new index and extend a preset with custom options:

  1. ``` js
  2. var index = new FlexSearch({
  3.     preset: "memory",
  4.     tokenize: "forward",
  5.     resolution: 5
  6. });
  7. ```

See all available custom options.

Add text item to an index


Every content which should be added to the index needs an ID. When your content has no ID, then you need to create one by passing an index or count or something else as an ID (a value from type number is highly recommended). Those IDs are unique references to a given content. This is important when you update or adding over content through existing IDs. When referencing is not a concern, you can simply use something simple like count++.

Index.__add(id, string)__


  1. ``` js
  2. index.add(0, "John Doe");
  3. ```

Search items


Index.__search(string | options, \<limit\>, \<options\>)__


  1. ``` js
  2. index.search("John");
  3. ```

Limit the result:

  1. ``` js
  2. index.search("John", 10);
  3. ```

Check existence of already indexed IDs


You can check if an ID was already indexed by:

  1. ``` js
  2. if(index.contain(1)){
  3.     console.log("ID is already in index");
  4. }
  5. ```

Async


You can call each method in its async version, e.g. index.addAsync or index.searchAsync.

You can assign callbacks to each async function:

  1. ``` js
  2. index.addAsync(id, content, function(){
  3.     console.log("Task Done");
  4. });

  5. index.searchAsync(query, function(result){
  6.     console.log("Results: ", result);
  7. });
  8. ```

Or do not pass a callback function and getting back a Promise instead:

  1. ``` js
  2. index.addAsync(id, content).then(function(){
  3.     console.log("Task Done");
  4. });

  5. index.searchAsync(query).then(function(result){
  6.     console.log("Results: ", result);
  7. });
  8. ```

Or use async and await:

  1. ``` js
  2. async function add(){
  3.     await index.addAsync(id, content);
  4.     console.log("Task Done");
  5. }

  6. async function search(){
  7.     const results = await index.searchAsync(query);
  8.     console.log("Results: ", result);
  9. }
  10. ```

Append Contents


You can append contents to an existing index like:

  1. ``` js
  2. index.append(id, content);
  3. ```

This will not overwrite the old indexed contents as it will do when perform index.update(id, content). Keep in mind that index.add(id, content) will also perform "update" under the hood when the id was already being indexed.

Appended contents will have their own context and also their own full resolution. Therefore, the relevance isn't being stacked but gets its own context.

Let us take this example:

  1. ``` js
  2. index.add(0, "some index");
  3. index.append(0, "some appended content");

  4. index.add(1, "some text");
  5. index.append(1, "index appended content");
  6. ```

When you query index.search("index") then you will get index id 1 as the first entry in the result, because the context starts from zero for the appended data (isn't stacked to the old context) and here "index" is the first term.

If you didn't want this behavior than just use the standard index.add(id, content) and provide the full length of content.

Update item from an index


Index.__update(id, string)__


  1. ``` js
  2. index.update(0, "Max Miller");
  3. ```

Remove item from an index


Index.__remove(id)__


  1. ``` js
  2. index.remove(0);
  3. ```

Add custom tokenizer


A tokenizer split words/terms into components or partials.


Define a private custom tokenizer during creation/initialization:
  1. ``` js
  2. var index = new FlexSearch({

  3.     tokenize: function(str){

  4.         return str.split(/\s-\//g);
  5.     }
  6. });
  7. ```

The tokenizer function gets a string as a parameter and has to return an array of strings representing a word or term. In some languages every char is a term and also not separated via whitespaces.


Add language-specific stemmer and/or filter


__Stemmer:__ several linguistic mutations of the same word (e.g. "run" and "running")


__Filter:__ a blacklist of words to be filtered out from indexing at all (e.g. "and", "to" or "be")


Assign a private custom stemmer or filter during creation/initialization:
  1. ``` js
  2. var index = new FlexSearch({

  3.     stemmer: {

  4.         // object {key: replacement}
  5.         "ational": "ate",
  6.         "tional": "tion",
  7.         "enci": "ence",
  8.         "ing": ""
  9.     },
  10.     filter: [

  11.         // array blacklist
  12.         "in",
  13.         "into",
  14.         "is",
  15.         "isn't",
  16.         "it",
  17.         "it's"
  18.     ]
  19. });
  20. ```

Using a custom filter, e.g.:
  1. ``` js
  2. var index = new FlexSearch({

  3.     filter: function(value){

  4.         // just add values with length > 1 to the index

  5.         return value.length > 1;
  6.     }
  7. });
  8. ```

Or assign stemmer/filters globally to a language:

Stemmer are passed as a object (key-value-pair), filter as an array.


  1. ``` js
  2. FlexSearch.registerLanguage("us", {

  3.     stemmer: { /* ... */ },
  4.     filter:  [ /* ... */ ]
  5. });
  6. ```

Or use some pre-defined stemmer or filter of your preferred languages:
  1. ``` html
  2. <html>
  3. <head>
  4.     <script src="js/flexsearch.bundle.js"></script>
  5.     <script src="js/lang/en.min.js"></script>
  6.     <script src="js/lang/de.min.js"></script>
  7. </head>
  8. ...
  9. ```

Now you can assign built-in stemmer during creation/initialization:
  1. ``` js
  2. var index_en = new FlexSearch.Index({
  3.     language: "en"
  4. });

  5. var index_de = new FlexSearch.Index({
  6.     language: "de"
  7. });
  8. ```

In Node.js all built-in language packs files are available:

  1. ``` js
  2. const { Index } = require("flexsearch");

  3. var index_en = new Index({
  4.     language: "en"
  5. });
  6. ```

Right-To-Left Support


Set the tokenizer at least to "reverse" or "full" when using RTL.


Just set the field "rtl" to _true_ and use a compatible tokenizer:

  1. ``` js
  2. var index = new Index({
  3.     encode: str => str.toLowerCase().split(/[^a-z]+/),
  4.     tokenize: "reverse",
  5.     rtl: true
  6. });
  7. ```

CJK Word Break (Chinese, Japanese, Korean)


Set a custom tokenizer which fits your needs, e.g.:

  1. ``` js
  2. var index = FlexSearch.create({
  3.     encode: str => str.replace(/[\x00-\x7F]/g, "").split("")
  4. });
  5. ```

You can also pass a custom encoder function to apply some linguistic transformations.

  1. ``` js
  2. index.add(0, "一个单词");
  3. ```

  1. ``` js
  2. var results = index.search("单词");
  3. ```

Index Documents (Field-Search)


The Document Descriptor


Assuming our document has a data structure like this:

  1. ``` json
  2. {
  3.     "id": 0,
  4.     "content": "some text"
  5. }
  6. ```

Old syntax FlexSearch v0.6.3 (___not supported anymore!___):

  1. ``` js
  2. const index = new Document({
  3.     doc: {
  4.         id: "id",
  5.         field: ["content"]
  6.     }
  7. });
  8. ```

The document descriptor has slightly changed, there is no field branch anymore, instead just apply one level higher, so key becomes a main member of options.


For the new syntax the field "doc" was renamed to document and the field "field" was renamed to index:

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         id: "id",
  5.         index: ["content"]
  6.     }
  7. });

  8. index.add({
  9.     id: 0,
  10.     content: "some text"
  11. });
  12. ```

The field id describes where the ID or unique key lives inside your documents. The default key gets the value id by default when not passed, so you can shorten the example from above to:

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         index: ["content"]
  5.     }
  6. });
  7. ```

The member index has a list of fields which you want to be indexed from your documents. When just selecting one field, then you can pass a string. When also using default key id then this shortens to just:

  1. ``` js
  2. const index = new Document({ document: "content" });
  3. index.add({ id: 0, content: "some text" });
  4. ```

Assuming you have several fields, you can add multiple fields to the index:

  1. ``` js
  2. var docs = [{
  3.     id: 0,
  4.     title: "Title A",
  5.     content: "Body A"
  6. },{
  7.     id: 1,
  8.     title: "Title B",
  9.     content: "Body B"
  10. }];
  11. ```

  1. ``` js
  2. const index = new Document({
  3.     id: "id",
  4.     index: ["title", "content"]
  5. });
  6. ```

You can pass custom options for each field:

  1. ``` js
  2. const index = new Document({
  3.     id: "id",
  4.     index: [{
  5.         field: "title",
  6.         tokenize: "forward",
  7.         optimize: true,
  8.         resolution: 9
  9.     },{
  10.         field:  "content",
  11.         tokenize: "strict",
  12.         optimize: true,
  13.         resolution: 5,
  14.         minlength: 3,
  15.         context: {
  16.             depth: 1,
  17.             resolution: 3
  18.         }
  19.     }]
  20. });
  21. ```

Field options gets inherited when also global options was passed, e.g.:

  1. ``` js
  2. const index = new Document({
  3.     tokenize: "strict",
  4.     optimize: true,
  5.     resolution: 9,
  6.     document: {
  7.         id: "id",
  8.         index:[{
  9.             field: "title",
  10.             tokenize: "forward"
  11.         },{
  12.             field: "content",
  13.             minlength: 3,
  14.             context: {
  15.                 depth: 1,
  16.                 resolution: 3
  17.             }
  18.         }]
  19.     }
  20. });
  21. ```

Note: The context options from the field "content" also gets inherited by the corresponding field options, whereas this field options was inherited by the global option.

Nested Data Fields (Complex Objects)


Assume the document array looks more complex (has nested branches etc.), e.g.:

  1. ``` json
  2. {
  3.   "record": {
  4.     "id": 0,
  5.     "title": "some title",
  6.     "content": {
  7.       "header": "some text",
  8.       "footer": "some text"
  9.     }
  10.   }
  11. }
  12. ```

Then use the colon separated notation root:child:child to define hierarchy within the document descriptor:

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         id: "record:id",
  5.         index: [
  6.             "record:title",
  7.             "record:content:header",
  8.             "record:content:footer"
  9.         ]
  10.     }
  11. });
  12. ```

Just add fields you want to query against. Do not add fields to the index, you just need in the result (but did not query against). For this purpose you can store documents independently of its index (read below).


When you want to query through a field you have to pass the exact key of the field you have defined in the doc as a field name (with colon syntax):

  1. ``` js
  2. index.search(query, {
  3.     index: [
  4.         "record:title",
  5.         "record:content:header",
  6.         "record:content:footer"
  7.     ]
  8. });
  9. ```

Same as:

  1. ``` js
  2. index.search(query, [
  3.     "record:title",
  4.     "record:content:header",
  5.     "record:content:footer"
  6. ]);
  7. ```

Using field-specific options:

  1. ``` js
  2. index.search([{
  3.     field: "record:title",
  4.     query: "some query",
  5.     limit: 100,
  6.     suggest: true
  7. },{
  8.     field: "record:title",
  9.     query: "some other query",
  10.     limit: 100,
  11.     suggest: true
  12. }]);
  13. ```

You can perform a search through the same field with different queries.

When passing field-specific options you need to provide the full configuration for each field. They get not inherited like the document descriptor.


Complex Documents


You need to follow 2 rules for your documents:

1. The document cannot start with an Array at the root index. This will introduce sequential data and isn't supported yet. See below for a workaround for such data.

  1. ``` js
  2. [ // <-- not allowed as document start!
  3.   {
  4.     "id": 0,
  5.     "title": "title"
  6.   }
  7. ]
  8. ```

2. The id can't be nested inside an array (also none of the parent fields can't be an array). This will introduce sequential data and isn't supported yet. See below for a workaround for such data.

  1. ``` js
  2. {
  3.   "records": [ // <-- not allowed when ID or tag lives inside!
  4.     {
  5.       "id": 0,
  6.       "title": "title"
  7.     }
  8.   ]
  9. }
  10. ```

Here an example for a supported complex document:

  1. ``` json
  2. {
  3.   "meta": {
  4.     "tag": "cat",
  5.     "id": 0
  6.   },
  7.   "contents": [
  8.     {
  9.       "body": {
  10.         "title": "some title",
  11.         "footer": "some text"
  12.       },
  13.       "keywords": ["some", "key", "words"]
  14.     },
  15.     {
  16.       "body": {
  17.         "title": "some title",
  18.         "footer": "some text"
  19.       },
  20.       "keywords": ["some", "key", "words"]
  21.     }
  22.   ]
  23. }
  24. ```

The corresponding document descriptor (when all fields should be indexed) looks like:

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         id: "meta:id",
  5.         tag: "meta:tag",
  6.         index: [
  7.             "contents[]:body:title",
  8.             "contents[]:body:footer",
  9.             "contents[]:keywords"
  10.         ]
  11.     }
  12. });
  13. ```

Again, when searching you have to use the same colon-separated-string from your field definition.

  1. ``` js
  2. index.search(query, {
  3.     index: "contents[]:body:title"
  4. });
  5. ```

Not Supported Documents (Sequential Data)


This example breaks both rules from above:

  1. ``` js
  2. [ // <-- not allowed as document start!
  3.   {
  4.     "tag": "cat",
  5.     "records": [ // <-- not allowed when ID or tag lives inside!
  6.       {
  7.         "id": 0,
  8.         "body": {
  9.           "title": "some title",
  10.           "footer": "some text"
  11.         },
  12.         "keywords": ["some", "key", "words"]
  13.       },
  14.       {
  15.         "id": 1,
  16.         "body": {
  17.           "title": "some title",
  18.           "footer": "some text"
  19.         },
  20.         "keywords": ["some", "key", "words"]
  21.       }
  22.     ]
  23.   }
  24. ]
  25. ```

You need to apply some kind of structure normalization.

A workaround to such a data structure looks like this:

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         id: "record:id",
  5.         tag: "tag",
  6.         index: [
  7.             "record:body:title",
  8.             "record:body:footer",
  9.             "record:body:keywords"
  10.         ]
  11.     }
  12. });

  13. function add(sequential_data){

  14.     for(let x = 0, data; x < sequential_data.length; x++){

  15.         data = sequential_data[x];

  16.         for(let y = 0, record; y < data.records.length; y++){

  17.             record = data.records[y];

  18.             index.add({
  19.                 id: record.id,
  20.                 tag: data.tag,
  21.                 record: record
  22.             });
  23.         }
  24.     }  
  25. }

  26. // now just use add() helper method as usual:

  27. add([{
  28.     // sequential structured data
  29.     // take the data example above
  30. }]);
  31. ```

You can skip the first loop when your document data has just one index as the outer array.

Add/Update/Remove Documents to/from the Index


Just pass the document array (or a single object) to the index:

  1. ``` js
  2. index.add(docs);
  3. ```

Update index with a single object or an array of objects:

  1. ``` js
  2. index.update({
  3.     data:{
  4.         id: 0,
  5.         title: "Foo",
  6.         body: {
  7.             content: "Bar"
  8.         }
  9.     }
  10. });
  11. ```

Remove a single object or an array of objects from the index:

  1. ``` js
  2. index.remove(docs);
  3. ```

When the id is known, you can also simply remove by (faster):

  1. ``` js
  2. index.remove(id);
  3. ```

Join / Append Arrays


On the complex example above, the field keywords is an array but here the markup did not have brackets like keywords[]. That will also detect the array but instead of appending each entry to a new context, the array will be joined into on large string and added to the index.

The difference of both kinds of adding array contents is the relevance when searching. When adding each item of an array via append() to its own context by using the syntax field[], then the relevance of the last entry concurrent with the first entry. When you left the brackets in the notation, it will join the array to one whitespace-separated string. Here the first entry has the highest relevance, whereas the last entry has the lowest relevance.

So assuming the keyword from the example above are pre-sorted by relevance to its popularity, then you want to keep this order (information of relevance). For this purpose do not add brackets to the notation. Otherwise, it would take the entries in a new scoring context (the old order is getting lost).

Also you can left bracket notation for better performance and smaller memory footprint. Use it when you did not need the granularity of relevance by the entries.

Field-Search


Search through all fields:

  1. ``` js
  2. index.search(query);
  3. ```

Search through a specific field:

  1. ``` js
  2. index.search(query, { index: "title" });
  3. ```

Search through a given set of fields:

  1. ``` js
  2. index.search(query, { index: ["title", "content"] });
  3. ```

Same as:

  1. ``` js
  2. index.search(query, ["title", "content"]);
  3. ```

Pass custom modifiers and queries to each field:

  1. ``` js
  2. index.search([{
  3.     field: "content",
  4.     query: "some query",
  5.     limit: 100,
  6.     suggest: true
  7. },{
  8.     field: "content",
  9.     query: "some other query",
  10.     limit: 100,
  11.     suggest: true
  12. }]);
  13. ```

You can perform a search through the same field with different queries.

See all available field-search options.

The Result Set


Schema of the result-set:

fields[] => { field, result[] => { document }}


The first index is an array of fields the query was applied to. Each of this field has a record (object) with 2 properties "field" and "result". The "result" is also an array and includes the result for this specific field. The result could be an array of IDs or as enriched with stored document data.

A non-enriched result set now looks like:

  1. ``` js
  2. [{
  3.     field: "title",
  4.     result: [0, 1, 2]
  5. },{
  6.     field: "content",
  7.     result: [3, 4, 5]
  8. }]
  9. ```

An enriched result set now looks like:

  1. ``` js
  2. [{
  3.     field: "title",
  4.     result: [
  5.         { id: 0, doc: { /* document */ }},
  6.         { id: 1, doc: { /* document */ }},
  7.         { id: 2, doc: { /* document */ }}
  8.     ]
  9. },{
  10.     field: "content",
  11.     result: [
  12.         { id: 3, doc: { /* document */ }},
  13.         { id: 4, doc: { /* document */ }},
  14.         { id: 5, doc: { /* document */ }}
  15.     ]
  16. }]
  17. ```

When using pluck instead of "field" you can explicitly select just one field and get back a flat representation:

  1. ``` js
  2. index.search(query, { pluck: "title", enrich: true });
  3. ```

  1. ``` js
  2. [
  3.     { id: 0, doc: { /* document */ }},
  4.     { id: 1, doc: { /* document */ }},
  5.     { id: 2, doc: { /* document */ }}
  6. ]
  7. ```

This result set is a replacement of "boolean search". Instead of applying your bool logic to a nested object, you can apply your logic by yourself on top of the result-set dynamically. This opens hugely capabilities on how you process the results. Therefore, the results from the fields aren't squashed into one result anymore. That keeps some important information, like the name of the field as well as the relevance of each field results which didn't get mixed anymore.

A field search will apply a query with the boolean "or" logic by default. Each field has its own result to the given query.


There is one situation where the bool property is being still supported. When you like to switch the default "or" logic from the field search into "and", e.g.:

  1. ``` js
  2. index.search(query, {
  3.     index: ["title", "content"],
  4.     bool: "and"
  5. });
  6. ```

You will just get results which contains the query in both fields. That's it.

Tags


Like the key for the ID just define the path to the tag:

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         id: "id",
  5.         tag: "tag",
  6.         index: "content"
  7.     }
  8. });
  9. ```

  1. ``` js
  2. index.add({
  3.     id: 0,
  4.     tag: "cat",
  5.     content: "Some content ..."
  6. });
  7. ```

Your data also can have multiple tags as an array:

  1. ``` js
  2. index.add({
  3.     id: 1,
  4.     tag: ["animal", "dog"],
  5.     content: "Some content ..."
  6. });
  7. ```

You can perform a tag-specific search by:

  1. ``` js
  2. index.search(query, {
  3.     index: "content",
  4.     tag: "animal"
  5. });
  6. ```

This just gives you result which was tagged with the given tag.

Use multiple tags when searching:

  1. ``` js
  2. index.search(query, {
  3.     index: "content",
  4.     tag: ["cat", "dog"]
  5. });
  6. ```

This gives you result which are tagged with one of the given tag.

Multiple tags will apply as the boolean "or" by default. It just needs one of the tags to be existing.


This is another situation where the bool property is still supported. When you like to switch the default "or" logic from the tag search into "and", e.g.:

  1. ``` js
  2. index.search(query, {
  3.     index: "content",
  4.     tag: ["dog", "animal"],
  5.     bool: "and"
  6. });
  7. ```

You will just get results which contains both tags (in this example there is just one records which has the tag "dog" and "animal").

Tag Search


You can also fetch results from one or more tags when no query was passed:

  1. ``` js
  2. index.search({ tag: ["cat", "dog"] });
  3. ```

In this case the result-set looks like:

  1. ``` js
  2. [{
  3.     tag: "cat",
  4.     result: [ /* all cats */ ]
  5. },{
  6.     tag: "dog",
  7.     result: [ /* all dogs */ ]
  8. }]
  9. ```

Limit & Offset


By default, every query is limited to 100 entries. Unbounded queries leads into issues. You need to set the limit as an option to adjust the size.


You can set the limit and the offset for each query:

  1. ``` js
  2. index.search(query, { limit: 20, offset: 100 });
  3. ```

You cannot pre-count the size of the result-set. That's a limit by the design of FlexSearch. When you really need a count of all results you are able to page through, then just assign a high enough limit and get back all results and apply your paging offset manually (this works also on server-side). FlexSearch is fast enough that this isn't an issue.


Document Store


Only a document index can have a store. You can use a document index instead of a flat index to get this functionality also when only storing ID-content-pairs.

You can define independently which fields should be indexed and which fields should be stored. This way you can index fields which should not be included in the search result.

Do not use a store when: 1. an array of IDs as the result is good enough, or 2. you already have the contents/documents stored elsewhere (outside the index).


When the store attribute was set, you have to include all fields which should be stored explicitly (acts like a whitelist).


When the store attribute was not set, the original document is stored as a fallback.


This will add the whole original content to the store:

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         index: "content",
  5.         store: true
  6.     }
  7. });

  8. index.add({ id: 0, content: "some text" });
  9. ```

Access documents from internal store


You can get indexed documents from the store:

  1. ``` js
  2. var data = index.get(1);
  3. ```

You can update/change store contents directly without changing the index by:

  1. ``` js
  2. index.set(1, data);
  3. ```

To update the store and also update the index then just use index.update, index.add or index.append.

When you perform a query, weather it is a document index or a flat index, then you will always get back an array of IDs.

Optionally you can enrich the query results automatically with stored contents by:

  1. ``` js
  2. index.search(query, { enrich: true });
  3. ```

Your results look now like:

  1. ``` js
  2. [{
  3.     id: 0,
  4.     doc: { /* content from store */ }
  5. },{
  6.     id: 1,
  7.     doc: { /* content from store */ }
  8. }]
  9. ```

Configure Storage (Recommended)


This will add just specific fields from a document to the store (the ID isn't necessary to keep in store):

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         index: "content",
  5.         store: ["author", "email"]
  6.     }
  7. });

  8. index.add(id, content);
  9. ```

You can configure independently what should being indexed and what should being stored. It is highly recommended to make use of this whenever you can.

Here a useful example of configuring doc and store:

  1. ``` js
  2. const index = new Document({
  3.     document: {
  4.         index: "content",
  5.         store: ["author", "email"]
  6.     }
  7. });

  8. index.add({
  9.     id: 0,
  10.     author: "Jon Doe",
  11.     email: "john@mail.com",
  12.     content: "Some content for the index ..."
  13. });
  14. ```

You can query through the contents and will get back the stored values instead:

  1. ``` js
  2. index.search("some content", { enrich: true });
  3. ```

Your results are now looking like:

  1. ``` js
  2. [{
  3.     field: "content",
  4.     result: [{
  5.         id: 0,
  6.         doc: {
  7.             author: "Jon Doe",
  8.             email: "john@mail.com",
  9.         }
  10.     }]
  11. }]
  12. ```

Both field "author" and "email" are not indexed.

Chaining


Simply chain methods like:

  1. ``` js
  2. var index = FlexSearch.create()
  3.                       .addMatcher({'â': 'a'})
  4.                       .add(0, 'foo')
  5.                       .add(1, 'bar');
  6. ```

  1. ``` js
  2. index.remove(0).update(1, 'foo').add(2, 'foobar');
  3. ```

Enable Contextual Scoring


Create an index and use the default context:
  1. ``` js
  2. var index = new FlexSearch({

  3.     tokenize: "strict",
  4.     context: true
  5. });
  6. ```

Create an index and apply custom options for the context:
  1. ``` js
  2. var index = new FlexSearch({

  3.     tokenize: "strict",
  4.     context: {
  5.         resolution: 5,
  6.         depth: 3,
  7.         bidirectional: true
  8.     }
  9. });
  10. ```

Only the tokenizer "strict" is actually supported by the contextual index.


The contextual index requires <a href="#memory">additional amount of memory</a> depending on depth.


Auto-Balanced Cache (By Popularity)


You need to initialize the cache and its limit during the creation of the index:

  1. ``` js
  2. const index = new Index({ cache: 100 });
  3. ```

  1. ``` js
  2. const results = index.searchCache(query);
  3. ```

A common scenario for using a cache is an autocomplete or instant search when typing.

When passing a number as a limit the cache automatically balance stored entries related to their popularity.


When just using "true" the cache is unbounded and perform actually 2-3 times faster (because the balancer do not have to run).


Worker Parallelism (Browser + Node.js)


The new worker model from v0.7.0 is divided into "fields" from the document (1 worker = 1 field index). This way the worker becomes able to solve tasks (subtasks) completely. The downside of this paradigm is they might not have been perfect balanced in storing contents (fields may have different length of contents). On the other hand there is no indication that balancing the storage gives any advantage (they all require the same amount in total).

When using a document index, then just apply the option "worker":
  1. ``` js
  2. const index = new Document({
  3.     index: ["tag", "name", "title", "text"],
  4.     worker: true
  5. });

  6. index.add({
  7.     id: 1, tag: "cat", name: "Tom", title: "some", text: "some"
  8. }).add({
  9.     id: 2, tag: "dog", name: "Ben", title: "title", text: "content"
  10. }).add({
  11.     id: 3, tag: "cat", name: "Max", title: "to", text: "to"
  12. }).add({
  13.     id: 4, tag: "dog", name: "Tim", title: "index", text: "index"
  14. });
  15. ```

  1. ```
  2. Worker 1: { 1: "cat", 2: "dog", 3: "cat", 4: "dog" }
  3. Worker 2: { 1: "Tom", 2: "Ben", 3: "Max", 4: "Tim" }
  4. Worker 3: { 1: "some", 2: "title", 3: "to", 4: "index" }
  5. Worker 4: { 1: "some", 2: "content", 3: "to", 4: "index" }
  6. ```

When you perform a field search through all fields then this task is being balanced perfectly through all workers, which can solve their subtasks independently.

Worker Index


Above we have seen that documents will create worker automatically for each field. You can also create a WorkerIndex directly (same like using Index instead of Document).

Use as ES6 module:

  1. ``` js
  2. import WorkerIndex from "./worker/i