Zero Labs
Industry News / AI

Text Embeddings Aren’t Enough for Similarity Joins

Source · Towards AI By Greg Short

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

Article 2 of 3 in the Similarity Joins series0. BackgroundThis is the second article in a three-part series. The first, Beyond vector search: what your database can do with embeddings, introduced similarity joins. In this article, we will take a deeper dive into similarity joins, a type of entity join in databases that uses the similarity of embedding vectors. These have made it possible to describe what an entity is in a vector and then join based on this vector. The first article in the series introduced it, and here we follow up on this by looking at the benefits of using multiple representations.1. How should we represent an entity?The previous article in this series on similarity joins gave each occupation a single representation: a vector built from its text description. That vector places the occupation in a space where distance carries meaning. Two occupations will be similar when their descriptions have similar meanings. In this case, we had one representation, and thus could only find things that were similar in that one view. We know that entities can be similar in more than one way, though. For instance, two people can have similar personalities, yet have quite different work experiences.The occupation’s description vector is used to represent the occupation, but it is not the occupation itself. A sentence-transformer reads the description and squeezes it into a few hundred numbers. Everything the description said, the work, the tools, the setting, compresses into a single point. The representation is a summary, and a summary leaves things out.Representations outside of databases work the same way. For example, in politics, we can draw a single electoral district that sends one representative to stand for everyone in it. That representative fits some constituents well and others poorly, with no room for a second voice. To resolve this lack of representation for some constituents, proportional representation is used in some systems. In these systems, parties receive representatives based on the percentage of votes the party gets. With this approach, the “entities” (constituents) will have better representation by having representatives both through the community and the party. This also helps in reducing political divisions and animosity.A more technical example of this would be how to represent a film. A film can be represented by its description text, the plot and themes written out, or by its audience, the people who watched and liked it, and so on. None is the “true” representation of the film. All can be useful for recommending what to watch next, and they disagree in instructive ways: a description links films that read alike, and an audience links films that the same people enjoy. The strongest recommender does not choose between them. It uses more than one.An entity in a database can likewise carry several at once, each a different compression, each tuned to a different question. Once it does, three capabilities open up with the same similarity operator:Same operator on different reps of one entity. Different rep, different question.Comparing across entity types. When the reps of two entity types live in the same latent space, the operator compares them directly.A group of entities as one rep. An aggregate of reps is itself a rep, usable everywhere a single rep is.To show this, we’ll use the hiring database we used in the previous article and add a second representation to a table. However, this time, instead of using text embeddings, we’ll form a rep from the many-to-many relationships between two tables. We’ll call it a relational rep. The rest of the article dives into this, then walks through each of the three capabilities in turn.2. Convert Many-to-Many Relationships into RepsSo now let’s give each entity more than one representation, each giving us a different view of the entity. We now build that second representation for the hiring data by giving Occupation another representation. The previous article already gave each occupation a rep from its description, the analog of the film’s description. For this, we’ll take an M2M table and turn it into a rep. The hiring dataset has two M2M tables we could use:OccupationSkill connects ONET occupations to skills with an importance* rating (1-5). Every occupation needs many skills; every skill is needed by many occupations.Application connects applicants to jobs with a best-match label.These tables encode the structure of the relationship between the entities. So from these, we can provide a new rep that gives a view of each entity based on how it relates to entities in another table.So then let’s treat OccupationSkill as a sparse matrix: rows are occupations, columns are skills, cells are importance ratings (1-5). Factor it with ALS (alternating least squares). Then we've got a 32-dim vector per occupation and a 32-dim vector per skill, all in the same latent space. Taking the dot product will approximate the original importance rating. If this seems familiar, it’s because this is the same technique that is commonly used in recommender systems.Each Occupation now carries two reps:description_rep: 384-dim sentence-transformer vector. Encoded from the occupation's text description. An attribute rep derived from one column on the row.skill_rep: 32-dim ALS vector. The occupation's position in the skill latent space. A relational rep - derived from how the row relates to other rows.The skill table will be symmetric with this; it has its own description_rep (attribute) and occupation_rep (co-trained with Occupation.skill_rep in the same 32-dim space).3. Set up the RepsWe’ll use the same dataset as the previous article, with the Occupation, Skill, and the OccupationSkill M2M tables. The cell below loads the entities and attaches pre-computed reps (text embeddings and ALS-factorized vectors).Start the database if it isn’t running:docker run -d --name similarity-join-pg \ -e POSTGRES_PASSWORD=postgres \ -e POSTGRES_DB=similarity_join_test \ -p 5432:5432 \ pgvector/pgvector:pg16With Postgres running, load the entities and attach their reps:import osimport subprocessfrom sqlalchemy import create_engine, select, textfrom sqlalchemy.orm import Session, aliasedfrom similarity_join import rep_aggfrom similarity_join.utils import project_rootfrom tutorials.shared.jobs import ( Applicant, Application, Base, Job, Occupation, OccupationSkill, Skill, populate,)# Ensure the jobs subset data is present on disk.DATA_DIR = project_root() / "local" / "data" / "jobs" / "subset"if not (DATA_DIR / "occupations.csv").exists(): print("Data not found. Running prepare script...") subprocess.run( ["bash", str(project_root() / "scripts" / "prepare_jobs_data.sh")], cwd=str(project_root()), check=True, )DATABASE_URL = os.environ.get( "DATABASE_URL", "postgresql://postgres:postgres@localhost:5432/similarity_join_test",)engine = create_engine(DATABASE_URL, echo=False)# pgvector's server-side extension must exist in the database before any# VECTOR column can be created. Idempotent - safe to run every time.with engine.begin() as conn: conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))Base.metadata.drop_all(engine)Base.metadata.create_all(engine)with Session(engine) as session: counts = populate(session)print( f"Loaded {counts['occupations']} occupations, {counts['skills']} skills, " f"{counts['occupation_skills']} skill ratings.")print( f" {counts['applicants']} applicants, {counts['jobs']} jobs, " f"{counts['applications']} applications.")4. Get Different Perspectives through Different RepsWith two reps per occupation, the similarity operator can ask two different questions about the same pair of rows. We’ll demonstrate by self-joining Occupation against itself. First under description_rep (the attribute rep), then under skill_rep (the relational rep). The operator and the query shape don't change. Only the rep column changes.OccB = aliased(Occupation)with Session(engine) as session: stmt = ( select(Occupation, OccB) .where(Occupation.id .sim_join( OccB, Occupation.description_rep, OccB.description_rep, limit=15, ) ) results = session.execute(stmt).all() print("Top 15 occupation pairs by DESCRIPTION similarity (attribute rep)") print("-" * 80) for occ_a, occ_b in results: print(f" {occ_a.title: {occ_b.title}")Below are the most similar based on the description.Top 15 occupation pairs by DESCRIPTION similarity (attribute rep)-------------------------------------------------------------------------------- Human Resources Managers Training and Development Managers Civil Engineers Mechanical Engineers Regulatory Affairs Managers Compliance Managers Computer Hardware Engineers Electrical Engineers Bioinformatics Technicians Bioinformatics Scientists Market Research Analysts and Marketing Specialists Search Marketing Strategists Architectural and Engineering Managers Natural Sciences Managers Computer Network Support Specialists Network and Computer Systems Administrators Computer and Information Systems Managers Architectural and Engineering Managers Education and Childcare Administrators, Preschool and Daycare Education Administrators, Kindergarten through Secondary Compensation and Benefits Managers Human Resources Managers Database Architects Data Warehousing Specialists Computer and Information Systems Managers Natural Sciences Managers Computer Network Support Specialists Computer Network Architects Compensation and Benefits Managers Training and Development ManagersNow let’s swap description_rep for skill_rep to get a different view of the relation.with Session(engine) as session: stmt = ( select(Occupation, OccB) .where(Occupation.id .sim_join( OccB, Occupation.skill_rep, OccB.skill_rep, limit=15, ) ) results = session.execute(stmt).all() print("Top 15 occupation pairs by SKILL-PROFILE similarity (relational rep)") print("-" * 80) for occ_a, occ_b in results: print(f" {occ_a.title: {occ_b.title}")This yields the most similar occupations based on the skill profile.Top 15 occupation pairs by SKILL-PROFILE similarity (relational rep)-------------------------------------------------------------------------------- Geothermal Production Managers Biomass Power Plant Managers Equal Opportunity Representatives and Officers Business Intelligence Analysts Treasurers and Controllers Cost Estimators Water/Wastewater Engineers Wind Energy Engineers Search Marketing Strategists Document Management Specialists Computer Network Support Specialists Electrical and Electronic Engineering Technologists and Technicians Bioinformatics Scientists Geneticists Loan Officers Tax Examiners and Collectors, and Revenue Agents Soil and Plant Scientists Materials Scientists Market Research Analysts and Marketing Specialists Actuaries Financial Quantitative Analysts Business Intelligence Analysts Computer Systems Analysts Computer Network Architects Validation Engineers Materials Scientists Soil and Plant Scientists Medical Scientists, Except Epidemiologists Animal Scientists Medical Scientists, Except EpidemiologistsThe two lists differ in revealing ways.Under description_rep, pairs share vocabulary and job family. Human Resources Managers ↔ Training and Development Managers. Civil Engineers ↔ Mechanical Engineers. Bioinformatics Technicians ↔ Bioinformatics Scientists. The text encoder pairs occupations whose descriptions reuse the same words.Under skill_rep, pairs share skill profile. The descriptions often differ:Geothermal Production Managers ↔ Biomass Power Plant Managers: different fuels, same managerial mix.Animal Scientists ↔ Medical Scientists: different organisms, same research skills.Treasurers and Controllers ↔ Cost Estimators: different roles, similar quantitative profile.Water/Wastewater Engineers ↔ Wind Energy Engineers: different domains, same engineering mix.A text encoder ranks these pairs lower because the specific subject matter (geothermal vs biomass, animals vs medicine, water vs wind) dominates the embedding even when the role family is shared. The relational rep ranks them by required-skill overlap — the underlying skill profile is what surfaces, not the surface vocabulary.So they give you:description_rep: which occupations read similarly?skill_rep: which occupations require similar skills?Neither is more correct. With both reps in place, the question becomes an analyst’s choice per query.5. Then Join Across Entity TypesOccupation.skill_rep and Skill.occupation_rep came out of the same ALS factorization. They live in the same 32-dim latent space. Their dot product approximates the original importance rating from OccupationSkill. That shared space lets us sim_join an occupation directly against a skill, even though they're different entity types.The same query through text reps doesn’t carry the same meaning. Occupation.description_rep and Skill.description_rep are both 384-dim sentence-transformer vectors, so the geometry is the same. But they encode different kinds of content. Cosine across them measures vocabulary overlap, nothing more.Below: Computer Programmers as the seed occupation, top-5 skills via each path.with Session(engine) as session: seed = session.execute( select(Occupation).where(Occupation.title == "Computer Programmers") ).scalar_one() print(f"Seed occupation: {seed.title}") print(f'Description: "{(seed.description or "")[:160]}..."') print() # Path A: skills via the shared ALS space (Occupation.skill_rep × Skill.occupation_rep) stmt_als = ( select(Skill) .vec_filter(Skill.occupation_rep, seed._skill_rep_vec, limit=5) ) print("Top 5 skills via ALS (M2M-derived shared space):") for s in session.execute(stmt_als).scalars().all(): print(f" {s.name}") print() # Path B: skills via text (Occupation.description_rep × Skill.description_rep) stmt_text = ( select(Skill) .vec_filter(Skill.description_rep, seed._description_rep_vec, limit=5) ) print("Top 5 skills via text (description-to-description):") for s in session.execute(stmt_text).scalars().all(): print(f" {s.name}")This gives us the most similar given both representations.Seed occupation: Computer ProgrammersDescription: "Create, modify, and test the code and scripts that allow computer applications to run. Work from specifications drawn up by software and web developers or other..."Top 5 skills via ALS (M2M-derived shared space): Installation Repairing Operations Analysis Equipment Selection ScienceTop 5 skills via text (description-to-description): Programming Installation Systems Analysis Technology Design Operation and ControlThe two answers diverge.The ALS path returns skills the OccupationSkill data shows programmers need at high importance. Some of these skills don't read like the programmer description at all. The ALS rep encodes the importance ratings; the text rep doesn't see them. The text path returns skills whose definitions “read” like the programmer description.Both views can be useful. The ALS rep encodes the structural “needs” relationship. The text rep encodes vocabulary similarity. Reading them side by side is more informative than either alone. Different entity types, one similarity operator, and distances that respect the latent geometry.6. Grouping of entities together as one repSometimes the question isn’t about one entity but about a set of entities. What’s typical of engineering occupations? Which products resemble this user’s last five purchases? Both ask for a representation of a group. With the library’s rep_agg we can produce such a representation. Hand it a source query and a representation column, and it returns a scalar subquery: a single aggregated vector.Below: aggregate the skill_rep of every occupation whose title contains "engineer," then find non-engineering occupations near that centroid.with Session(engine) as session: eng_query = ( select(Occupation) .where(Occupation.title.ilike("%engineer%")) ) eng_group_size = len(session.execute(eng_query).scalars().all()) print(f"Engineering group size: {eng_group_size} occupations") print() # Compute the engineering centroid (mean of skill_rep across the group) centroid = rep_agg(eng_query, Occupation.skill_rep, mode="mean") # Find non-engineering occupations nearest the centroid stmt = ( select(Occupation) .where(~Occupation.title.ilike("%engineer%")) .vec_filter(Occupation.skill_rep, centroid, limit=10) ) print("Top 10 non-engineering occupations nearest the engineering centroid:") for occ in session.execute(stmt).scalars().all(): print(f" {occ.title}")Then we get a list of the closest jobs to engineering based on skill.Engineering group size: 45 occupationsTop 10 non-engineering occupations nearest the engineering centroid: Software Quality Assurance Analysts and Testers Computer and Information Research Scientists Biofuels/Biodiesel Technology and Product Development Managers Foresters Web Administrators Quality Control Systems Managers Database Architects Range Managers Chemists Database AdministratorsThe non-engineering occupations nearest the engineering centroid are technical and quantitative roles. Their skill profiles overlap with the engineering average even though their titles don’t say “engineer.” The centroid represents the group in the same latent space in which individual occupations live.We used mode="mean", the arithmetic centroid. The library also supports sum and weighted_mean (where another column supplies the weights). Weighted means open up similarity-weighted aggregation, the structure behind kNN regression, and attention.A set of entities now participates in the algebra as a single rep.7. Representations and shared spaceCapability 2 made use of the fact that Occupation.skill_rep and Skill.occupation_rep share a latent space. That wasn't by accident. It was a direct result of ALS. Since similarity relies on two vectors sharing a latent space, the operator will refuse to compute similarity between two reps that do not. This implementation is still pretty primitive in the library.Below: try to sim_join description_rep (text-embedding space) against skill_rep (occupation-skill space). The library raises an IncompatibleSpaceError immediately.from similarity_join import IncompatibleSpaceErrorOccC = aliased(Occupation)# Attempt to sim_join Occupation.description_rep (text_embedding space)# against Occupation.skill_rep (occupation_skill space). These are two# different encoders in two different geometries - the library refuses.with Session(engine) as session: try: stmt = ( select(Occupation, OccC) .sim_join( OccC, Occupation.description_rep, OccC.skill_rep, k=1, ) ) session.execute(stmt).all() except IncompatibleSpaceError as err: print(f"IncompatibleSpaceError: {err}")This will give us an error.IncompatibleSpaceError: Incompatible semantic spaces: 'description_rep' uses space 'text_embedding', but 'skill_rep' uses space 'occupation_skill'. Representations must declare the same space to be compared.The error appears immediately. Cross-space comparisons without explicit alignment are almost never what you want.The space check has a limit. Two sentence transformers that both declare text_embedding will type-check fine, even if their geometries don't align. Distances across them are noise. Declared compatibility is necessary, not sufficient. Article 3 picks up this thread.8. DiscussionIn this article, we’ve looked into using multiple reps for similarity joins. Each occupation and skill now carries two reps: an attribute rep from text and a relational rep from the OccupationSkill M2M. The second is an ALS factorization result, in a shared 32-dim space with its co-trained partner. With both reps in place, the same similarity operator reaches three places it couldn’t with one rep:Per-question rep selection on the same self-join: description_rep and skill_rep return different pairs.Joins across entity types: Occupation × Skill, directly, because the two reps share a latent space.A group of entities as one rep: the engineering centroid behaves like a single rep.Beyond these, multiple reps open a path the prototype doesn’t yet take: producing more than one similarity score and aggregating them with a t-norm or s-norm.There’s no reason to stop at two representations, though. If the information is available, a job could be represented by past employees, past applicants, salary level, and so on. For instance, the application M2M table could provide another representation. Multiple columns could also be used as a representation such as the salary range, the description, and the title for the job. We’ve also worked with encoded representations, but it is not critical to encode representations.As a final note, you might ask why not represent the occupation perfectly and build an encoding that loses nothing and pins down each occupation exactly? We could easily do this by using a one-hot encoding to represent the entity: give every occupation its own dimension, set it to one, set every other dimension to zero. The encoding is perfectly faithful, as it loses no information about the entity. No two occupations will ever be confused, and you can read the original row straight back out of the vector.However, under a one-hot encoding, every vector is orthogonal to every other, so it is useless for a similarity join. A registered nurse sits exactly as far from a nurse practitioner as from a roof welder. The encoding records what each occupation is and nothing about what it resembles. A representation that keeps everything tells you nothing about similarity.So a perfectly faithful representation of an entity carries no similarity, and a useful one will throw information away. So the question is not how to represent it perfectly, but how to represent it in a way that lets us evaluate similarity through different views. One representation commits to one answer. Different tasks ask different questions, so you will often want more than one representation of an entity, and sometimes several at once for a single task.ChallengesMultiple reps amplify some challenges from the previous article and introduce new ones. Each is a gap a multi-rep similarity-join database would need to close. A3 returns to these from the framework side.Cold start on relational reps. A brand-new occupation has no skill ratings yet. Its skill_rep doesn't exist or is uninformed. Attribute reps come for free from a text encoder. This is actually a benefit of multiple reps. To handle the cold start situation, one can fall back to an attribute representation for instance.Staleness. When OccupationSkill updates are made, every downstream skill_rep and occupation_rep is stale. Refactoring is expensive. Production runs it on a schedule; the library tracks which version each column holds.Versioning. The previous article had one rep per entity. Here it’s two, three with aggregates. Each carries its own encoder identity, upgrade cycle, and backward-compat story. The (source, encoder, space, metric) type system tracks this; the discipline comes from the schema designer.Rep compatibility. The cross-entity demo worked because ALS was placed Occupation.skill_rep and Skill.occupation_rep in the same latent space. Same for the text reps.9. What’s nextIn the next article, Article 3, we will take a step back and explore the theory behind representations and discuss similarity joins more in depth.Further readingKoren-Bell-Volinsky 2009 (Matrix Factorization Techniques for Recommender Systems) for the matrix-factorization lineage behind the ALS-derived relational rep.Hu-Koren-Volinsky 2008 (Collaborative Filtering for Implicit Feedback Datasets) for the ALS variant that handles binary/count M2M tables rather than explicit ratings.Mikolov et al. 2013 (Efficient Estimation of Word Representations in Vector Space) for distributed representations in a shared latent space, the canonical reference for the “multiple views as embeddings” idea.Bordes et al. 2013 (Translating Embeddings for Modeling Multi-relational Data, TransE) for entity-level embeddings of multi-relational data, the knowledge-graph version of the same problem.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.Text Embeddings Aren’t Enough for Similarity Joins was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.