Locality-sensitive hashing

Also known as: LSH

On this page 7

Locality-sensitive hashing (LSH) is a family of randomized hashing techniques that map similar items to the same hash value with high probability and dissimilar items to different values, which makes it a classic method for approximate nearest neighbor search. In retrieval & knowledge systems, LSH lets an application find documents, images or embeddings that resemble a query without comparing the query to every stored item.

Ordinary hash functions are designed to scatter even nearly identical inputs; LSH does the opposite on purpose. Formalized by Indyk and Motwani in 1998 and refined in later work, it offers provable sublinear query time and remains widely used for near-duplicate detection, deduplication of training corpora and lightweight vector search.

How locality-sensitive hashing preserves similarity

LSH relies on hash functions whose collision probability rises with similarity. Formally, a family is (r, cr, p1, p2)-sensitive when points within distance r collide with probability at least p1, and points farther than cr collide with probability at most p2, where p1 is greater than p2. The gap between these probabilities is what allows candidates to be separated from noise.

A single hash is too weak, so implementations use amplification. They concatenate k hash functions into one signature to make collisions stricter (the AND construction), then build L independent hash tables and treat a match in any table as a candidate (the OR construction). A query is hashed, the matching buckets are read, and only those candidates are re-ranked by exact distance.

The table below summarizes how the two amplification parameters change the behavior of an LSH index.

ParameterMeaningIncreasing it
k (hashes per table)Length of each bucket signatureFewer false positives, lower recall
L (number of tables)Independent hash tables queriedHigher recall, more memory
Bucket width wQuantization step for Euclidean LSHMore collisions, more candidates
Probes per tableNeighboring buckets also checkedHigher recall with fewer tables
Effect of the main LSH parameters

Common LSH families and their distance measures

Each LSH family is tied to a specific similarity or distance measure, so the right choice depends on how the data is represented. Using a family that does not match the metric produces buckets that group the wrong items.

FamilySimilarity measureTypical data
MinHashJaccard similarity of setsShingled text, web pages
SimHash (random hyperplanes)Cosine similarityEmbeddings, feature vectors
p-stable LSH (E2LSH)Euclidean distanceDense numeric vectors
Bit samplingHamming distanceBinary codes
Major LSH families

Random hyperplane hashing is the variant most relevant to embedding-based retrieval. Each hash bit records which side of a random hyperplane a vector falls on, and the probability that two vectors receive the same bit equals one minus their angle divided by pi. MinHash, in turn, powers the banding technique used to deduplicate large text collections.

LSH compared with other vector search methods

In modern vector search, LSH competes with graph-based and quantization-based indexes such as HNSW, IVF index and product quantization. Benchmarks on dense embeddings generally show that graph indexes reach a given recall with far fewer distance computations than classical LSH.

Index typeStrengthWeakness
LSHTheoretical guarantees, easy streaming insertsMany tables for high recall
HNSWExcellent recall and latencyHigh memory, slower builds
IVF with product quantizationCompact memory footprintRecall loss from compression
Exact searchPerfect recallLinear cost per query
LSH versus other approximate nearest neighbor indexes

LSH keeps clear advantages in distributed and streaming settings. Hash signatures are independent of each other, so new items can be inserted without rebuilding structure, and buckets can be sharded across machines with simple key-based partitioning.

Choosing and tuning an LSH index

Tuning LSH is a trade-off between recall, latency and memory. A practical approach starts from a target recall, measured against exact search on a sample of queries, and then adjusts k and L until the candidate set stays small enough for the latency budget.

SituationRecommended choiceReason
Near-duplicate documentsMinHash with bandingMatches Jaccard on shingles
Streaming embeddingsRandom hyperplane LSHCheap inserts, no rebuild
High-recall semantic searchPrefer HNSW or IVFLSH needs too many tables
Memory-limited devicesShort binary LSH codesCompact Hamming comparisons
Decision guide for LSH in retrieval
  • Multi-probe LSH checks neighboring buckets and can cut the number of tables several times for the same recall.
  • Normalize vectors before cosine hashing so that magnitude does not distort bucket assignment.
  • Always re-rank candidates exactly, because bucket membership is only a coarse filter.

Limitations of locality-sensitive hashing

LSH struggles with high intrinsic dimensionality and uneven data distributions. When many points sit at similar distances from a query, buckets either overflow or miss true neighbors. Dense clusters can create hot buckets that slow every query touching them.

Memory can also grow quickly, because each of the L tables stores a reference to every item. A common misconception is that LSH is outdated; in practice it remains the standard tool for large-scale deduplication, while graph indexes usually win for interactive semantic search.

Randomness is another practical concern. Because hash functions are drawn at random, two builds with different seeds return slightly different candidate sets, which complicates regression testing and reproducible evaluation. Teams usually fix the random seed and store the hyperplanes or permutations alongside the index. Finally, LSH guarantees are probabilistic: a true neighbor is found only with a stated probability, so systems that require exhaustive matches, such as legal discovery or safety filtering, should combine LSH with a second exact pass or avoid it entirely.

Stripped to the essentials

Locality-sensitive hashing is a way to sort similar things into the same box. Imagine a library that shelves books by rough topic. You only search one shelf instead of the whole building.

LSH does this with numbers. Similar items usually get the same label. When you search, you check only the boxes with your label. You might miss a few matches, but you save a huge amount of time.

Where it is applied

A team preparing a training corpus for a language model collects about two billion web pages. Many pages are copies or lightly edited versions of each other, and comparing every pair is impossible. The team splits each page into five-word shingles and computes a MinHash signature of 128 values.

The signatures are divided into 16 bands of 8 rows, and pages that match in any band become candidate pairs. Only those pairs receive an exact Jaccard check against a threshold of 0.8. The pipeline runs in parallel across a cluster in hours rather than weeks and removes a substantial share of near-duplicate pages, which reduces memorization and improves data quality for the retrieval and training stages that follow.