### Initialize and Use elasticlunr.js in Node.js
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Require the library, initialize an index, add documents, and perform a search. This is a basic example for Node.js usage.
```javascript
var elasticlunr = require('elasticlunr');
var index = elasticlunr(function () {
this.addField('title')
this.addField('body')
});
var doc1 = {
"id": 1,
"title": "Oracle released its latest database Oracle 12g",
"body": "Yestaday Oracle has released its new database Oracle 12g, this would make more money for this company and lead to a nice profit report of annual year."
}
var doc2 = {
"id": 2,
"title": "Oracle released its profit report of 2015",
"body": "As expected, Oracle released its profit report of 2015, during the good sales of database and hardware, Oracle's profit of 2015 reached 12.5 Billion."
}
index.addDoc(doc1);
index.addDoc(doc2);
index.search("Oracle database profit");
```
--------------------------------
### Install elasticlunr.js in Node.js
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Use npm to install the elasticlunr.js package for Node.js projects.
```bash
npm install elasticlunr
```
--------------------------------
### Node.js Example for Other Languages
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Use this snippet to integrate elasticlunr.js with language support files in Node.js. Ensure you have downloaded the language support files from lunr-languages and placed them in your project.
```javascript
var elasticlunr = require('elasticlunr');
require('./lunr.stemmer.support.js')(elasticlunr);
require('./lunr.de.js')(elasticlunr);
var index = elasticlunr(function () {
// use the language (de)
this.use(elasticlunr.de);
// then, the normal elasticlunr index initialization
this.addField('title')
this.addField('body')
});
```
--------------------------------
### Creating an Index
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
The `elasticlunr(config)` function is used to create and configure a new search index instance. You can define searchable fields and the document reference key during setup. The default pipeline includes trimming, stop-word filtering, and English stemming.
```APIDOC
## Creating an Index
`elasticlunr(config)` — the main factory function that creates and configures a new index instance. The default pipeline includes a trimmer, stop-word filter, and English stemmer. Fields to be indexed and the document reference key must be declared here.
```javascript
const elasticlunr = require('elasticlunr');
// Create index with two searchable fields and a custom ref field
const idx = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
// Optionally disable document storage to reduce index size
// this.saveDocument(false);
});
// Alternative fluent setup (equivalent)
const idx2 = elasticlunr();
idx2.addField('title');
idx2.addField('body');
idx2.setRef('id');
console.log(idx.getFields()); // ['id', 'title', 'body']
```
```
--------------------------------
### Add Documents to the Index
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Use `index.addDoc(doc)` to add JSON documents to the index. Fields not declared during setup are ignored. The document reference field (e.g., 'id') serves as the lookup key.
```javascript
const idx = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
});
idx.addDoc({ id: 1, title: 'Oracle released its latest database Oracle 12g', body: 'Oracle has released its new database Oracle 12g, making more profit this year.' });
idx.addDoc({ id: 2, title: 'Oracle released its profit report of 2015', body: 'Oracle profit of 2015 reached 12.5 Billion during good hardware and database sales.' });
idx.addDoc({ id: 3, title: 'Google releases Chrome 100', body: 'Google has released a new version of Chrome with improved performance.' });
console.log(idx.documentStore.length); // 3
```
--------------------------------
### Adding Documents
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
The `index.addDoc(doc)` method adds a JSON document to the index. Fields not declared during index setup are ignored. The document's reference field (e.g., 'id') serves as the lookup key.
```APIDOC
## `index.addDoc(doc)` — Adding Documents
Adds a JSON document to the index. Fields not declared during setup are silently ignored. The document reference field (`id` by default) is used as the lookup key.
```javascript
const idx = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
});
idx.addDoc({ id: 1, title: 'Oracle released its latest database Oracle 12g', body: 'Oracle has released its new database Oracle 12g, making more profit this year.' });
idx.addDoc({ id: 2, title: 'Oracle released its profit report of 2015', body: 'Oracle profit of 2015 reached 12.5 Billion during good hardware and database sales.' });
idx.addDoc({ id: 3, title: 'Google releases Chrome 100', body: 'Google has released a new version of Chrome with improved performance.' });
console.log(idx.documentStore.length); // 3
```
```
--------------------------------
### Create a Simple Search Index
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Initialize an elasticlunr index with specified fields and a document reference. Use 'id' as the default reference if not explicitly set.
```javascript
var index = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
});
```
```javascript
var index = elasticlunr();
index.addField('title');
index.addField('body');
index.setRef('id');
```
--------------------------------
### Use German Language Support in elasticlunr.js
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Initialize an elasticlunr.js index and specify the use of German language support by calling this.use(elasticlunr.de). This should be done during index initialization.
```javascript
var index = elasticlunr(function () {
// use the language (de)
this.use(elasticlunr.de);
// then, the normal elasticlunr index initialization
this.addField('title')
this.addField('body')
});
```
--------------------------------
### Configuration Query with Boosting
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Performs a search query with configurable boosting for specific fields. This allows for prioritizing certain fields during the search.
```APIDOC
## Configuration Query - Query-Time Boosting
### Description
Performs a search query with configurable boosting for specific fields. This allows for prioritizing certain fields during the search. If this configuration is set, elasticlunr.js will only search the query string in the specified fields with boosting weight.
### Method
`index.search(query, configuration)`
### Parameters
- **query** (String) - The search query string.
- **configuration** (Object) - Configuration object for search parameters.
- **fields** (Object) - An object where keys are field names and values are boost configurations.
- **fieldName** (Object) - Configuration for a specific field.
- **boost** (Number) - The boost weight for this field.
### Request Example
```javascript
index.search("Oracle database profit", {
fields: {
title: {boost: 2},
body: {boost: 1}
}
});
```
```
--------------------------------
### Create an Elasticlunr.js Index
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Use the `elasticlunr(config)` function to create a new index. Configure searchable fields and the document reference key. The default pipeline includes trimming, stop-word filtering, and English stemming.
```javascript
const elasticlunr = require('elasticlunr');
// Create index with two searchable fields and a custom ref field
const idx = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
// Optionally disable document storage to reduce index size
// this.saveDocument(false);
});
// Alternative fluent setup (equivalent)
const idx2 = elasticlunr();
idx2.addField('title');
idx2.addField('body');
idx2.setRef('id');
console.log(idx.getFields()); // ['id', 'title', 'body']
```
--------------------------------
### Perform a Basic Search
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Execute a search query against the index to find matching documents.
```javascript
index.search("Oracle database profit");
```
--------------------------------
### Search with Query-Time Boosting
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Perform a search with query-time boosting to prioritize certain fields. Configure boost values for fields like 'title' and 'body'.
```javascript
index.search("Oracle database profit", {
fields: {
title: {boost: 2},
body: {boost: 1}
}
});
```
--------------------------------
### Configuration Query with Token Expansion
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Performs a search query with token expansion enabled, which can increase recall by including related terms. Expanded query results are penalized.
```APIDOC
## Configuration Query - Token Expansion
### Description
Performs a search query with token expansion enabled, which can increase recall by including related terms. Expanded query results are penalized because they are not exactly the same as the query token. Field-level expand configuration will overwrite global expand configuration.
### Method
`index.search(query, configuration)`
### Parameters
- **query** (String) - The search query string.
- **configuration** (Object) - Configuration object for search parameters.
- **fields** (Object) - An object where keys are field names and values are field-specific configurations.
- **fieldName** (Object) - Configuration for a specific field.
- **boost** (Number) - The boost weight for this field.
- **bool** (String) - The boolean logic ('AND' or 'OR') for this field.
- **expand** (Boolean) - Whether to enable token expansion for this field.
- **bool** (String) - The global boolean logic ('AND' or 'OR') for the query.
- **expand** (Boolean) - Whether to enable token expansion globally for the query.
### Request Example (Global Expand True)
```javascript
index.search("micro", {
fields: {
title: {boost: 2, bool: "AND"},
body: {boost: 1}
},
bool: "OR",
expand: true
});
```
### Request Example (Field-level Expand False, Global Expand True)
```javascript
index.search("micro", {
fields: {
title: {
boost: 2,
bool: "AND",
expand: false
},
body: {boost: 1}
},
bool: "OR",
expand: true
});
```
```
--------------------------------
### Add Documents to the Index
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Prepare documents in JSON format and add them to the index. Fields not configured in the index will not be searchable.
```javascript
var doc1 = {
"id": 1,
"title": "Oracle released its latest database Oracle 12g",
"body": "Yesterday Oracle has released its new database Oracle 12g, this would make more money for this company and lead to a nice profit report of annual year."
}
var doc2 = {
"id": 2,
"title": "Oracle released its profit report of 2015",
"body": "As expected, Oracle released its profit report of 2015, during the good sales of database and hardware, Oracle's profit of 2015 reached 12.5 Billion."
}
index.addDoc(doc1);
index.addDoc(doc2);
```
--------------------------------
### Advanced Search with Boosting and Boolean Logic
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Use `index.search(query, options)` for advanced search control. Specify field boosts, Boolean logic ('OR'/'AND'), and token expansion. Field-level settings override global ones.
```javascript
// Boost title matches 3× over body, require AND match in title
const results = idx.search('Oracle profit', {
fields: {
title: { boost: 3, bool: 'AND' },
body: { boost: 1, bool: 'OR' }
},
bool: 'OR',
expand: false
});
console.log(results);
// [ { ref: '2', score: ..., positions: { ... } } ]
// Token expansion: 'profit' also matches 'profitable', 'profits', etc.
const expandedResults = idx.search('profit', {
fields: { title: { boost: 2 }, body: { boost: 1 } },
expand: true
});
```
--------------------------------
### Advanced Search with Options
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
The `index.search(query, options)` method allows for advanced search configurations, including query-time boosting for specific fields, Boolean logic (`AND`/`OR`), and token expansion to match variations of search terms.
```APIDOC
## `index.search(query, options)` — Query-Time Boosting and Boolean Model
Passes a configuration object as the second argument to control which fields are searched, their relative boost weights, Boolean logic (`"OR"` / `"AND"`), and token expansion. Field-level settings override global ones.
```javascript
// Boost title matches 3× over body, require AND match in title
const results = idx.search('Oracle profit', {
fields: {
title: { boost: 3, bool: 'AND' },
body: { boost: 1, bool: 'OR' }
},
bool: 'OR',
expand: false
});
console.log(results);
// [ { ref: '2', score: ..., positions: { ... } } ]
// Token expansion: 'profit' also matches 'profitable', 'profits', etc.
const expandedResults = idx.search('profit', {
fields: { title: { boost: 2 }, body: { boost: 1 } },
expand: true
});
```
```
--------------------------------
### Create Index Without Storing Documents
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Initialize an index and configure it not to store original JSON documents to reduce index size. This setting impacts document update and deletion capabilities.
```javascript
var index = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
this.saveDocument(false);
});
```
```javascript
var index = elasticlunr();
index.addField('title');
index.addField('body');
index.setRef('id');
index.saveDocument(false);
```
--------------------------------
### Search with Token Expansion Enabled
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Enables token expansion for queries, which broadens the search to include related terms and increases recall. Results from expanded tokens are penalized to reflect their lower relevance.
```javascript
index.search("micro", {
fields: {
title: {boost: 2, bool: "AND"},
body: {boost: 1}
},
bool: "OR",
expand: true
});
```
--------------------------------
### Include Language Support Scripts in Browser
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Include the necessary JavaScript files for language support in a browser environment. Ensure lunr.stemmer.support.js and the specific language file (e.g., lunr.de.js) are included.
```html
```
--------------------------------
### Simple String Search with Elasticlunr.js
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Perform a basic search using `index.search(query)`. Results are sorted by descending relevance score and include the document reference (`ref`) and `score`. An empty array is returned if no matches are found.
```javascript
const results = idx.search('Oracle database profit');
console.log(results);
// [
// { ref: '1', score: 0.643, positions: { title: [...], body: [...] } },
// { ref: '2', score: 0.521, positions: { title: [...], body: [...] } }
// ]
// Search returns an empty array when nothing matches
console.log(idx.search('kubernetes')); // []
```
--------------------------------
### Multi-Language Support with lunr-languages (Node.js)
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Integrate language-specific stemmers and stop-word filters using the `lunr-languages` package. Activate language support by calling `this.use()` within the index configuration.
```javascript
const elasticlunr = require('elasticlunr');
require('./lunr.stemmer.support.js')(elasticlunr);
require('./lunr.de.js')(elasticlunr);
const idx = elasticlunr(function () {
this.use(elasticlunr.de);
this.addField('title');
this.addField('body');
this.setRef('id');
});
idx.addDoc({ id: 1, title: 'Datenbankveröffentlichung', body: 'Oracle hat eine neue Datenbank veröffentlicht.' });
const results = idx.search('Datenbank');
console.log(results);
```
--------------------------------
### Simple Query
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Performs a simple search query using a string. The results are returned as an array of objects, each containing a `ref` and `score`.
```APIDOC
## Simple Query
### Description
Performs a simple search query using a string. The results are returned as an array of objects, each containing a `ref` and `score`, sorted by score in descending order.
### Method
`index.search(query)`
### Parameters
- **query** (String) - The search query string.
### Request Example
```javascript
index.search("Oracle database profit");
```
### Response
#### Success Response (Array)
- **ref** (String) - The document reference.
- **score** (Number) - The similarity measurement.
Results array is sorted descent by `score`.
```
--------------------------------
### Configuration Query with Boolean Model
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Performs a search query using a specified boolean logic (OR/AND) for combining results. Defaults to 'OR' if not specified.
```APIDOC
## Configuration Query - Boolean Model
### Description
Performs a search query using a specified boolean logic (OR/AND) for combining results. Defaults to 'OR' if not specified. Boolean logic can be set globally or at the field level, with field-level settings overriding global ones.
### Method
`index.search(query, configuration)`
### Parameters
- **query** (String) - The search query string.
- **configuration** (Object) - Configuration object for search parameters.
- **fields** (Object) - An object where keys are field names and values are field-specific configurations.
- **fieldName** (Object) - Configuration for a specific field.
- **boost** (Number) - The boost weight for this field.
- **bool** (String) - The boolean logic ('AND' or 'OR') for this field.
- **bool** (String) - The global boolean logic ('AND' or 'OR') for the query.
### Request Example (Global OR)
```javascript
index.search("Oracle database profit", {
fields: {
title: {boost: 2},
body: {boost: 1}
},
bool: "OR"
});
```
### Request Example (Field-level AND, Global OR)
```javascript
index.search("Oracle database profit", {
fields: {
title: {boost: 2, bool: "AND"},
body: {boost: 1}
},
bool: "OR"
});
```
```
--------------------------------
### Save Index Snippet for JSON
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
This snippet specifically shows how the index is stringified and written to a file, highlighting the use of JSON.stringify.
```javascript
fs.writeFile('./example/example_index.json', JSON.stringify(idx), function (err) {
if (err) throw err;
console.log('done');
});
```
--------------------------------
### Specify Language Support in elasticlunr.js
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
This line demonstrates how to integrate language-specific features into an elasticlunr.js index. Replace 'elasticlunr.de' with the appropriate language object (e.g., elasticlunr.es for Spanish).
```javascript
this.use(elasticlunr.de);
```
--------------------------------
### JSON.stringify(idx) / elasticlunr.Index.load(data)
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Serializes the complete index to JSON for persistence and loads it back from a parsed JSON object without rebuilding from source documents.
```APIDOC
## `JSON.stringify(idx)` / `elasticlunr.Index.load(data)` — Serialization and Loading
Serializes the complete index (fields, inverted index, pipeline references) to JSON for persistence. Load it back from a parsed JSON object without rebuilding from source documents.
### Example Usage:
```javascript
const fs = require('fs');
// Build and save
const buildIdx = elasticlunr(function () {
this.setRef('id');
this.addField('title');
this.addField('body');
});
[
{ id: 1, title: 'Oracle database 12g', body: 'Released yesterday.' },
{ id: 2, title: 'Oracle profit 2015', body: 'Reached 12.5 Billion.' }
].forEach((doc) => buildIdx.addDoc(doc));
fs.writeFileSync('./search-index.json', JSON.stringify(buildIdx));
// Later: load without rebuilding
const raw = JSON.parse(fs.readFileSync('./search-index.json', 'utf8'));
const loadedIdx = elasticlunr.Index.load(raw);
console.log(loadedIdx.search('database'));
// [{ ref: '1', score: ..., positions: {...} }]
```
```
--------------------------------
### index.on(event, handler) / index.off(event, handler)
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Subscribes to or unsubscribes from index mutation events: 'add', 'update', and 'remove'. Handlers receive the affected document and the index instance.
```APIDOC
## `index.on(event, handler)` / `index.off(event, handler)` — Index Events
Subscribes to or unsubscribes from index mutation events: `'add'`, `'update'`, and `'remove'`. Handlers receive the affected document and the index instance.
### Example Usage:
```javascript
idx.on('add', function (doc, index) {
console.log('Document added:', doc.id);
});
idx.on('update', function (doc, index) {
console.log('Document updated:', doc.id);
});
idx.on('remove', function (docRef, index) {
console.log('Document removed:', docRef);
});
idx.addDoc({ id: 99, title: 'New entry', body: 'Content here.' });
// → "Document added: 99"
idx.off('add'); // unsubscribe
```
```
--------------------------------
### Custom Pipeline Functions
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
The pipeline is an ordered queue of functions applied to tokens during both indexing and querying. Custom functions can be added before or after existing ones, or default functions can be removed entirely.
```APIDOC
## `index.pipeline`
### Description
The pipeline is an ordered queue of functions applied to tokens during both indexing and querying. Custom functions can be added before or after existing ones, or default functions can be removed entirely.
### Methods
- `elasticlunr.Pipeline.registerFunction(fn, label)`: Registers a custom pipeline function.
- `pipeline.add(fn)`: Adds a custom function to the end of the pipeline.
- `pipeline.before(existingFn, newFn)`: Inserts a new function before an existing one.
- `pipeline.remove(fn)`: Removes a function from the pipeline.
- `pipeline.get()`: Returns the current pipeline functions.
### Example
```javascript
// Register a custom pipeline function (required for serialization)
var myCustomFilter = function (token) {
// Discard tokens shorter than 3 characters
if (token && token.toString().length < 3) return null;
return token;
};
elasticlunr.Pipeline.registerFunction(myCustomFilter, 'minLengthFilter');
const idx = elasticlunr(function () {
this.addField('title');
this.setRef('id');
// Add custom filter after the stemmer
this.pipeline.add(myCustomFilter);
});
// Insert before an existing stage
idx.pipeline.before(elasticlunr.stemmer, myCustomFilter);
// Remove a default stage (e.g. disable stemming)
idx.pipeline.remove(elasticlunr.stemmer);
// Inspect the current pipeline
console.log(idx.pipeline.get()); // [trimmer, stopWordFilter, myCustomFilter]
```
```
--------------------------------
### Per-Field Query Object Search
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
You can use `index.search(query)` with a plain object as the query to specify different search terms for different fields simultaneously, enabling more targeted searches.
```APIDOC
## `index.search(query)` — Per-Field Query Object
Passes a plain object (not a string) as the query to supply different search terms for different fields simultaneously.
```javascript
// Search 'database' only in title, 'profit' only in body
const results = idx.search({
title: 'database',
body: 'profit'
});
console.log(results);
// [ { ref: '2', score: ..., positions: { ... } } ]
```
```
--------------------------------
### index.updateDoc(doc)
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Replaces an existing document in the index with new content by removing the old version's tokens and re-indexing the new version.
```APIDOC
## `index.updateDoc(doc)` — Updating a Document
Replaces an existing document in the index with new content. Internally removes all tokens for the old version and re-indexes the new version.
### Example Usage:
```javascript
idx.updateDoc({
id: 1,
title: 'Oracle released Oracle 12g database with new features',
body: 'Oracle 12g includes advanced partitioning, in-memory options, and multitenant architecture.'
});
const results = idx.search('multitenant');
console.log(results); // [{ ref: '1', score: ... }]
```
```
--------------------------------
### Serialize and Load Index
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Serializes the index to JSON for persistence and loads it back without rebuilding. This is useful for saving and restoring index state.
```javascript
const fs = require('fs');
// Build and save
const buildIdx = elasticlunr(function () {
this.setRef('id');
this.addField('title');
this.addField('body');
});
[
{ id: 1, title: 'Oracle database 12g', body: 'Released yesterday.' },
{ id: 2, title: 'Oracle profit 2015', body: 'Reached 12.5 Billion.' }
].forEach((doc) => buildIdx.addDoc(doc));
fs.writeFileSync('./search-index.json', JSON.stringify(buildIdx));
// Later: load without rebuilding
const raw = JSON.parse(fs.readFileSync('./search-index.json', 'utf8'));
const loadedIdx = elasticlunr.Index.load(raw);
console.log(loadedIdx.search('database'));
// [{ ref: '1', score: ..., positions: {...} }]
```
--------------------------------
### Save elasticlunr.js Index to JSON
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Build an index and save it to a JSON file for later use. This involves reading data, processing it, adding to the index, and then writing the stringified index to a file.
```javascript
var elasticlunr = require('./elasticlunr.js'),
fs = require('fs');
var idx = elasticlunr(function () {
this.setRef('id');
this.addField('title');
this.addField('tags');
this.addField('body');
});
fs.readFile('./example/example_data.json', function (err, data) {
if (err) throw err;
var raw = JSON.parse(data);
var questions = raw.questions.map(function (q) {
return {
id: q.question_id,
title: q.title,
body: q.body,
tags: q.tags.join(' ')
};
});
questions.forEach(function (question) {
idx.addDoc(question);
});
fs.writeFile('./example/example_index.json', JSON.stringify(idx), function (err) {
if (err) throw err;
console.log('done');
});
});
```
--------------------------------
### Simple String Search
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
The `index.search(query)` method performs a simple text search across all indexed fields. Results are returned sorted by descending relevance score, with each result including a `ref` and `score`.
```APIDOC
## `index.search(query)` — Simple String Search
Searches all indexed fields with the provided query string. Results are sorted by descending relevance score. Each result contains a `ref` (the document's reference key) and a `score`.
```javascript
const results = idx.search('Oracle database profit');
console.log(results);
// [
// { ref: '1', score: 0.643, positions: { title: [...], body: [...] } },
// { ref: '2', score: 0.521, positions: { title: [...], body: [...] } }
// ]
// Search returns an empty array when nothing matches
console.log(idx.search('kubernetes')); // []
```
```
--------------------------------
### Display Search Results
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
The search results are returned as a list of matching documents, each with a 'ref' and a 'score' indicating relevance.
```javascript
[{
"ref": 1,
"score": 0.5376053707962494
},
{
"ref": 2,
"score": 0.5237481076838757
}]
```
--------------------------------
### index.elasticsearch(query)
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Executes a structured query using an Elasticsearch-compatible JSON DSL. Supports various query types like bool, match, match_all, terms, and not, with options for boosting and fuzziness.
```APIDOC
## `index.elasticsearch(query)` — Elasticsearch-Compatible DSL
Executes a structured query using an Elasticsearch-compatible JSON DSL. Supports `bool`, `match`, `match_all`, `terms`, and `not` query types with `should`, `must`, `must_not`, `filter`, `fuzziness`, and `minimum_should_match`.
### Example Usage:
```javascript
// bool/should — OR across multiple match clauses with boosting
const results = idx.elasticsearch({
query: {
bool: {
should: [
{ match: { title: 'Oracle' }, boost: 3 },
{ match: { body: 'profit' }, boost: 1 }
]
}
}
});
// must + must_not
const filtered = idx.elasticsearch({
query: {
bool: {
must: { match: { title: 'Oracle' } },
must_not: { match: { title: 'Chrome' } }
}
}
});
// Fuzzy match (fuzziness = edit distance)
const fuzzy = idx.elasticsearch({
query: {
match: { title: 'Orcale', fuzziness: 1 } // matches 'Oracle'
}
});
// terms — exact token list
const termsResult = idx.elasticsearch({
query: {
terms: { title: ['oracle', 'database'] }
}
});
console.log(results); // [{ ref: '1', score: ..., positions: {...} }, ...]
```
```
--------------------------------
### Handle Index Events
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Subscribes to or unsubscribes from index mutation events ('add', 'update', 'remove'). Handlers receive the affected document and the index instance.
```javascript
idx.on('add', function (doc, index) {
console.log('Document added:', doc.id);
});
idx.on('update', function (doc, index) {
console.log('Document updated:', doc.id);
});
idx.on('remove', function (docRef, index) {
console.log('Document removed:', docRef);
});
idx.addDoc({ id: 99, title: 'New entry', body: 'Content here.' });
// → "Document added: 99"
idx.off('add'); // unsubscribe
```
--------------------------------
### index.saveDocument(bool)
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Controls whether the original JSON documents are stored in the index. Disabling storage reduces index size but prevents using `highlight()` and retrieving original documents.
```APIDOC
## `index.saveDocument(bool)` — Controlling Document Storage
Toggles whether the original JSON documents are stored in the index alongside their tokens. Disabling storage reduces index size significantly but prevents using `highlight()` and retrieving original documents.
### Example Usage:
```javascript
const compactIdx = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
this.saveDocument(false); // do not store raw documents
});
compactIdx.addDoc({ id: 1, title: 'Oracle database', body: 'Details...' });
// Index is smaller; highlight() will throw if called on results
```
```
--------------------------------
### Per-Field Query Object Search
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Provide a query object to `index.search()` to specify different search terms for different fields simultaneously. This allows for more granular control over search criteria.
```javascript
// Search 'database' only in title, 'profit' only in body
const results = idx.search({
title: 'database',
body: 'profit'
});
console.log(results);
// [ { ref: '2', score: ..., positions: { ... } } ]
```
--------------------------------
### Execute Elasticsearch-Compatible Queries
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Use this function to perform structured queries using an Elasticsearch-compatible JSON DSL. It supports various query types and clauses for flexible searching.
```javascript
const results = idx.elasticsearch({
query: {
bool: {
should: [
{ match: { title: 'Oracle' }, boost: 3 },
{ match: { body: 'profit' }, boost: 1 }
]
}
}
});
```
```javascript
const filtered = idx.elasticsearch({
query: {
bool: {
must: { match: { title: 'Oracle' } },
must_not: { match: { title: 'Chrome' } }
}
}
});
```
```javascript
const fuzzy = idx.elasticsearch({
query: {
match: { title: 'Orcale', fuzziness: 1 } // matches 'Oracle'
}
});
```
```javascript
const termsResult = idx.elasticsearch({
query: {
terms: { title: ['oracle', 'database'] }
}
});
```
--------------------------------
### Load elasticlunr.js Index from JSON
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Load a previously persisted index from a JSON string. The JSON string is parsed, and then elasticlunr.Index.load is used to reconstruct the index object.
```javascript
var indexDump = JSON.parse(indexDump)
console.time('load')
window.idx = elasticlunr.Index.load(indexDump)
```
--------------------------------
### Highlight Search Results
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Generates a highlighter function to wrap matched terms in specified tags. This requires the document reference and a positions map from search results. Overlapping ranges are merged automatically.
```javascript
const results = idx.search('Oracle database');
if (results.length > 0) {
const top = results[0];
const highlighter = idx.highlight(top.ref, top.positions);
// Wrap matched spans in tags
const highlighted = highlighter('', '');
console.log(highlighted.title);
// "Oracle released its latest database Oracle 12g"
console.log(highlighted.body);
// "Oracle has released its new database Oracle 12g..."
}
```
--------------------------------
### Search with Boolean OR Logic
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Applies the 'OR' boolean logic to search queries, which defaults to 'OR' if not specified. This setting maximizes recall by including documents that match any of the query terms.
```javascript
index.search("Oracle database profit", {
fields: {
title: {boost: 2},
body: {boost: 1}
},
bool: "OR"
});
```
--------------------------------
### Use Spanish Language Support in elasticlunr.js
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
To use Spanish language support, include 'lunr.es.js' and change the use statement to 'this.use(elasticlunr.es);'. This follows the pattern for integrating other language stemmers and tokenizers.
```javascript
this.use(elasticlunr.es);
```
--------------------------------
### Control Document Storage
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Toggles whether original documents are stored. Disabling storage reduces index size but prevents using `highlight()` and retrieving original documents.
```javascript
const compactIdx = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
this.saveDocument(false); // do not store raw documents
});
compactIdx.addDoc({ id: 1, title: 'Oracle database', body: 'Details...' });
// Index is smaller; highlight() will throw if called on results
```
--------------------------------
### Stop Word Management
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Manages the English stop-word list used during tokenization. Words in the stop list are excluded from the index and from queries. Custom lists can be added or the defaults replaced entirely.
```APIDOC
## `elasticlunr.clearStopWords()` / `elasticlunr.addStopWords(words)` / `elasticlunr.resetStopWords()`
### Description
Manages the English stop-word list used during tokenization. Words in the stop list are excluded from the index and from queries. Custom lists can be added or the defaults replaced entirely.
### Methods
- `elasticlunr.clearStopWords()`: Removes all default English stop words.
- `elasticlunr.addStopWords(words)`: Adds a custom domain-specific stop list.
- `elasticlunr.resetStopWords()`: Restores the default stop words.
### Example
```javascript
// Remove all 120 default English stop words
elasticlunr.clearStopWords();
// Add a custom domain-specific stop list
elasticlunr.addStopWords(['oracle', 'released', 'new']);
// Restore defaults
elasticlunr.resetStopWords();
```
```
--------------------------------
### index.highlight(ref, positions)
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Given a document reference and a positions map, returns a function that wraps matched terms in specified tags, automatically merging overlapping ranges.
```APIDOC
## `index.highlight(ref, positions)` — Result Highlighting
Given a document reference and a positions map (as returned in search results), returns a function that wraps matched terms in any start/end tags, merging overlapping ranges automatically.
### Example Usage:
```javascript
const results = idx.search('Oracle database');
if (results.length > 0) {
const top = results[0];
const highlighter = idx.highlight(top.ref, top.positions);
// Wrap matched spans in tags
const highlighted = highlighter('', '');
console.log(highlighted.title);
// "Oracle released its latest database Oracle 12g"
console.log(highlighted.body);
// "Oracle has released its new database Oracle 12g..."
}
```
```
--------------------------------
### Field-Specific Search
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Query on different terms for each field by providing an object where keys are field names and values are search terms.
```javascript
index.search({
title: 'database',
body: 'profit',
});
```
--------------------------------
### Add Customized Stop Words
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Add a list of custom stop words to the index. Ensure the array is defined before calling this function.
```javascript
var customized_stop_words = ['an', 'hello', 'xyzabc'];
elasticlunr.addStopWords(customized_stop_words);
```
--------------------------------
### Add Custom Pipeline Functions in Elasticlunr.js
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Register and add custom functions to the token processing pipeline for both indexing and querying. Custom functions must be registered before being added to the pipeline.
```javascript
var myCustomFilter = function (token) {
if (token && token.toString().length < 3) return null;
return token;
};
elasticlunr.Pipeline.registerFunction(myCustomFilter, 'minLengthFilter');
const idx = elasticlunr(function () {
this.addField('title');
this.setRef('id');
this.pipeline.add(myCustomFilter);
});
idx.pipeline.before(elasticlunr.stemmer, myCustomFilter);
idx.pipeline.remove(elasticlunr.stemmer);
console.log(idx.pipeline.get());
```
--------------------------------
### Multi-Language Support
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Elasticlunr.js supports non-English languages by integrating with the `lunr-languages` package, which provides language-specific stemmers and stop-word filters.
```APIDOC
## Multi-Language Support with `lunr-languages`
### Description
Elasticlunr.js supports non-English languages by integrating with the `lunr-languages` package, which provides language-specific stemmers and stop-word filters.
### Usage
1. Include the necessary language support files (e.g., `lunr.stemmer.support.js`, `lunr.de.js`).
2. Use `elasticlunr.use(language)` within your index configuration.
### Example (Node.js - German)
```javascript
const elasticlunr = require('elasticlunr');
require('./lunr.stemmer.support.js')(elasticlunr);
require('./lunr.de.js')(elasticlunr);
const idx = elasticlunr(function () {
this.use(elasticlunr.de); // activate German language support
this.addField('title');
this.addField('body');
this.setRef('id');
});
idx.addDoc({ id: 1, title: 'Datenbankveröffentlichung', body: 'Oracle hat eine neue Datenbank veröffentlicht.' });
const results = idx.search('Datenbank');
console.log(results); // [{ ref: '1', score': ... }]
```
### Example (Browser)
```html
```
```
--------------------------------
### Manage Stop Words in Elasticlunr.js
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Control the list of stop words excluded from indexing and queries. Custom lists can be added or defaults replaced.
```javascript
elasticlunr.clearStopWords();
elasticlunr.addStopWords(['oracle', 'released', 'new']);
elasticlunr.resetStopWords();
const idx = elasticlunr(function () {
this.addField('title');
this.setRef('id');
});
idx.addDoc({ id: 1, title: 'Oracle released a new database product' });
```
--------------------------------
### Update Document in Index
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Updates a document in the index by providing the JSON document object. This is equivalent to removing the old document and adding a new one with the same ID.
```javascript
var doc = {
"id": 1,
"title": "Oracle released its latest database Oracle 12g",
"body": "Yestaday Oracle has released its new database Oracle 12g, this would make more money for this company and lead to a nice profit report of annual year."
}
index.updateDoc(doc);
```
--------------------------------
### Update Document in Index
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Replaces an existing document by its ID. This operation removes all tokens for the old version and re-indexes the new content.
```javascript
idx.updateDoc({
id: 1,
title: 'Oracle released Oracle 12g database with new features',
body: 'Oracle 12g includes advanced partitioning, in-memory options, and multitenant architecture.'
});
const results = idx.search('multitenant');
console.log(results); // [{ ref: '1', score: ... }]
```
--------------------------------
### Update Document
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Updates a document in the index by providing the JSON document object to the `updateDoc` function.
```APIDOC
## Update Document in Index
### Description
Updates a document in the index by providing the JSON document object to the `elasticlunr.Index.prototype.updateDoc()` function.
### Method
`index.updateDoc(doc)`
### Parameters
- **doc** (Object) - The JSON document object to update.
### Request Example
```javascript
var doc = {
"id": 1,
"title": "Oracle released its latest database Oracle 12g",
"body": "Yestaday Oracle has released its new database Oracle 12g, this would make more money for this company and lead to a nice profit report of annual year."
}
index.updateDoc(doc);
```
```
--------------------------------
### Search with Field-Level Boolean AND Logic
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Overrides the global boolean logic for specific fields, using 'AND' for the 'title' field while maintaining 'OR' for others. Field-level settings take precedence over global settings.
```javascript
index.search("Oracle database profit", {
fields: {
title: {boost: 2, bool: "AND"},
body: {boost: 1}
},
bool: "OR"
});
```
--------------------------------
### Custom Tokenizer Separator
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Overrides the default whitespace/hyphen token separator with a custom regular expression. Useful for indexing languages or formats with different word boundaries.
```APIDOC
## `elasticlunr.tokenizer.setSeperator(sep)`
### Description
Overrides the default whitespace/hyphen token separator with a custom regular expression. Useful for indexing languages or formats with different word boundaries.
### Method
`elasticlunr.tokenizer.setSeperator(sep)`: Sets a custom regular expression for token separation.
### Parameters
- **sep** (RegExp) - The regular expression to use as a separator.
### Example
```javascript
// Split on whitespace, hyphens, underscores, and dots
elasticlunr.tokenizer.setSeperator(/[
!-/:-@[-`{-~ -
-
-_.]+/g);
const tokens = elasticlunr.tokenizer('full_text.search-engine');
console.log(tokens.map(t => t.toString())); // ['full', 'text', 'search', 'engine']
// Reset to default (splits on whitespace and hyphens)
elasticlunr.tokenizer.resetSeperator();
```
```
--------------------------------
### index.removeDoc(doc)
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Removes a document from the index by providing its full JSON object, using the reference field to locate it.
```APIDOC
## `index.removeDoc(doc)` — Removing a Document
Removes a document from the index by providing its full JSON object (the reference field is used to locate it).
### Example Usage:
```javascript
idx.removeDoc({ id: 3, title: 'Google releases Chrome 100', body: '...' });
console.log(idx.documentStore.length); // 2
console.log(idx.search('Chrome')); // []
```
```
--------------------------------
### Search with Field-Level Token Expansion Disabled
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Disables token expansion for a specific field ('title') while keeping it enabled globally. Field-level configurations for expansion override global settings.
```javascript
index.search("micro", {
fields: {
title: {
boost: 2,
bool: "AND",
expand: false
},
body: {boost: 1}
},
bool: "OR",
expand: true
});
```
--------------------------------
### Customize Tokenizer Separator in Elasticlunr.js
Source: https://context7.com/weixsong/elasticlunr.js/llms.txt
Override the default token separator with a custom regular expression to handle different word boundary rules. Resets to default behavior when called without arguments.
```javascript
elasticlunr.tokenizer.setSeperator(/[
\s\-_"]+/g);
const tokens = elasticlunr.tokenizer('full_text.search-engine');
console.log(tokens.map(t => t.toString()));
elasticlunr.tokenizer.resetSeperator();
```
--------------------------------
### Clear Default Stop Words
Source: https://github.com/weixsong/elasticlunr.js/blob/master/README.md
Call this function to remove all default English stop words from the index.
```javascript
elasticlunr.clearStopWords();
```