Introduction to Elasticlunr
Elasticlunr is a lightweight, full-text search engine for use in the browser and in Node.js applications. It provides a simple API and is designed for small to medium datasets. Here, we’ll explore its features and showcase various API examples.
Getting Started
First, you need to include Elasticlunr in your project. You can install it using npm:
npm install elasticlunr
Or include it in your HTML file directly from a CDN:
<script src="https://cdn.jsdelivr.net/npm/elasticlunr@0.9.6/elasticlunr.js"></script>
Creating an Index
Creating an index in Elasticlunr is straightforward. Here’s how you can create a new index and add documents to it:
var index = elasticlunr(function () {
this.addField('title');
this.addField('body');
this.setRef('id');
});
index.addDoc({
id: 1,
title: 'Introduction to Elasticlunr',
body: 'Elasticlunr is a lightweight search engine.'
});
index.addDoc({
id: 2,
title: 'Advanced Guide to Elasticlunr',
body: 'Learn advanced techniques in Elasticlunr.'
});
Search for Documents
Once docs are indexed, you can perform searches:
var results = index.search('guide');
console.log(results);
Customizing Search
Elasticlunr allows you to customize your search index in several ways, including custom scoring and boosting:
index.addField('author');
index.addDoc({
id: 3,
title: 'Learning Elasticlunr',
body: 'This is a tutorial on using Elasticlunr.',
author: 'John Doe'
});
var customResults = index.search('Elasticlunr', {
fields: {
title: { boost: 2 },
body: { boost: 1 }
},
expand: true
});
console.log(customResults);
Building a Simple Search App
Here’s an example of a simple search application using Elasticlunr:
// HTML
<input type="text" id="searchBox" placeholder="Enter search term...">
<div id="results"></div>
// JavaScript
document.getElementById('searchBox').addEventListener('input', function() {
var query = this.value;
var results = index.search(query);
var resultContainer = document.getElementById('results');
resultContainer.innerHTML = '';
results.forEach(function(result) {
var doc = index.documentStore.getDoc(result.ref);
resultContainer.innerHTML += '<p>' + doc.title + ': ' + doc.body + '</p>';
});
});
With these examples, you can now integrate Elasticlunr smoothly into your web application to provide powerful and efficient search functionality.
Hash: c17f7954c236ac5d92c1ae3c4feeb293279e6d3463b85ec96ef1f9bfa1a4c98a