### Basic Suggestion Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-module/basic-suggestion/index.html
Sets up a FlexSearch index, adds data, performs a search with suggestions, and displays the results in the browser.
```javascript
import { Index } from "https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.8.2/dist/flexsearch.light.module.min.js";
// create a simple index which can store id-content-pairs
const index = new Index({ tokenize: "forward" });
// some test data
const data = [
'cats abcd efgh ijkl mnop qrst uvwx cute',
'cats abcd efgh ijkl mnop qrst cute',
'cats abcd efgh ijkl dogs cute',
'cats abcd efgh ijkl cute',
'cats abcd efgh cute',
'cats abcd cute',
'cats cute'
];
// add data to the index
data.forEach((item, id) => {
index.add(id, item);
});
// perform query
const result = index.search({
query: "black dog or cute cat",
suggest: true
});
// display results
result.forEach(i => {
console.log(data[i]);
log(data[i]);
});
function log(str){
document.body.appendChild( document.createTextNode(str + "\n") );
}
```
--------------------------------
### Basic Index and Resolver Setup
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-module/basic-resolver/index.html
Sets up a FlexSearch index with forward tokenization and adds sample data. This is the initial step before performing queries.
```javascript
import { Index, Resolver } from "https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.8.2/dist/flexsearch.bundle.module.min.js";
// create a simple index which can store id-content-pairs
const index = new Index({ tokenize: "forward" });
// some test data
const data = [
'cats abcd efgh ijkl dogs pigs rats cute',
'cats abcd efgh ijkl dogs pigs cute',
'cats abcd efgh ijkl dogs cute',
'cats abcd efgh ijkl cute',
'cats abcd efgh cute',
'cats abcd cute',
'cats cute'
];
// add data to the index
data.forEach((item, id) => {
index.add(id, item);
});
```
--------------------------------
### Install pg-promise
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-postgres.md
Install the pg-promise npm package to manage PostgreSQL connections.
```bash
npm install pg-promise@11.10.2
```
--------------------------------
### Create Resolver with Initial Query
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/resolver.md
Instantiate a `Resolver` directly by providing an initial query and the index. This is an alternative to starting with `index.search()`.
```javascript
import { Resolver } from "flexsearch";
const raw = new Resolver({
// pass the index is required when query was set
index: index,
query: "a short query"
});
const result = raw.resolve();
```
--------------------------------
### Install Redis Package
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-redis.md
Install the 'redis' npm package to enable Redis persistence for FlexSearch.
```bash
npm install redis@4.7.0
```
--------------------------------
### Using Map for Matcher Initialization
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/encoder.md
Initialize matcher rules using a `Map` object for a concise setup.
```javascript
Map([["and", "&"] , ["usd", "$"]])
```
--------------------------------
### Install FlexSearch via NPM
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Install FlexSearch in your Node.js project using npm. This command downloads and installs the package, making it available for use in your project.
```bash
npm install flexsearch
```
--------------------------------
### Basic Result Highlighting Setup and Query
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/result-highlighting.md
Demonstrates how to create a Document index with the store option, add data, and perform a search with basic highlighting enabled using the 'highlight' option.
```javascript
// 1. create the document index
const index = new Document({
document: {
// using store is required
store: true,
index: [{
field: "title",
tokenize: "forward",
encoder: Charset.LatinBalance
}]
}
});
// 2. add data
index.add({
"id": 1,
"title": "Carmencita"
});
index.add({
"id": 2,
"title": "Le clown et ses chiens"
});
// 3. perform a query
const result = index.search({
query: "karmen or clown or not found",
// also get results when query has no exact match
suggest: true,
// use highlighting options or pass a template, where $1 is
// a placeholder for the matched partial
highlight: "$1",
// optionally pick and apply search to just
// one field and get back a flat result
pluck: "title"
});
```
--------------------------------
### Using Map for Mapper Initialization
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/encoder.md
Initialize mapper rules using a `Map` object for a concise setup.
```javascript
Map([["é", "e"], ["ß", "ss"]])
```
--------------------------------
### Install SQLite3 Package
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-sqlite.md
Install the necessary npm package for SQLite3 support in your project.
```bash
npm install sqlite3@5.1.7
```
--------------------------------
### Compare Context Search - Basic
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Example demonstrating basic search without context enabled. Shows how term proximity affects results.
```js
const index = new Index();
index.add(1, "1 A B C D 2 E F G H I 3 J K L");
index.add(2, "A B C D E F G H I J 1 2 3 K L");
const result = index.search("1 2 3");
// --> [1, 2]
```
--------------------------------
### Compare Context Search - With Context Enabled
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Example demonstrating search with context enabled. Shows how shorter term distances with context influence result order.
```js
const index = new Index({ context: true });
index.add(1, "1 A B C D 2 E F G H I 3 J K L");
index.add(2, "A B C D E F G H I J 1 2 3 K L");
const result = index.search("1 2 3");
// --> [2, 1]
```
--------------------------------
### Browser Module Document Resolver Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-module/document-resolver/index.html
This snippet demonstrates setting up a FlexSearch Document index, adding data, and then using the Resolver to perform a complex query with enrichment. It requires importing necessary components from the FlexSearch library.
```javascript
import { Document, Charset, Resolver } from "https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.8.2/dist/flexsearch.compact.module.min.js"; // some test data const data = [
{
"tconst": "tt0000001",
"titleType": "short",
"primaryTitle": "Carmencita",
"originalTitle": "Carmencita",
"isAdult": 0,
"startYear": "1894",
"endYear": "",
"runtimeMinutes": "1",
"genres": [
"Documentary",
"Short"
]
},
{
"tconst": "tt0000002",
"titleType": "short",
"primaryTitle": "Le clown et ses chiens",
"originalTitle": "Le clown et ses chiens",
"isAdult": 0,
"startYear": "1892",
"endYear": "",
"runtimeMinutes": "5",
"genres": [
"Animation",
"Short"
]
}
]; // create the document index const index = new Document({
document: {
id: "tconst",
store: true,
index: [
{
field: "primaryTitle",
tokenize: "forward",
encoder: Charset.LatinBalance
},
{
field: "originalTitle",
tokenize: "forward",
encoder: Charset.LatinBalance
}
],
tag: [
{
field: "startYear"
},
{
field: "genres"
}
]
}
}); // add test data for(let i = 0; i < data.length; i++){
index.add(data[i]);
}
// perform a complex query + enrich results
let result = new Resolver({
index: index,
query: "karmen",
pluck: "primaryTitle"
}).or({
query: "clown",
pluck: "primaryTitle"
}).and({
query: "not found",
field: "originalTitle",
suggest: true
}).not({
query: "clown",
pluck: "primaryTitle"
}).resolve({
enrich: true
});
// display results
console.log(result);
log(JSON.stringify(result, null, 2));
log("\n-------------------------------------\n");
function log(str){
document.body.appendChild(
document.createTextNode(str + "\n")
);
}
```
--------------------------------
### Install Clickhouse Package
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-clickhouse.md
Install the required 'clickhouse' npm package for your project.
```bash
npm install clickhouse@2.6.0
```
--------------------------------
### Browser Module Document Persistent Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-module/document-persistent/index.html
This snippet demonstrates setting up a FlexSearch index with IndexedDB, adding data, committing changes, and performing searches with enrichment, merging, and suggestions. It requires the FlexSearch bundle to be imported.
```javascript
import { Document, Charset, IndexedDB } from "https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.8.2/dist/flexsearch.bundle.module.min.js"; // some test data const data = [{ "tconst": "tt0000001", "titleType": "short", "primaryTitle": "Carmencita", "originalTitle": "Carmencita", "isAdult": 0, "startYear": "1894", "endYear": "", "runtimeMinutes": "1", "genres": [ "Documentary", "Short" ] },{ "tconst": "tt0000002", "titleType": "short", "primaryTitle": "Le clown et ses chiens", "originalTitle": "Le clown et ses chiens", "isAdult": 0, "startYear": "1892", "endYear": "", "runtimeMinutes": "5", "genres": [ "Animation", "Short" ] }]; // create DB instance with namespace const db = new IndexedDB("my-store"); // create the document index const index = new Document({ document: { id: "tconst", store: true, index: [{ field: "primaryTitle", tokenize: "forward", encoder: Charset.LatinBalance },{ field: "originalTitle", tokenize: "forward", encoder: Charset.LatinBalance }], tag: [{ field: "startYear" },{ field: "genres" }] } }); await index.mount(db); // await document.destroy(); // await document.mount(db); // add test data for(let i = 0; i < data.length; i++){ index.add(data[i]); } // transfer changes (bulk) await index.commit(); // perform a query const result = await index.search({ query: "karmen", tag: { "startYear": "1894", "genres": [ "Documentary", "Short" ] }, enrich: true }); // display results console.log(result); log(JSON.stringify(result, null, 2)); log("\n-------------------------------------\n"); // perform a query + merge results const merged = await index.search({ query: "karmen", tag: { "startYear": "1894", "genres": [ "Documentary", "Short" ] }, enrich: true, merge: true }); // display results console.log(merged); log(JSON.stringify(merged, null, 2)); log("\n-------------------------------------\n"); // perform a query + get suggestions const suggestions = await index.search({ query: "karmen or clown or not found", tag: { // no data for this category: "genres": "Movie" }, suggest: true, enrich: true, merge: true }); // display results console.log(suggestions); log(JSON.stringify(suggestions, null, 2)); function log(str){ document.body.appendChild( document.createTextNode(str + "\n") ); }
```
--------------------------------
### Disallowed Document Start (Array)
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
Documents cannot start with an array at the root level. This structure is not supported.
```javascript
[ // <-- not allowed as document start!
{
"id": 0,
"title": "title"
}
]
```
--------------------------------
### Browser Document Worker Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-legacy/document-worker/index.html
This snippet demonstrates setting up a FlexSearch Document index with a worker, adding data, and performing searches with query, tag, enrich, and merge options. It also shows how to retrieve suggestions.
```javascript
async function(){
// some test data
const data = [
{
"tconst": "tt0000001",
"titleType": "short",
"primaryTitle": "Carmencita",
"originalTitle": "Carmencita",
"isAdult": 0,
"startYear": "1894",
"endYear": "",
"runtimeMinutes": "1",
"genres": [
"Documentary",
"Short"
]
},
{
"tconst": "tt0000002",
"titleType": "short",
"primaryTitle": "Le clown et ses chiens",
"originalTitle": "Le clown et ses chiens",
"isAdult": 0,
"startYear": "1892",
"endYear": "",
"runtimeMinutes": "5",
"genres": [
"Animation",
"Short"
]
}
];
// create the document index
const index = new FlexSearch.Document({
// enable worker: worker: true,
// hint: the encoder is shared for both index fields
// because primaryTitle and originalTitle has almost
// equal content, otherwise you should set the encoder
// option to each of the field options separately
encoder: FlexSearch.Charset.LatinBalance,
document: {
id: "tconst",
store: true,
index: [
{ field: "primaryTitle", tokenize: "forward" },
{ field: "originalTitle", tokenize: "forward" }
],
tag: [
{ field: "startYear" },
{ field: "genres" }
]
}
});
// add test data
for(let i = 0; i < data.length; i++){
await index.add(data[i]);
}
// perform a query
const result = await index.search({
query: "karmen",
tag: {
"startYear": "1894",
"genres": [
"Documentary",
"Short"
]
},
enrich: true
});
// display results
console.log(result);
log(JSON.stringify(result, null, 2));
log("\n-------------------------------------\n");
// perform a query + merge results
const merged = await index.search({
query: "karmen",
tag: {
"startYear": "1894",
"genres": [
"Documentary",
"Short"
]
},
enrich: true,
merge: true
});
// display results
console.log(merged);
log(JSON.stringify(merged, null, 2));
log("\n-------------------------------------\n");
// perform a query + get suggestions
const suggestions = await index.search({
query: "karmen or clown or not found",
tag: {
// no data for this category:
"genres": "Movie"
},
suggest: true,
enrich: true,
merge: true
});
// display results
console.log(suggestions);
log(JSON.stringify(suggestions, null, 2));
function log(str){
document.body.appendChild(
document.createTextNode(str + "\n")
);
}
}()
```
--------------------------------
### Default Resolver Usage
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/resolver.md
Demonstrates the default behavior of the resolver by first getting an unresolved result and then calling `.resolve()` without any options.
```javascript
const raw = index.search("a short query", {
resolve: false
});
const result = raw.resolve();
```
--------------------------------
### Browser Module Language Pack Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-module/language-pack/index.html
This snippet demonstrates initializing FlexSearch with a custom encoder and language preset for English, then indexing and searching string data. It requires importing necessary components from FlexSearch and the English language pack.
```javascript
import { Index, Encoder, Charset } from "https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.8.2/dist/flexsearch.compact.module.min.js";
import EnglishPreset from "https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.8.2/dist/module/lang/en.js";
const encoder = new Encoder( Charset.LatinSimple, EnglishPreset );
// create a simple index which can store id-content-pairs
const index = new Index({ tokenize: "forward", encoder: encoder });
// some test data
const data = [
'She doesn\'t get up at six o\'clock.',
'It\'s been raining for five hours now.'
];
// add data to the index
data.forEach((item, id) => {
index.add(id, item);
});
// perform query
let result = index.search("she does not at clock");
// display results
result.forEach(i => {
console.log(data[i]);
log(data[i]);
log("\n-------------------------------------\n");
});
// perform query
result = index.search("it is raining now");
// display results
result.forEach(i => {
console.log(data[i]);
log(data[i]);
});
function log(str){
document.body.appendChild( document.createTextNode(str + "\n") );
}
```
--------------------------------
### Unsupported Document Example (Sequential Data)
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
An example of a document structure that breaks both rules for root arrays and nested IDs within arrays.
```javascript
[
{
"tag": "cat",
"records": [
{
"id": 0,
"body": {
"title": "some title",
"footer": "some text"
},
"keywords": ["some", "key", "words"]
},
{
"id": 1,
"body": {
"title": "some title",
"footer": "some text"
},
"keywords": ["some", "key", "words"]
}
]
}
]
```
--------------------------------
### Result Highlighting JSON Output Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/result-highlighting.md
Shows the expected JSON structure of search results when result highlighting is enabled and configured.
```json
[
{
"id": 1,
"highlight": "Carmencita"
},
{
"id": 2,
"highlight": "Le clown et ses chiens"
}
]
```
--------------------------------
### Supported Complex Document Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
An example of a complex document structure that FlexSearch supports, with nested objects and arrays.
```json
{
"meta": {
"tag": "cat",
"id": 0
},
"contents": [
{
"body": {
"title": "some title",
"footer": "some text"
},
"keywords": ["some", "key", "words"]
},
{
"body": {
"title": "some title",
"footer": "some text"
},
"keywords": ["some", "key", "words"]
}
]
}
```
--------------------------------
### Document Schema Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
An example of a document schema used with FlexSearch, including fields like title, type, and genres.
```javascript
{
"tconst": "tt0000001",
"titleType": "short",
"primaryTitle": "Carmencita",
"originalTitle": "Carmencita",
"isAdult": 0,
"startYear": "1894",
"endYear": "",
"runtimeMinutes": "1",
"genres": [
"Documentary",
"Short"
]
}
```
--------------------------------
### Configure In-Memory Keystore Range
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/keystore.md
Set the keystore range for an In-Memory index to increase the maximum number of distinct terms/partials that can be stored. This example sets an 8-Bit keystore, allowing for a theoretical total of 2^32 keys.
```javascript
const index = new Index({
// e.g. set keystore range to 8-Bit:
// 2^8 * 2^24 = 2^32 keys total
keystore: 8
});
```
--------------------------------
### Apply Highlight Option to Resolver Stage
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/result-highlighting.md
Demonstrates passing highlight options to a specific resolver stage within a complex query setup. The last resolver stage inherits necessary options.
```javascript
const raw = new Resolver({
index: index,
field: "title",
query: "some query"
})
.or({
field: "title",
// highlight requires a query
query: "highlight this",
// define on a single resolver stage
highlight: { /* ... */ }
})
.not({
field: "title",
query: "undefined",
})
.resolve();
```
--------------------------------
### Import FlexSearch from CDN (ESM)
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Load FlexSearch components directly from a CDN using an ES module import. This is a convenient way to include the library without local installation.
```html
```
--------------------------------
### FlexSearch Document Index with IndexedDB Persistence
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-legacy/document-persistent/index.html
This snippet demonstrates the setup and usage of FlexSearch's Document API with IndexedDB for persistent storage. It includes creating an index, mounting it to a database, adding data, committing changes, and performing searches.
```javascript
async function(){
// some test data
const data = [
{
"tconst": "tt0000001",
"titleType": "short",
"primaryTitle": "Carmencita",
"originalTitle": "Carmencita",
"isAdult": 0,
"startYear": "1894",
"endYear": "",
"runtimeMinutes": "1",
"genres": [
"Documentary",
"Short"
]
},
{
"tconst": "tt0000002",
"titleType": "short",
"primaryTitle": "Le clown et ses chiens",
"originalTitle": "Le clown et ses chiens",
"isAdult": 0,
"startYear": "1892",
"endYear": "",
"runtimeMinutes": "5",
"genres": [
"Animation",
"Short"
]
}
];
// create DB instance with namespace
const db = new FlexSearch.IndexedDB("my-store");
// create the document index
const index = new FlexSearch.Document({
// hint: the encoder is shared for both index fields
// because primaryTitle and originalTitle has almost
// equal content, otherwise you should set the encoder
// option to each of the field options separately
encoder: FlexSearch.Charset.LatinBalance,
document: {
id: "tconst",
store: true,
index: [
{
field: "primaryTitle",
tokenize: "forward"
},
{
field: "originalTitle",
tokenize: "forward"
}
],
tag: [
{
field: "startYear"
},
{
field: "genres"
}
]
}
});
await index.mount(db);
// await document.destroy();
// await document.mount(db);
// add test data
for(let i = 0; i < data.length; i++){
index.add(data[i]);
}
// transfer changes (bulk)
await index.commit();
// perform a query
const result = await index.search({
query: "karmen",
tag: {
"startYear": "1894",
"genres": [
"Documentary",
"Short"
]
},
enrich: true
});
// display results
console.log(result);
log(JSON.stringify(result, null, 2));
log("\n-------------------------------------\n");
// perform a query + merge results
const merged = await index.search({
query: "karmen",
tag: {
"startYear": "1894",
"genres": [
"Documentary",
"Short"
]
},
enrich: true,
merge: true
});
// display results
console.log(merged);
log(JSON.stringify(merged, null, 2));
log("\n-------------------------------------\n");
// perform a query + get suggestions
const suggestions = await index.search({
query: "karmen or clown or not found",
tag: {
// no data for this category:
"genres": "Movie"
},
suggest: true,
enrich: true,
merge: true
});
// display results
console.log(suggestions);
log(JSON.stringify(suggestions, null, 2));
function log(str){
document.body.appendChild(
document.createTextNode(str + "\n")
);
}
}())
```
--------------------------------
### Perform Search for Suggestions with Tag Filtering
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-module/document-worker-extern-config/index.html
Retrieves search suggestions based on a query, with results filtered by tags. This example also demonstrates merging results and enabling suggestions.
```javascript
const suggestions = await index.search({
query: "karmen or clown or not found",
tag: {
// no data for this category:
"genres": "Movie"
},
suggest: true,
enrich: true,
merge: true
});
console.log(suggestions);
log(JSON.stringify(suggestions, null, 2));
```
--------------------------------
### Worker Document Setup with Parallel Fields
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/worker.md
Configure a Document index to use worker threads for parallel processing of indexed fields. This is useful for large datasets to prevent main thread blocking.
```javascript
const index = new Document({
worker: true,
document: {
id: "id",
index: ["name", "title"],
tag: ["cat"]
}
});
index.add({
id: 1, cat: "catA", name: "Tom", title: "some"
}).add({
id: 2, cat: "catA", name: "Ben", title: "title"
}).add({
id: 3, cat: "catB", name: "Max", title: "to"
}).add({
id: 4, cat: "catB", name: "Tim", title: "index""
});
```
--------------------------------
### Run Basic Builds
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/custom-builds.md
Execute standard build commands for different FlexSearch configurations.
```bash
npm run build:bundle
npm run build:light
npm run build:module
```
--------------------------------
### Initialize Redis Database Adapter
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-redis.md
Create a FlexSearch index and mount a Redis database adapter for persistence. Changes are automatically committed by default.
```javascript
import { Index } from "flexsearch";
import Database from "flexsearch/db/redis";
// Redis Connection
const config = {
host: "localhost",
port: "6379",
user: null,
pass: null
};
// create an index
const index = new Index();
// create db instance with optional prefix
const db = new Database("my-store", config);
// mount and await before transfering data
await index.mount(db);
// update the index as usual
index.add(1, "content...");
index.update(2, "content...");
index.remove(3);
// changes are automatically committed by default
// when you need to wait for the task completion, then you
// can use the commit method explicitely:
await index.commit();
```
--------------------------------
### Initialize FlexSearch with Clickhouse Storage
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-clickhouse.md
Create a FlexSearch index and mount a Clickhouse database adapter. Ensure the database is mounted before transferring data.
```js
import { Index } from "flexsearch";
import Database from "flexsearch/db/clickhouse";
// your database configuration
const config = {
host: "http://localhost",
port: "8123",
database: "default",
basicAuth: null,
debug: false
};
// create an index
const index = new Index();
// create db instance with optional prefix
const db = new Database("my-store", config);
// mount and await before transfering data
await index.mount(db);
// update the index as usual
index.add(1, "content...");
index.update(2, "content...");
index.remove(3);
// changes are automatically committed by default
// when you need to wait for the task completion, then you
// can use the commit method explicitely:
await index.commit();
```
--------------------------------
### Install MongoDB npm Package
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-mongodb.md
Install the required mongodb npm package for version 6.13.0.
```bash
npm install mongodb@6.13.0
```
--------------------------------
### Encoder Initialization with Preset (Equivalent)
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/encoder.md
Shows an equivalent way to initialize an Encoder with a preset, followed by assigning a configuration to modify it.
```javascript
const encoder = new Encoder(EnglishBookPreset);
encoder.assign({ filter: false });
```
--------------------------------
### Initialize and Mount Postgres Storage
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-postgres.md
Create a FlexSearch index and mount a Postgres database adapter for persistent storage. Changes are automatically committed by default.
```javascript
import { Index } from "flexsearch";
import Database from "flexsearch/db/postgres";
// your database configuration
const config = {
user: "postgres",
pass: "postgres",
host: "localhost",
port: "5432",
// database name:
name: "postgres"
};
// create an index
const index = new Index();
// create db instance with optional prefix
const db = new Database("my-store", config);
// mount and await before transfering data
await index.mount(db);
// update the index as usual
index.add(1, "content...");
index.update(2, "content...");
index.remove(3);
// changes are automatically committed by default
// when you need to wait for the task completion, then you
// can use the commit method explicitely:
await index.commit();
```
--------------------------------
### Initialize Index with Chained Methods
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Demonstrates initializing a new FlexSearch index and performing multiple operations like adding matchers and items in a single chained sequence.
```javascript
const index = new Index().addMatcher({'â': 'a'}).add(0, 'foo').add(1, 'bar');
```
--------------------------------
### Search All Fields
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
Use this to search across all indexed fields in your FlexSearch index. No specific setup is required beyond having an initialized index.
```javascript
index.search(query);
```
--------------------------------
### Create index with preset
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Create a new index and select one of the available presets.
```javascript
const index = new Index("match");
```
--------------------------------
### Require FlexSearch Default Export (Node.js)
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Use the default export of FlexSearch in Node.js CommonJS modules. This is the standard way to import the library after installation.
```javascript
const FlexSearch = require("flexsearch");
const index = new FlexSearch.Index(/* ... */);
```
--------------------------------
### Example of Injected Function Body
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/export-import.md
Illustrates the structure of the JavaScript function generated by `index.serialize()`. This function is used to inject index data into a client-side index.
```javascript
function inject(index){
index.reg = new Set([/* ... */]);
index.map = new Map([/* ... */]);
index.ctx = new Map([/* ... */]);
}
```
--------------------------------
### Initialize and Mount FlexSearch with IndexedDB
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-module/basic-persistent/index.html
Sets up an IndexedDB instance and a FlexSearch index, then mounts the index to the database for persistent storage. Use this for applications requiring data persistence across sessions.
```javascript
import { Index, IndexedDB } from "https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.8.2/dist/flexsearch.bundle.module.min.js";
// create DB instance with namespace
const db = new IndexedDB("my-store");
// create a simple index which can store id-content-pairs
const index = new Index({
tokenize: "forward"
});
// mount database to the index
await index.mount(db);
// await index.destroy();
// await index.mount(db);
```
--------------------------------
### Retrieve Unresolved Search Results
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/resolver.md
Use `resolve: false` in the search options to get an unresolved result object. This allows for further manipulation before final resolution.
```javascript
const raw = index.search("a short query", {
resolve: false
});
```
--------------------------------
### Create index with custom options
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Create a new index and configure it with custom options.
```javascript
const index = new Index({
tokenize: "forward"
});
```
--------------------------------
### Searching with Tag Filters
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
Perform searches using tag filters to narrow down results based on specific tags. This example searches for documents tagged with 'Berlin'.
```javascript
const result = index.search({
query: "john doe",
tag: { "city": "Berlin" }
});
```
--------------------------------
### Mounting PostgreSQL with FlexSearch in Node.js
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent.md
Shows how to set up a FlexSearch index with a persistent PostgreSQL database adapter in a Node.js environment. The database must be mounted before data operations can occur.
```javascript
import { Index } from "flexsearch";
import Database from "flexsearch/db/postgres";
// create an index
const index = new Index();
// create db instance with optional prefix
const db = new Database("my-store");
// mount and await before transfering data
await index.mount(db);
// update the index as usual
index.add(1, "content...");
index.update(2, "content...");
index.remove(3);
// changes are automatically committed by default
// when you need to wait for the task completion, then you
// can use the commit method explicitely:
await index.commit();
```
--------------------------------
### Mounting IndexedDB with FlexSearch in Browser
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent.md
Demonstrates how to create and mount an IndexedDB storage for a FlexSearch index in a browser environment. Ensure the database is mounted before transferring data.
```javascript
import { Index, IndexedDB } from "../dist/flexsearch.bundle.module.min.js";
// create an index
const index = new Index();
// create db instance with optional prefix
const db = new IndexedDB("my-store");
// mount and await before transfering data
await index.mount(db);
// update the index as usual
index.add(1, "content...");
index.update(2, "content...");
index.remove(3);
// changes are automatically committed by default
// when you need to wait for the task completion, then you
// can use the commit method explicitely:
await index.commit();
```
--------------------------------
### Basic Suggestion Index Creation and Usage
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-legacy/basic-suggestion/index.html
Initializes a FlexSearch index with forward tokenization, adds sample data, and performs a search query with suggestion enabled. Results are then logged to the console and the document body.
```javascript
create a simple index which can store id-content-pairs
const index = new FlexSearch.Index({ tokenize: "forward" });
// some test data
const data = [
'cats abcd efgh ijkl mnop qrst uvwx cute',
'cats abcd efgh ijkl mnop qrst cute',
'cats abcd efgh ijkl dogs cute',
'cats abcd efgh ijkl cute',
'cats abcd efgh cute',
'cats abcd cute',
'cats cute'
];
// add data to the index
data.forEach((item, id) => {
index.add(id, item);
});
// perform query
const result = index.search({
query: "black dog or cute cat",
suggest: true
});
// display results
result.forEach(i => {
console.log(data[i]);
log(data[i]);
});
function log(str){
document.body.appendChild( document.createTextNode(str + "\n") );
}
```
--------------------------------
### Browser Module Document Highlighting
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-module/document-highlighting/index.html
Imports FlexSearch, sets up data, creates an index, adds documents, performs a search with highlighting, and logs the results. Ensure the FlexSearch library is imported correctly.
```javascript
import { Document, Charset } from "https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch@0.8.2/dist/flexsearch.compact.module.min.js"; // some test data const data = [
{
"id": 1,
"title": "Carmencita"
},
{
"id": 2,
"title": "Le clown et ses chiens"
}
]; // create the document index const index = new Document({
document: {
store: true,
index: [
{
"field": "title",
"tokenize": "forward",
"encoder": Charset.LatinBalance
}
]
}
}); // add test data for(let i = 0; i < data.length; i++){
index.add(data[i]);
}
// perform a query const result = index.search({
query: "karmen or clown or not found",
suggest: true,
// set enrich to true (required)
enrich: true,
// highlight template
// $1 is a placeholder for the matched partial
highlight: "$1"
});
// display results console.log(result);
log(JSON.stringify(result, null, 2));
function log(str){
document.body.appendChild(
document.createTextNode(str + "\n")
);
}
```
--------------------------------
### Chaining Operations with Nested Queries
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/resolver.md
Demonstrates chaining resolver operations with nested query structures, including `or`, `and`, and `not` conditions. The `resolve` method is called at the end to get the final results.
```javascript
const result = index.search("further query", {
// set resolve to false on the first query
resolve: false,
// boost the first query
boost: 2
})
.or({
// nested expression
and: [{
query: "a query"
},{
query: "another query"
}]
})
.not({
query: "some query"
})
// resolve the result
.resolve({
limit: 100,
offset: 0
});
```
--------------------------------
### Create index extending preset with options
Source: https://github.com/nextapps-de/flexsearch/blob/master/README.md
Create a new index by extending a preset and applying custom options.
```javascript
var index = new FlexSearch({
preset: "memory",
tokenize: "forward",
resolution: 5
});
```
--------------------------------
### Initialize and Populate FlexSearch Document Index
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-legacy/document-highlighting/index.html
Sets up a FlexSearch document index with specific field configurations and adds sample data. Use this for basic document indexing and searching in the browser.
```javascript
const data = [
{
"id": 1,
"title": "Carmencita"
},
{
"id": 2,
"title": "Le clown et ses chiens"
}
];
const index = new FlexSearch.Document({
document: {
store: true,
index: [
{
"field": "title",
"tokenize": "forward",
"encoder": FlexSearch.Charset.LatinBalance
}
]
}
});
for (let i = 0; i < data.length; i++) {
index.add(data[i]);
}
```
--------------------------------
### Limit and Offset Search Results
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
Control the number of results returned and the starting point for pagination by setting 'limit' and 'offset' options. Note that FlexSearch has a default limit of 100 entries per query.
```javascript
index.search(query, { limit: 20, offset: 100 });
```
--------------------------------
### Search by Multiple Tags (Intersection)
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
Finds entries that match all specified tags across different fields, demonstrating an intersection of criteria. For example, documents tagged as both 'Documentary' and 'Short' in genres, and '1894' in startYear.
```javascript
const result = index.search({
//enrich: true, // enrich documents
tag: {
"genres": ["Documentary", "Short"],
"startYear": "1894"
}
});
```
--------------------------------
### Queueing Async Queries with FlexSearch Resolver
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/resolver.md
Demonstrates how to queue multiple asynchronous queries using the FlexSearch Resolver. Tasks are processed consecutively and balanced by the runtime observer.
```javascript
import { Resolver } from "flexsearch";
const resolver = await new Resolver({
index: index,
query: "a query",
async: true
})
.and({
query: "another query",
queue: true
})
.or({
query: "some query",
queue: true
})
.resolve(100);
```
--------------------------------
### Initialize FlexSearch Document Index
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-legacy/document/index.html
Sets up a FlexSearch Document index with specific configurations for fields, tokenization, and tagging. Use this to prepare for indexing structured data.
```javascript
const data = [{"tconst": "tt0000001", "titleType": "short", "primaryTitle": "Carmencita", "originalTitle": "Carmencita", "isAdult": 0, "startYear": "1894", "endYear": "", "runtimeMinutes": "1", "genres": ["Documentary", "Short"]},{"tconst": "tt0000002", "titleType": "short", "primaryTitle": "Le clown et ses chiens", "originalTitle": "Le clown et ses chiens", "isAdult": 0, "startYear": "1892", "endYear": "", "runtimeMinutes": "5", "genres": ["Animation", "Short"]}]
const index = new FlexSearch.Document({
encoder: FlexSearch.Charset.LatinBalance,
document: {
id: "tconst",
store: true,
index: [{ field: "primaryTitle", tokenize: "forward" },{ field: "originalTitle", tokenize: "forward" }],
tag: [{ field: "startYear" },{ field: "genres" }]
}
});
```
--------------------------------
### Create and Populate Basic FlexSearch Index
Source: https://github.com/nextapps-de/flexsearch/blob/master/example/browser-legacy/basic/index.html
Initializes a FlexSearch index with forward tokenization for partial matching and adds sample data. Use this for simple text indexing where partial word matches are desired.
```javascript
const index = new FlexSearch.Index({
// use forward when you want to match partials
// e.g. match "flexsearch" when query "flex"
tokenize: "forward"
});
// some test data
const data = [
'cats abcd efgh ijkl mnop qrst uvwx cute',
'cats abcd efgh ijkl mnop qrst cute',
'cats abcd efgh ijkl mnop cute',
'cats abcd efgh ijkl cute',
'cats abcd efgh cute',
'cats abcd cute',
'cats cute'
];
// add data to the index
data.forEach((item, id) => {
index.add(id, item);
});
```
--------------------------------
### Creating a FlexSearch Document Index
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/worker.md
Instantiates a FlexSearch Document index using a provided configuration object.
```javascript
import { Document } from "flexsearch";
const document = await new Document(config);
// add data to the index
// ...
```
--------------------------------
### Mount SQLite Database to FlexSearch Index
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-sqlite.md
Create a FlexSearch index and mount a SQLite database adapter to it. Changes are automatically committed by default.
```js
import { Index } from "flexsearch";
import Database from "flexsearch/db/sqlite";
// create an index
const index = new Index();
// create db instance with optional prefix
const db = new Database("my-store");
// mount and await before transfering data
await index.mount(db);
// update the index as usual
index.add(1, "content...");
index.update(2, "content...");
index.remove(3);
// changes are automatically committed by default
// when you need to wait for the task completion, then you
// can use the commit method explicitely:
await index.commit();
```
--------------------------------
### Score Function Parameters Example
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/customization.md
Illustrates the parameters passed to the custom score function when using the 'full' tokenizer and processing partial terms. The parameters include content, term, term index, partial, and partial index.
```javascript
function score(content, term, term_index, partial, partial_index){
content = ["this", "is", "an", "example", "of", "partial", "encoding"]
term = "example"
term_index = 3
partial = "amp"
partial_index = 2
}
```
--------------------------------
### Pluck Single Field with Enrichment
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/document-search.md
Use the 'pluck' option to retrieve results from only one specific field, combined with 'enrich: true' to get the document data. This returns a flat array of enriched results for the selected field.
```javascript
index.search(query, {
pluck: "title",
enrich: true
});
```
```javascript
[
{ id: 0, doc: { /* document */ }},
{ id: 1, doc: { /* document */ }},
{ id: 2, doc: { /* document */ }}
]
```
--------------------------------
### Create and Mount MongoDB Index
Source: https://github.com/nextapps-de/flexsearch/blob/master/doc/persistent-mongodb.md
Create a FlexSearch index and mount a MongoDB storage adapter. Changes are automatically committed by default.
```javascript
import { Index } from "flexsearch";
import Database from "flexsearch/db/mongodb";
// create an index
const index = new Index();
// create db instance with optional namespace
const db = new Database("my-store");
// mount and await before transfering data
await index.mount(db);
// update the index as usual
index.add(1, "content...");
index.update(2, "content...");
index.remove(3);
// changes are automatically committed by default
// when you need to wait for the task completion, then you
// can use the commit method explicitely:
await index.commit();
```