Skip to main content
This tutorial covers the core vector similarity search workflow with Actian VectorAI DB. By the end, you will be able to:
  • Store and retrieve vectors using PointStruct, points.upsert, and points.search.
  • Control search behaviour with distance metrics, score thresholds, SearchParams, and pagination.
  • Fetch, count, and batch-search points using points.get, points.count, and search_batch.
Similarity search is the foundation of every vector database application. Instead of matching exact keywords, it finds items that are semantically close to a query. For example, “affordable flights to Europe” retrieves results about “cheap airfare to Paris” even though no words overlap. The workflow has four stages:
  1. Embed — Convert text, images, or audio into dense numerical vectors using a model.
  2. Store — Insert vectors with metadata into a collection.
  3. Search — Encode a query into the same vector space and find the nearest neighbors.
  4. Score — Rank results by distance (cosine, Euclidean, dot product, or Manhattan).

Environment setup

Run this command to install the two packages the tutorial depends on.

Step 1: Import and configure

Run this cell to import the SDK classes, set the server address and collection name, and load the embedding model. The two helper functions at the bottom are used throughout the tutorial to convert text into vectors.

Expected output

The cell prints the configured server address and confirms the embedding model loaded successfully with its dimensionality.

Step 2: Create a collection

Run this cell to create the collection that all subsequent steps will use. If the collection already exists, get_or_create returns without error.

Key parameters

The following parameters are passed to collections.get_or_create() to define the collection structure.

Distance metrics

Actian VectorAI DB supports four distance metrics. The choice is made at collection creation time and cannot be changed afterwards. Most text embedding models produce normalized vectors, making cosine the standard choice. The other metrics are useful in specialized scenarios covered later in this tutorial.

Expected output

A single confirmation line prints once the collection is created (or already exists).

Step 3: Embed and store vectors

Run this cell to embed all ten sample documents and store them as points in the collection. Each point has an integer ID, a 384-dimensional vector, and a payload containing the original text plus topic and difficulty metadata.

How it works

The ingestion pipeline converts raw text into vectors and stores them with metadata in a single batch operation.
  1. embed_texts() converts each document’s text into a 384-dimensional float vector using all-MiniLM-L6-v2.
  2. PointStruct(id, vector, payload) packages the ID, vector, and metadata together.
  3. points.upsert() inserts (or updates) the points in the collection.
  4. vde.flush() persists vectors to disk immediately.

Expected output

The count confirms all ten documents were stored successfully.
Run this cell to search the collection using a natural-language query. The function embeds the query string and returns the five most similar documents, each with its ID, cosine score, topic, and a text preview.

How it works

The search follows a three-step flow: encode, retrieve, rank.
  1. The query text is embedded into the same 384-dim vector space as the stored documents.
  2. points.search() finds the nearest vectors by cosine similarity.
  3. Results are returned as scored point objects, ranked by score (highest first for cosine).

Key parameters

The following parameters are accepted by points.search().

Expected output

The five closest documents are printed in score order. The top result is about neural networks, followed by transformers and machine learning — demonstrating that the search captured semantic relationships rather than exact keyword overlap.
The top result (id=2) is about neural networks — an exact topic match. The second result (id=6) is about transformers, which are a type of neural network. The third (id=1) is about machine learning more broadly. The search captures semantic relationships, not just keyword overlap.

Step 5: Understanding scores

The score value returned by each search result depends on the distance metric configured on the collection.

Cosine similarity

For cosine distance — the metric used in this tutorial — scores represent the cosine similarity between normalized vectors. When both the stored vectors and query vectors are unit-normalized (as produced by all-MiniLM-L6-v2), scores range from 0 to 1 and are interpreted as follows.

Comparing queries

Run this cell to issue three different queries against the collection and compare their score distributions. Each query will return three results with scores that reflect how closely the corpus matches that particular topic.

Expected output

Each query surfaces a different set of top results. The scores shift noticeably between topics, confirming that semantic relevance drives the ranking rather than surface-level word matching.
Each query surfaces the most semantically relevant documents, even when the exact words differ.

Step 6: Tune search accuracy with SearchParams

SearchParams controls how the HNSW index is traversed at query time. Adjusting these values lets you trade search speed for recall accuracy. Run this cell to compare the results of three search modes — low-effort approximate, high-effort approximate, and exact brute-force — against the same query.

SearchParams reference

All fields are optional. Omitting SearchParams entirely uses the collection’s default HNSW configuration. When a collection uses scalar or product quantization, use QuantizationSearchParams to control how quantized vectors are used during the search. The following example enables rescoring, which reranks the initial candidates using the original full-precision vectors for higher accuracy.

Step 7: Score threshold — filter low-confidence results

score_threshold discards results below a minimum similarity score server-side before they are returned. Run this cell to see how raising the threshold progressively narrows the result set for a deep-learning query.

When to use score thresholds

Choose a threshold based on how strictly the results need to match the query intent.

Expected output

