Zero Labs
Industry News / AI

Beyond Vector Search: What Your Database Can Do with Embeddings

Source · Towards AI By Greg Short

From the publisher’s feed, collected in the ZeroLabs newsroom.

The similarity join: an SQL operator for predictions, analytics, and joining tables that have no foreign keysThe typical way to join tables in relational databases is through foreign keys. This relationship is encoded into the database at design time, and then you join on this column. Let’s call this an equi-join. This requires one to place strict designs and to know the relationships a priori.We can easily imagine far more relationships we don’t know beforehand, though.a resume relates to a job postinga patient’s symptoms relate to research papersa support ticket relates to documentation, and a complaint relates to engineering specs.But we (likely) don’t have foreign keys relating any of these tables to one another, even though they are completely natural tables to join.Embedding vectors and similarity joins can provide a solution to this problem. Embedding vectors have exploded over recent years and become a standard component of databases. These vectors are typically used for semantic search, and used to find rows that are similar to the user’s query vector. However, through similarity joins, we can join many related tables that do not have foreign keys connecting them.Through these similarity joins, we get access to a number of capabilities such as prediction at query time, population-level analytics, and cross-entity comparison.Thus, I propose to treat similarity joins as a first-class database operator like in Silva & Aref (2010). The explosion of vector columns and representations has increased the potential value of this operation.Why not just use similarity search?This article shows how to express joins on similarity with relationships like these using the same algebra as JOIN, WHERE, GROUP BY.We’ll cover the three cardinality shapes of similarity joins: k-closest pair, kNN, and ε-joins. Each gets a simple example and a discussion of when to reach for it.You might think, why not just use similarity search? It’s simple, already lots of tools available for it. The process is simpleencode one resumeretrieve the nearest job postingsIt’s great in a lot of cases, but it’s not well-suited for all types of analysis because you only get one entity in the output (i.e., one side). For example, consider the following search. “Given this resume, find matching jobs.” Then it gives you back jobs. Just jobs. You don’t get back which candidates match a given job, or which department has the most matches, or which postings have no good candidates at all. It’s akin to IN in SQL, instead of joining two tables, you are only filtering one table. You get filtered results but no structure to work with. The analytical power comes from the pairing, though.Using representations to join entitiesFirst, to join two entities in a database, we need something the database can compare. For this, we’ll use the term “representation” from machine learning. A representation characterizes an entity, where proximity in some space means relatedness in the world.A “representation” expresses a view about what the entity is. A representation can come from many sources and often be an embedding vector. It is up to the designer to decide on what representation will best serve a task. We could use a single field, multiple numeric columns, interactions with other tables, and more.Then, to join the entities, we use a similarity join, primarily motivated by Silva & Aref (2010). They formalized similarity operators for metric spaces. Extending that machinery to learned representations is the natural next step. Similarity joins empower us to join entities not by a binary operation, but by similarity or relatedness. This gives us the relationship as a queryable structure. We get every applicant and job pair, with a similarity score, in a single result set. This gives us the power to then aggregate over that structure.GROUP BY candidate: Which candidates are specialists vs. generalists?GROUP BY job: Which roles have the deepest talent pool?SUM(similarity) per department: Total "fit score" as a staffing metricWHERE similarity WHERE similarity > 0.7 across many jobs: Most versatile candidatesThese are analytics over the similarity relationship rather than simple search queries. But to join, we need a join condition. Foreign-key joins use equality joins (equi-joins). Here we’ll use “similarity joins” based on similarity metrics.Problem: recruiting without foreign keysSo let’s take a look at a problem where we can apply similarity joins. A recruiter has two tables: resumes and job postings. In this case, there are no foreign keys coming to the rescue to help us link these two tables. But these two entities are absolutely related.How do you connect these tables?First, let’s use 500 applicants with resume text and 51 job postings with descriptions, from a Kaggle recruitment dataset and O*NET.The setup cell below loads the data and encodes each resume and job description with all-MiniLM-L6-v2. The resulting vectors live in representation columns on the SQLAlchemy models ( Applicant.resume_rep, Job.description_rep) - regular model attributes, not a separate store.We’ll use a text encoding. Each resume and job description is encoded with a sentence transformer. The resulting similarity reflects the semantic relatedness of the text.Start the server first:docker run -d --name similarity-join-pg \ -e POSTGRES_PASSWORD=postgres \ -e POSTGRES_DB=similarity_join_test \ -p 5432:5432 \ pgvector/pgvector:pg16https://medium.com/media/202cdae09c4f515f334bc2f5502a5348/hrefK-closest pair similarity joinThe first type of join we’ll look at is the k-closest pair similarity join, a leaderboard-like join that returns the strongest matches between applicant and job.The limit=15 parameter makes this a k-closest pair join. It will always output 15 rows regardless of input size unless there are fewer than 15 rows, that is. The underlying k-closest pair query was studied in spatial-database work (Hjaltason & Samet 1998, Corral et al. 2000).We’ll use the sim_join method from the library, which adds to SQLAlchemy's query builder. Without this, the statement is a standard select().https://medium.com/media/8f42811dd34f514a1e73fefff76826ad/hrefK similar rows with kNN-joinThe previous join will always give us the same number of results and may not find matches for all rows. However, there are tasks like search or row-level prediction where we want to have K matches for each row. For these tasks, we can use the kNN-join. This join operator joins each row with the k-nearest matches for each row, per-outer top-K.We’ll look at different questions with this. For example, what if the question is “give each applicant their K best matches” instead of “what are the best pairs overall”? Same sim_join, different parameter: k=K in place of limit=N. Output cardinality becomes K × (number of applicants) - the recommendation shape.Under the hood, this library emits a LATERAL subquery. When using k=, pass only the left entity in select(...) - the right entity is bound to the lateral internally.Note: DuckDB’s VSS (Vector Similarity Search) extension provides this operator as HNSW_INDEX_JOIN. The academic literature calls this kNN-join (Böhm & Krebs 2004). I prefer the term kNN-join because it invokes one of the oldest non-parametric statistical models (Cover-Hart 1967), and kNN can do far more than retrieval. kNN-join also supports classification, regression, density estimation, and more, with search being just one application of the model.The similarity score below is recomputed Python-side because sim_join doesn't return it directly (see §8 Challenges).https://medium.com/media/a7fd0bf8602d8cc9af1432b6233ad143/hrefNotice the shape change between the two cells above:limit=15 returned 15 rows total.k=2 returned 1000 rows (2 jobs × 500 applicants), with - critically - the bottom slice of scores far worse than the top. Those aren't bad data; they're the structural consequence of k=2. Every applicant is forced to show up twice even if no job in the catalog is actually a good fit. A candidate with a niche background gets matched to whatever happens to be closest in embedding space, and "closest" can still be a very poor match in absolute terms.These are two different similarity join flavors with the same inputs and representations with different cardinality constraints.Extending equi-joins with ε-joinsThe previous two we looked at, k-closest pair join and kNN-join, always return a fixed number of results regardless of the quality of the join.ε-joins, on the other hand, make use of a threshold, and instead of predefining the cardinality, they let the data decide cardinality. In the standard version, a pair will be emitted if its similarity exceeds ε. The library also implements band-pass and low-pass joins. With this approach, you’ll set a threshold that defines what is “similar-enough,” then get back a table with entities that meet this criterion. With ε-join there is no forced cap, no forced fan-out. Same sim_join operator, different parameter: gte=0.5 (or gt, lte, lt) instead of limit= or k=.ε-joins are:A generalization of equi-joins: equi-join is the degenerate case where similarity must be exact.Symmetric: the same pairs come out regardless of which side drives the join as long as the similarity used is symmetric.Stable across dataset size: doubling one side doesn’t change which pairs pass the threshold.Analytical: data-determined cardinality plays naturally with population-level aggregation over GROUP BY, COUNT, AVG, HAVING - the aggregates reflect the full qualifying population, not a truncated slice.Below, we’ll explore a few analytical queries that use ε-joins ( gte=0.5) because the questions they ask, "how many matches?", "which jobs have the fewest strong candidates?", all require data-determined cardinality.Specialists vs generalistsIn this example, we’ll look at how to estimate who is a generalist. For each applicant, count how many jobs they match well (cosine similarity ≥ 0.5). Someone matching many roles is more of a generalist; someone matching few is a specialist.https://medium.com/media/822c93fba5d969d23e3af3ad177a02af/hrefFrom this spread, the individuals making up the top rows can be expected to be more generalist, since their resumes read close to a broader band of postings, so they match many jobs at the threshold. The bottom rows (and any applicants missing from the list because their count was zero) can be considered specialists. That spread creates the analytical signal; it tells the recruiter where to place versatile hires vs. where to treat each match as a specific fit. It falls out of a GROUP BY over the ε-join. To get the specialists, you would reverse the sort order and look at applicants with the lowest match counts.Detect gaps in jobsLet’s now flip the aggregation to detect the jobs with thin talent pools or unrealistic descriptions. We’ll flip the script using the same ε-join but group by jobs instead.https://medium.com/media/e9313d53cc837f622675cd15336856f8/hrefLet’s compose a chainBecause the operator is in the same algebra as WHERE and GROUP BY, sim_join chains with them naturally.Now, we’ll look at how we can chain this to compose with the rest of SQL. Below we add WHERE Applicant.age https://medium.com/media/f68320fc3a2ba75be2f90c2ac2291207/hrefOne query, no Python glue. sim_join composes with WHERE, GROUP BY, aggregation, multi-way joins, and set operations the way any other operator does.RecapWhat the article showed:in the library sim_join is a single method on the SQLAlchemy query builder. Three cardinality shapes are selected by parameter:limit=N - k-closest pair join (global top-N, leaderboard).k=K - kNN-join (per-outer top-K, retrieval/prediction).gte=ε - ε-join (analytical, threshold-based; equi-join is the degenerate case at ε = 1).each join operator gives different capabilities and is complementaryk-closest pair allows for leaderboard-like retrieval and analyticskNN-join allows for per-row retrieval and predictionε-join is analytical and ensures that all joins meet a threshold requirement for similarityTwo design decisions are independent of the operator and matter just as much:The representation: what gets compared. A different representation produces different join results (the subject of Article 2).The cardinality constraint: limit, k, or ε. Different shapes answer different questions.The library is simply a prototype and not ready for production or anything more than small databases. Realizing similarity joins in database management systems has both design challenges (for anyone using them) and technical challenges (for the database community building support).Design challengesThreshold: what scores should pass? Unlike a foreign-key join, where you know in advance what will and won’t join, every pair can technically be joined in a similarity join. Setting a top-K, or an ε threshold, decides what counts as “similar enough.” That decision depends on the data, the task, and the representation.Score interpretation. A similarity of 0.7 might be excellent for one encoder or query and mediocre for another. The only way to set a threshold sensibly is to understand the space and the similarity operator, or get domain feedback for what “good” looks like.Representation choice. Which encoder, which space, which dimensionality, and what training objective will motivate the choice of representation. The representation, along with the metric determine what “similar” means for every query that uses it.Other challenges:staleness when source data changescold-start for new entities,Prior work on efficient similarity joins (Silva & Aref 2010, Spark-based approaches) addresses some of the scale concerns.Technical challengesJoin implementation. We’re using cross joins for demonstration, but cross joins scale poorly O(N × M) for per-pair distance computations. They can work on tens of thousands of rows, but they become intractable past that. HNSW is designed for kNN retrieval and naturally extends to kNN-joins; ε-joins are harder to support efficiently - HNSW handles range queries but more slowly than its native top-K mode. LSH-style indexes are better suited for ε-queries but aren't widely available in mainstream databases.Query optimization. It is necessary to have a good cardinality estimation for “how many pairs are within ε” and also join-order rules for mixing equi-joins with sim-joins.Score column in the result. sim_join today returns row pairs but not the similarity score that produced the pairing. We recompute it Python-side. A first-class implementation should emit the score as part of the result, but that needs a naming convention for the score column: predictable, collision-free, and well-defined when a query joins on multiple rep pairs.What’s NextIn this article, we used text representations for similarity joins. These encode what entities say about themselves. But the relationship you care about isn’t always in text.it can be in foreign key relationshipsit can be in a combination of columnsit can be in image representationsit can be in the frequency domain of a time seriesand so onFor example, while a movie can be represented by its plot description, it can also be represented by its audience. This will give you a completely different characterization, answering completely different questions. An entity can have multiple representations, each capturing a different facet. Same join operator with a different representation and thus a different question answered. We’ll look at this in article 2.Further reading:Silva-Aref-Ali 2010 (The Similarity Join Database Operator) for the algebraic case for similarity as a relational operator.Hjaltason-Samet 1998 and Corral et al. 2000 for the spatial-database lineage of the k-closest pair shape.Böhm-Krebs 2004 (The k-Nearest Neighbour Join) for the join formulation of kNN.Cover-Hart 1967 for the classical kNN classifier.Chaudhuri-Ganti-Kaushik 2006 and Gravano et al. 2001 for the data-cleaning predecessors that motivated ε-style thresholding.The prototype used in this article is available at github.com/short-greg/similarity-joins. It’s an SQLAlchemy extension demonstrating similarity joins on PostgreSQL + pgvector.Beyond Vector Search: What Your Database Can Do with Embeddings was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.