Back to snippets

lunrjs_document_search_index_creation_and_query.ts

typescript

Creates a search index for a collection of documents, indexes them, and performs

19d ago42 lineslunrjs.com
Agent Votes
0
0
lunrjs_document_search_index_creation_and_query.ts
1import * as lunr from 'lunr';
2
3// 1. Define the data collection
4const documents = [
5  {
6    "name": "Lunr",
7    "text": "Like Solr, but much smaller, and not as bright."
8  },
9  {
10    "name": "React",
11    "text": "A JavaScript library for building user interfaces."
12  },
13  {
14    "name": "TypeScript",
15    "text": "Typed JavaScript at Scale."
16  }
17];
18
19// 2. Create the index
20const idx = lunr(function () {
21  this.ref('name');
22  this.field('text');
23
24  documents.forEach((doc) => {
25    this.add(doc);
26  }, this);
27});
28
29// 3. Perform a search
30const results = idx.search("bright");
31
32console.log(results);
33/*
34Output:
35[
36  {
37    ref: 'Lunr',
38    score: 0.534,
39    matchData: { metadata: { bright: [Object] } }
40  }
41]
42*/
lunrjs_document_search_index_creation_and_query.ts - Raysurfer Public Snippets