The result counts drop as the threshold rises, and the strict pass returns only the two documents that score above 0.7.

Step 8: Pagination with offset and limit

For large result sets, use offset and limit to retrieve results one page at a time. Run this cell to walk through three pages of results for a programming query, with three results per page.

How pagination works

Each call advances the window by incrementing offset by limit. Results are always ranked by similarity score before the window is applied. offset skips the first N results and limit controls how many are returned per page.

Expected output

Three labeled pages print in sequence, each showing a different slice of the ranked result set.

Step 9: Retrieve points by ID

points.get retrieves specific points by their IDs without performing any vector similarity search. Run this cell to fetch points 0, 4, and 6 and print their topic and text.

Parameters

The following parameters control what points.get() returns alongside the point IDs.

Expected output

The three requested points are returned with their payload metadata. No vector data is included because with_vectors is set to False.

Step 10: Count points

points.count returns the number of points in a collection, with an option to apply a filter. Run this cell to count the total collection, an approximate count, and two filtered subsets.
The exact flag trades speed for accuracy. Choose based on whether the count needs to be precise.

Expected output

Both the exact and approximate counts return 10 for this small collection. The filtered counts confirm there are two deep learning documents and three beginner-level documents.

Step 11: Batch search — multiple queries in one call

search_batch sends up to 100 searches in a single gRPC round-trip, which eliminates per-request connection overhead. Run this cell to issue three different queries simultaneously and print their results side by side.

Why batch search matters

Sending multiple searches in a single call eliminates per-request connection overhead and reduces total latency significantly at scale. Each search in the batch can have its own vector, limit, filter, params, score_threshold, using, and offset. The results are returned in the same order as the input queries. Maximum batch size: 100 searches per call.

Expected output

All three queries return results in a single round-trip, each with its own ranked list.

Step 12: The universal query endpoint

points.query is a more powerful alternative to points.search. It supports vector search, payload ordering, server-side fusion, random sampling, and multistage prefetch — all through a single endpoint.

Vector search via points.query

Run this cell to perform a standard nearest-neighbour search using points.query. It produces the same ranked results as points.search but makes the full query feature set available.

Payload-sorted retrieval

Run this cell to retrieve points sorted by the difficulty payload field rather than by vector similarity. Passing an OrderBy object instead of a vector tells the endpoint to skip similarity computation entirely.

Multi-stage prefetch

Run this cell to run two filtered subsearches in parallel — one for machine learning documents and one for deep learning documents — and then rerank the merged candidate pool with a final similarity query, all in a single round-trip.

How prefetch works

Prefetch executes the filtered subsearches first, then merges their results for a final reranking pass.
  1. In the first stage, the engine fetches candidates matching the machine learning topic filter.
  2. In the second stage, the engine fetches candidates matching the deep learning topic filter.
  3. In the final stage, the top-level query reranks the merged candidate pool by similarity.
This is more efficient than running two separate searches and merging the results on the client side.

Step 13: Return vectors with results

Setting with_vectors=True includes the raw embedding vectors in the response alongside the payload and score. Run this cell to search for “machine learning” and print the dimensionality and first five values of each returned vector.

When to return vectors

Returning vectors increases response size significantly — each 384-dim float vector adds approximately 1.5 KB per result — so only enable this when needed.

Selective payload with WithPayloadSelector

Instead of with_payload=True (which returns all payload fields), use WithPayloadSelector to include or exclude specific fields.

Expected output

Each result includes the full 384-dimensional vector. The dimensionality confirms the vector is present, and the first five values show a sample of its contents.

Step 14: Combine search with filters

Filters restrict which points are considered during similarity search. The filter is evaluated server-side before ranking, so only matching points are scored. Run this cell to search by topic and by difficulty level separately.

Expected output

The first search returns only machine learning documents, and the second returns only beginner-level documents, regardless of topic.
For a deep dive into all available filter types, see the Predicate filters tutorial.

Step 15: Collection cleanup

Run this cell to flush any pending writes to disk and confirm the vector count. Uncomment the delete lines to remove the collection entirely once finished.

Expected output

The vector count confirms nothing was lost during the session, and the flush line confirms all data is persisted to disk.

Complete API reference

The following tables summarize the methods, parameters, and distance metrics covered in this tutorial.

Core search methods

The primary methods for running vector similarity searches are listed below.

Retrieval and counting

The following methods fetch points by ID and count collection contents.

Search parameters

All search methods accept the following parameters to control retrieval behaviour.

Distance metrics

The metric must be set at collection creation time and cannot be changed afterwards.

Next steps

Now that you can embed, store, search, and tune vector queries, explore the following tutorials to add more capabilities to your search pipeline.

Predicate filters

Combine similarity search with structured payload constraints

Reranking search results

Improve relevance with cross-encoder and reciprocal rank fusion reranking

Retrieval quality

Measure and optimize search accuracy using precision, recall, and MRR

Open-source embedding models

Integrate open-source models like Sentence Transformers and BGE