Tutorial: Semantic Search

A small script that stores short texts with their embeddings and answers questions by meaning rather than by keywords. It uses all-MiniLM-L6-v2 in-process, so it needs only Node.js and a running DianaDB server.

1. Set up

mkdir semantic-search && cd semantic-search
npm init -y && npm pkg set type=module
npm i @diana-db/odm @huggingface/transformers

2. Model and embedding function

Create search.js:

import { DianaDb, Model, Types } from '@diana-db/odm';
import { pipeline } from '@huggingface/transformers';

const extract = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
const embed = async (texts) => (await extract(texts, { pooling: 'mean', normalize: true })).tolist();

const dianaDb = new DianaDb('diana-db://admin:password@localhost:34567');
await dianaDb.connect(5000);

const noteModel = new Model({
  database: 'tutorial',
  collection: 'notes',
  name: 'Note',
  schema: {
    topic: { type: Types.STRING, required: true },
    text: { type: Types.STRING, required: true },
    embedding: { type: Types.VECTOR, dimensions: 384, required: true },
  },
});
await noteModel.init();

3. Store the texts

const notes = [
  ['cooking', 'Knead the dough until smooth and let it rise for an hour.'],
  ['cooking', 'Simmer the tomato sauce for twenty minutes, then add fresh basil.'],
  ['databases', 'The write-ahead log lets the database recover after a crash.'],
  ['databases', 'An index speeds up lookups at the cost of slower writes.'],
  ['football', 'The goalkeeper saved a penalty in extra time.'],
  ['football', 'The midfielder was booked for a late tackle.'],
  ['space', 'The probe used a gravity assist to reach Jupiter.'],
  ['space', 'The rover collected rock samples from the crater floor.'],
];

await noteModel.remove([{}]); // start clean on every run
const vectors = await embed(notes.map(([, text]) => text));
for (const [i, [topic, text]] of notes.entries()) {
  await noteModel.insert({ topic, text, embedding: vectors[i] });
}

4. Ask questions

const questions = ['How do I make bread at home?', 'How does a database survive a power failure?', 'Which player got a yellow card?'];

for (const question of questions) {
  const [vector] = await embed([question]);
  const found = await noteModel.find([{ embedding: { $neighbors: { vector, count: 2, metric: 'cosine' } } }]);
  console.log(question);
  for (const note of found) console.log(`  ${note.topic}: ${note.text}`);
}

// everything about the power-failure question that is similar enough
const [vector] = await embed(['How does a database survive a power failure?']);
const related = await noteModel.find([{ embedding: { $direction: { vector, minSimilarity: 0.3 } } }]);
console.log(`${related.length} related notes`);

await dianaDb.disconnect();
node search.js

None of the questions shares a keyword with its answer ("bread" and "dough", "power failure" and "crash", "yellow card" and "booked"), yet the nearest notes come from the right topic.

Next steps