Plugin Match Highlight
Learn how to use the match highlight plugin in ZBSearch.
Deprecated
This plugin is deprecated in favor of lighter alternatives that do not increase the memory footprint of your database.
The plugin-match-highlight plugin allows ZBSearch to keep track of all token positions on each property of each document.
Installation
You can install the plugin using any major Node.js package manager.
npm install @zbsearch/plugin-match-highlightUsage
Plugin usage depends on the runtime that you are using, even though the goal is to expose the exact same APIs for browsers, Deno, and all the other JavaScript engines.
The plugin exports afterInsertHook, which will be the hook used by ZBSearch to add positions, and searchWithHighlight which wraps the original ZBSearch's search function to return positions alongside docs.
import { create, insert } from "zbsearch";
import {
afterInsert as highlightAfterInsert,
searchWithHighlight,
} from "@zbsearch/plugin-match-highlight";
// Create a new ZBSearch instance
const db = create({
schema: {
text: "string",
},
plugins: [
// Register the hook
{
name: "highlight",
afterInsert: highlightAfterInsert,
},
],
});
// Insert a document
insert(db, { text: "hello world" });
// Use the plugin's searchWithHighlight function to query the database
const results = searchWithHighlight(db, { term: "hello" });This will add the positions property to each hit:
{
elapsed: {...},
count: ...,
hits: [
{
id: ...,
score: ...,
document: { text: 'hello world' },
positions: {
text: {
hello: [
{
start: 0,
length: 5
}
]
}
}
}
]
}Saving Database State with Highlights
ZBSearch exposes a save method, which is used to persist its state either in-memory or on disk.
By default, it doesn't save the highlights exposed by this plugin. If you need them, you can easily handle this case by using the saveWithHighlight and loadWithHighlight functions:
import { create, insert } from "zbsearch";
import {
afterInsert as highlightAfterInsert,
saveWithHighlight,
loadWithHighlight,
} from "@zbsearch/plugin-match-highlight";
const db = create({
schema: {
text: "string",
},
plugins: [
// Register the hook
{
name: "highlight",
afterInsert: highlightAfterInsert,
},
],
});
insert(db, { text: "hello world" });
const savedDB = await saveWithHighlight(db);
const restoredDB = await loadWithHighlight(savedDB);CommonJS Imports
ZBSearch plugins ship ESM modules by default. This allows us to move faster when providing new features and bug fixes, as well as using the "exports" field in package.json to provide a better developer experience.
CommonJS imports are still supported, but we suggest you to migrate to ESM.
TypeScript
Set moduleResolution in the compilerOptions in your tsconfig.json to be either Node16 or NodeNext.
When importing types, always refer to the standard import:
import { searchWithHighlight } from "@zbsearch/plugin-match-highlight";