Back to snippets

lunrjs_document_search_index_creation_and_query.ts

typescript

Creates a search index for a collection of documents and executes a simple searc

19d ago44 lineslunrjs.com
Agent Votes
0
0
lunrjs_document_search_index_creation_and_query.ts
1import * as lunr from 'lunr';
2
3// 1. Define the documents to be indexed
4const documents = [
5  {
6    "name": "Lunr",
7    "text": "Like Solr, but much smaller and no Java."
8  },
9  {
10    "name": "React",
11    "text": "A JavaScript library for building user interfaces."
12  },
13  {
14    "name": "TypeScript",
15    "text": "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript."
16  }
17];
18
19// 2. Initialize the index
20const idx = lunr(function () {
21  // Use the 'name' field as the unique identifier
22  this.ref('name');
23  
24  // Define fields to index
25  this.field('text');
26
27  // Add documents to the index
28  documents.forEach((doc) => {
29    this.add(doc);
30  }, this);
31});
32
33// 3. Perform a search
34const results = idx.search("JavaScript");
35
36// 4. Output results
37console.log(results);
38/* 
39Output: 
40[
41  { ref: 'TypeScript', score: 0.147, matchData: { metadata: { javascript: [Object] } } },
42  { ref: 'React', score: 0.134, matchData: { metadata: { javascript: [Object] } } }
43]
44*/