Generating Embeddings

DianaDB stores and searches vectors; it does not create them. An embedding model turns text (or images) into a vector, and texts with similar meaning get vectors pointing in similar directions. Use the same model for the stored documents and for the queries.

Choosing a model

ModelRunsdimensions
all-MiniLM-L6-v2In Node.js, through @huggingface/transformers384
nomic-embed-textLocally, through Ollama768
text-embedding-3-smallOpenAI API1536

The field's dimensions must equal the model's output size. Switching to a model with another size means a new field (or collection) and embedding the documents again.

In-process: Transformers.js

No server and no API key; the model (about 25 MB) is downloaded on first use.

npm i @huggingface/transformers
import { pipeline } from '@huggingface/transformers';

const extract = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');

async function embed(texts) {
  const output = await extract(texts, { pooling: 'mean', normalize: true });
  return output.tolist(); // one array of 384 numbers per text
}

Local server: Ollama

ollama pull nomic-embed-text
async function embed(texts) {
  const response = await fetch('http://localhost:11434/api/embed', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ model: 'nomic-embed-text', input: texts }),
  });
  if (!response.ok) throw new Error(`ollama: ${response.status}`);
  return (await response.json()).embeddings; // 768 numbers per text
}

Hosted API: OpenAI

async function embed(texts) {
  const response = await fetch('https://api.openai.com/v1/embeddings', {
    method: 'POST',
    headers: { 'content-type': 'application/json', authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
    body: JSON.stringify({ model: 'text-embedding-3-small', input: texts }),
  });
  if (!response.ok) throw new Error(`openai: ${response.status}`);
  return (await response.json()).data.map((item) => item.embedding); // 1536 numbers per text
}

Tips

  • Embed in batches: all three APIs above take an array of texts.
  • Use metric: 'cosine' for text embeddings, unless the model's documentation says otherwise.
  • Long documents: split them into chunks of a few paragraphs and store one document per chunk, with a field pointing to the source.
  • Store the text (or a reference to it) next to the vector: a vector can't be turned back into the text.
  • Some models expect a prefix that tells queries from documents (for example search_query: and search_document: for nomic-embed-text). Follow the model's documentation.