TigerData logo
TigerData logo
  • Product

    Tiger Cloud

    Robust elastic cloud platform for startups and enterprises

    Agentic Postgres

    Postgres for Agents

    TimescaleDB

    Postgres for time-series, real-time analytics and events

  • Docs
  • Pricing

    Pricing

    Enterprise Tier

  • Developer Hub

    Changelog

    Benchmarks

    Blog

    Community

    Customer Stories

    Events

    Support

    Integrations

    Launch Hub

  • Company

    Contact us

    About

    Timescale

    Partners

    Security

    Careers

Log InTry for free
Home
AWS Time-Series Database: Understanding Your OptionsStationary Time-Series AnalysisThe Best Time-Series Databases ComparedTime-Series Analysis and Forecasting With Python Alternatives to TimescaleWhat Are Open-Source Time-Series Databases—Understanding Your OptionsWhy Consider Using PostgreSQL for Time-Series Data?Time-Series Analysis in RWhat Is Temporal Data?What Is a Time Series and How Is It Used?Is Your Data Time Series? Data Types Supported by PostgreSQL and TimescaleUnderstanding Database Workloads: Variable, Bursty, and Uniform PatternsHow to Work With Time Series in Python?Tools for Working With Time-Series Analysis in PythonGuide to Time-Series Analysis in PythonUnderstanding Autoregressive Time-Series ModelingCreating a Fast Time-Series Graph With Postgres Materialized Views
Understanding PostgreSQLOptimizing Your Database: A Deep Dive into PostgreSQL Data TypesUnderstanding FROM in PostgreSQL (With Examples)How to Address ‘Error: Could Not Resize Shared Memory Segment’ How to Install PostgreSQL on MacOSUnderstanding FILTER in PostgreSQL (With Examples)Understanding GROUP BY in PostgreSQL (With Examples)PostgreSQL Join Type TheoryA Guide to PostgreSQL ViewsStructured vs. Semi-Structured vs. Unstructured Data in PostgreSQLUnderstanding Foreign Keys in PostgreSQLUnderstanding PostgreSQL User-Defined FunctionsUnderstanding PostgreSQL's COALESCE FunctionUnderstanding SQL Aggregate FunctionsUsing PostgreSQL UPDATE With JOINHow to Install PostgreSQL on Linux5 Common Connection Errors in PostgreSQL and How to Solve ThemUnderstanding HAVING in PostgreSQL (With Examples)How to Fix No Partition of Relation Found for Row in Postgres DatabasesHow to Fix Transaction ID Wraparound ExhaustionUnderstanding LIMIT in PostgreSQL (With Examples)Understanding PostgreSQL FunctionsUnderstanding ORDER BY in PostgreSQL (With Examples)Understanding WINDOW in PostgreSQL (With Examples)Understanding PostgreSQL WITHIN GROUPPostgreSQL Mathematical Functions: Enhancing Coding EfficiencyUnderstanding DISTINCT in PostgreSQL (With Examples)Using PostgreSQL String Functions for Improved Data AnalysisData Processing With PostgreSQL Window FunctionsPostgreSQL Joins : A SummaryUnderstanding OFFSET in PostgreSQL (With Examples)Understanding PostgreSQL Date and Time FunctionsWhat Is Data Compression and How Does It Work?What Is Data Transformation, and Why Is It Important?Understanding the Postgres string_agg FunctionWhat Is a PostgreSQL Left Join? And a Right Join?Understanding PostgreSQL SELECTSelf-Hosted or Cloud Database? A Countryside Reflection on Infrastructure ChoicesUnderstanding ACID Compliance Understanding percentile_cont() and percentile_disc() in PostgreSQLUnderstanding PostgreSQL Conditional FunctionsUnderstanding PostgreSQL Array FunctionsWhat Characters Are Allowed in PostgreSQL Strings?Understanding WHERE in PostgreSQL (With Examples)What Is a PostgreSQL Full Outer Join?What Is a PostgreSQL Cross Join?What Is a PostgreSQL Inner Join?Data Partitioning: What It Is and Why It MattersStrategies for Improving Postgres JOIN PerformanceUnderstanding the Postgres extract() FunctionUnderstanding the rank() and dense_rank() Functions in PostgreSQL
Guide to PostgreSQL PerformanceHow to Reduce Bloat in Large PostgreSQL TablesDesigning Your Database Schema: Wide vs. Narrow Postgres TablesBest Practices for Time-Series Data Modeling: Single or Multiple Partitioned Table(s) a.k.a. Hypertables Best Practices for (Time-)Series Metadata Tables A Guide to Data Analysis on PostgreSQLA Guide to Scaling PostgreSQLGuide to PostgreSQL SecurityHandling Large Objects in PostgresHow to Query JSON Metadata in PostgreSQLHow to Query JSONB in PostgreSQLHow to Use PostgreSQL for Data TransformationOptimizing Array Queries With GIN Indexes in PostgreSQLPg_partman vs. Hypertables for Postgres PartitioningPostgreSQL Performance Tuning: Designing and Implementing Your Database SchemaPostgreSQL Performance Tuning: Key ParametersPostgreSQL Performance Tuning: Optimizing Database IndexesDetermining the Optimal Postgres Partition SizeNavigating Growing PostgreSQL Tables With Partitioning (and More)Top PostgreSQL Drivers for PythonWhen to Consider Postgres PartitioningGuide to PostgreSQL Database OperationsUnderstanding PostgreSQL TablespacesWhat Is Audit Logging and How to Enable It in PostgreSQLGuide to Postgres Data ManagementHow to Index JSONB Columns in PostgreSQLHow to Monitor and Optimize PostgreSQL Index PerformanceSQL/JSON Data Model and JSON in SQL: A PostgreSQL PerspectiveA Guide to pg_restore (and pg_restore Example)PostgreSQL Performance Tuning: How to Size Your DatabaseAn Intro to Data Modeling on PostgreSQLExplaining PostgreSQL EXPLAINWhat Is a PostgreSQL Temporary View?A PostgreSQL Database Replication GuideHow to Compute Standard Deviation With PostgreSQLHow PostgreSQL Data Aggregation WorksBuilding a Scalable DatabaseRecursive Query in SQL: What It Is, and How to Write OneGuide to PostgreSQL Database DesignHow to Use Psycopg2: The PostgreSQL Adapter for Python
Best Practices for Scaling PostgreSQLHow to Design Your PostgreSQL Database: Two Schema ExamplesHow to Handle High-Cardinality Data in PostgreSQLHow to Store Video in PostgreSQL Using BYTEABest Practices for PostgreSQL Database OperationsHow to Manage Your Data With Data Retention PoliciesBest Practices for PostgreSQL AggregationBest Practices for Postgres Database ReplicationHow to Use a Common Table Expression (CTE) in SQLBest Practices for Postgres Data ManagementBest Practices for Postgres PerformanceBest Practices for Postgres SecurityBest Practices for PostgreSQL Data AnalysisTesting Postgres Ingest: INSERT vs. Batch INSERT vs. COPYHow to Use PostgreSQL for Data Normalization
PostgreSQL Extensions: amcheckPostgreSQL Extensions: Unlocking Multidimensional Points With Cube PostgreSQL Extensions: hstorePostgreSQL Extensions: ltreePostgreSQL Extensions: Secure Your Time-Series Data With pgcryptoPostgreSQL Extensions: pg_prewarmPostgreSQL Extensions: pgRoutingPostgreSQL Extensions: pg_stat_statementsPostgreSQL Extensions: Install pg_trgm for Data MatchingPostgreSQL Extensions: Turning PostgreSQL Into a Vector Database With pgvectorPostgreSQL Extensions: Database Testing With pgTAPPostgreSQL Extensions: PL/pgSQLPostgreSQL Extensions: Using PostGIS and Timescale for Advanced Geospatial InsightsPostgreSQL Extensions: Intro to uuid-ossp
Columnar Databases vs. Row-Oriented Databases: Which to Choose?Data Analytics vs. Real-Time Analytics: How to Pick Your Database (and Why It Should Be PostgreSQL)How to Choose a Real-Time Analytics DatabaseUnderstanding OLTPOLAP Workloads on PostgreSQL: A GuideHow to Choose an OLAP DatabasePostgreSQL as a Real-Time Analytics DatabaseWhat Is the Best Database for Real-Time AnalyticsHow to Build an IoT Pipeline for Real-Time Analytics in PostgreSQL
When Should You Use Full-Text Search vs. Vector Search?HNSW vs. DiskANNA Brief History of AI: How Did We Get Here, and What's Next?A Beginner’s Guide to Vector EmbeddingsPostgreSQL as a Vector Database: A Pgvector TutorialUsing Pgvector With PythonHow to Choose a Vector DatabaseVector Databases Are the Wrong AbstractionUnderstanding DiskANNA Guide to Cosine SimilarityStreaming DiskANN: How We Made PostgreSQL as Fast as Pinecone for Vector DataImplementing Cosine Similarity in PythonVector Database Basics: HNSWVector Database Options for AWSVector Store vs. Vector Database: Understanding the ConnectionPgvector vs. Pinecone: Vector Database Performance and Cost ComparisonHow to Build LLM Applications With Pgvector Vector Store in LangChainHow to Implement RAG With Amazon Bedrock and LangChainRetrieval-Augmented Generation With Claude Sonnet 3.5 and PgvectorRAG Is More Than Just Vector SearchPostgreSQL Hybrid Search Using Pgvector and CohereImplementing Filtered Semantic Search Using Pgvector and JavaScriptRefining Vector Search Queries With Time Filters in Pgvector: A TutorialUnderstanding Semantic SearchWhat Is Vector Search? Vector Search vs Semantic SearchText-to-SQL: A Developer’s Zero-to-Hero GuideNearest Neighbor Indexes: What Are IVFFlat Indexes in Pgvector and How Do They WorkBuilding an AI Image Gallery With OpenAI CLIP, Claude Sonnet 3.5, and Pgvector
Understanding IoT (Internet of Things)A Beginner’s Guide to IIoT and Industry 4.0Storing IoT Data: 8 Reasons Why You Should Use PostgreSQLMoving Past Legacy Systems: Data Historian vs. Time-Series DatabaseWhy You Should Use PostgreSQL for Industrial IoT DataHow to Choose an IoT DatabaseHow to Simulate a Basic IoT Sensor Dataset on PostgreSQLFrom Ingest to Insights in Milliseconds: Everactive's Tech Transformation With TimescaleHow Ndustrial Is Providing Fast Real-Time Queries and Safely Storing Client Data With 97 % CompressionHow Hopthru Powers Real-Time Transit Analytics From a 1 TB Table Migrating a Low-Code IoT Platform Storing 20M Records/DayHow United Manufacturing Hub Is Introducing Open Source to ManufacturingBuilding IoT Pipelines for Faster Analytics With IoT CoreVisualizing IoT Data at Scale With Hopara and TimescaleDB
What Is ClickHouse and How Does It Compare to PostgreSQL and TimescaleDB for Time Series?Timescale vs. Amazon RDS PostgreSQL: Up to 350x Faster Queries, 44 % Faster Ingest, 95 % Storage Savings for Time-Series DataWhat We Learned From Benchmarking Amazon Aurora PostgreSQL ServerlessTimescaleDB vs. Amazon Timestream: 6,000x Higher Inserts, 5-175x Faster Queries, 150-220x CheaperHow to Store Time-Series Data in MongoDB and Why That’s a Bad IdeaPostgreSQL + TimescaleDB: 1,000x Faster Queries, 90 % Data Compression, and Much MoreEye or the Tiger: Benchmarking Cassandra vs. TimescaleDB for Time-Series Data
Alternatives to RDSWhy Is RDS so Expensive? Understanding RDS Pricing and CostsEstimating RDS CostsHow to Migrate From AWS RDS for PostgreSQL to TimescaleAmazon Aurora vs. RDS: Understanding the Difference
5 InfluxDB Alternatives for Your Time-Series Data8 Reasons to Choose Timescale as Your InfluxDB Alternative InfluxQL, Flux, and SQL: Which Query Language Is Best? (With Cheatsheet)What InfluxDB Got WrongTimescaleDB vs. InfluxDB: Purpose Built Differently for Time-Series Data
5 Ways to Monitor Your PostgreSQL DatabaseHow to Migrate Your Data to Timescale (3 Ways)Postgres TOAST vs. Timescale CompressionBuilding Python Apps With PostgreSQL: A Developer's GuideData Visualization in PostgreSQL With Apache SupersetMore Time-Series Data Analysis, Fewer Lines of Code: Meet HyperfunctionsIs Postgres Partitioning Really That Hard? An Introduction To HypertablesPostgreSQL Materialized Views and Where to Find ThemTimescale Tips: Testing Your Chunk Size
Postgres cheat sheet
HomeTime series basicsPostgres basicsPostgres guidesPostgres best practicesPostgres extensionsPostgres for real-time analytics
Sections

AI and vector fundamentals

A Brief History of AI: How Did We Get Here, and What's Next?A Beginner’s Guide to Vector EmbeddingsPostgreSQL as a Vector Database: A Pgvector TutorialUsing Pgvector With PythonHow to Choose a Vector DatabaseVector Databases Are the Wrong Abstraction

Cosine similarity

A Guide to Cosine SimilarityImplementing Cosine Similarity in Python

Vector databases

Vector Database Options for AWSVector Store vs. Vector Database: Understanding the Connection

Tutorials

How to Build LLM Applications With Pgvector Vector Store in LangChainHow to Implement RAG With Amazon Bedrock and LangChainRetrieval-Augmented Generation With Claude Sonnet 3.5 and PgvectorRAG Is More Than Just Vector Search

Hybrid search & filtering

PostgreSQL Hybrid Search Using Pgvector and CohereImplementing Filtered Semantic Search Using Pgvector and JavaScriptRefining Vector Search Queries With Time Filters in Pgvector: A Tutorial

Image search

Building an AI Image Gallery With OpenAI CLIP, Claude Sonnet 3.5, and Pgvector

Semantic search

Fundamentals

Understanding Semantic SearchWhat Is Vector Search? Vector Search vs Semantic SearchWhen Should You Use Full-Text Search vs. Vector Search?

Vectorscale

Fundamentals

Understanding DiskANN

Schema design

Streaming DiskANN: How We Made PostgreSQL as Fast as Pinecone for Vector Data
Vector Database Basics: HNSW

Benchmarks

Pgvector vs. Pinecone: Vector Database Performance and Cost Comparison

Fundamentals

HNSW vs. DiskANN
Nearest Neighbor Indexes: What Are IVFFlat Indexes in Pgvector and How Do They Work

AI query interfaces

Text-to-SQL: A Developer’s Zero-to-Hero Guide

Products

Time Series and Analytics AI and Vector Enterprise Plan Cloud Status Support Security Cloud Terms of Service

Learn

Documentation Blog Forum Tutorials Changelog Success Stories Time Series Database

Company

Contact Us Careers About Brand Community Code Of Conduct Events

Subscribe to the Tiger Data Newsletter

By submitting, you acknowledge Tiger Data's Privacy Policy

2025 (c) Timescale, Inc., d/b/a Tiger Data. All rights reserved.

Privacy preferences
LegalPrivacySitemap

Published at Oct 30, 2024

Implementing Cosine Similarity in Python

Explore for free

AI development for all developers, not just AI experts. Build your AI app with Tiger Cloud today.

Written by Haziqa Sajid

Embeddings map language to vectors, while cosine similarity measures relationships between them, enabling various artificial intelligence (AI) applications. Cosine similarity calculates the angle between two vectors—similar vectors score 1, while dissimilar ones score 0. We explored the topic in depth in a previous article and explained how cosine similarity is used in AI systems.

image

This time, we will focus on implementing cosine similarity from scratch using Python. You will be able to touch the insides of the computation, locate bottlenecks in the algorithm, and look for essential tool optimizations to improve its performance. Let’s jump right in.

Basic Cosine Similarity Implementation in Python

Cosine similarity measures the similarity between two non-zero vectors by calculating the cosine of the angle between them in vector space. Simply put, it tells us how close two vectors are, regardless of their magnitude. 

Cosine similarity formula

The formula for cosine similarity between two vectors, X and Y, is:

image

Here, X and Y represent two vectors in an n-dimensional space, meaning they are numerical arrays of the same length, such as:

image

The cosine similarity is computed by taking the inner product of X and Y, and dividing it by the product of their magnitudes.

Inner product function

The first step is calculating the inner product (the dot product) between the two vectors. This is done by multiplying each pair of corresponding elements from the two vectors and summing the results.

Here’s the Python function to compute the inner product:

def inner_prod(X, Y):   sum_prod = 0   for x_i, y_i in zip(X, Y):       sum_prod += x_i * y_i   return sum_prod

This function loops over the entries of X and Y, multiplies each pair 𝑥i​ and 𝑦i​, and adds them to sum_prod, which is returned at the end.

Magnitude function

The magnitude (Euclidean norm) of a vector X is calculated by squaring each element, summing them, and taking the square root of the sum. The same calculation is applied to vector Y.

Here’s the Python function to compute the magnitude of a vector:

import math def magnitude(X):   sum_squares = 0   for x_i in X:       sum_squares += x_i ** 2   return math.sqrt(sum_squares)

In this function, sum_squares accumulates the sum of squares of all elements in X, and then the square root is taken to return the final magnitude.

Complete cosine similarity code

Now, we combine the inner product and magnitude functions to calculate cosine similarity:

def cosine_similarity(X, Y):   return inner_prod(X, Y) / (magnitude(X) * magnitude(Y))

This function simply calls the inner product and magnitude functions and returns the cosine similarity by dividing the dot product by the product of the magnitudes of X and Y.

Algorithm analysis

For vectors with 𝑛 entries:

  • The inner product computation requires 2𝑛 operations (one multiplication and one addition per element).

  • The magnitude computation for each vector involves 2𝑛 + 1 operations (squaring, summing, and taking the square root).

  • The algorithm's total complexity is O(6n), which means it scales linearly with the vector length or “dimension.”

This makes cosine similarity computation highly efficient for moderate dimensions. However, AI systems often work with vector embeddings with dimensions in the millions or even billions of numerical values. As a result, the computational cost increases significantly, primarily when cosine similarity is used in pairwise searches across large datasets.

Search With Cosine Similarity

In practice, cosine similarity is often used to search a database of vectors to find those most similar to a given query vector. The goal is to rank the vectors by their cosine similarity, where the results closer to 1 are more similar to the query vector, and those closer to -1 are dissimilar.

For instance, suppose we have a database of vectors Vector_db = [Y_0, Y_1, ..., Y_(m-1)] and a query vector X. We can perform a pairwise search by calculating the cosine similarity between X and each vector 𝑦i in the database. The vectors can then be sorted in descending order based on their similarity to the query vector.

Naive pairwise search code

This function performs a pairwise search by calculating cosine similarity between a query vector and each vector in a database, returning the results sorted by similarity in descending order. Here’s a naive implementation of a pairwise search with cosine similarity:

def search_db(X, vector_db):     results = []     for Y_i in vector_db:         similarity = cosine_similarity(X, Y_i)         results.append((Y_i, similarity))         # Sort by similarity in descending order     results.sort(key=lambda x: x[1], reverse=True)         return results

In this code, the function search_db takes a query vector X and a database of vectors vector_db. For each vector 𝑦i in the database, we calculate the cosine similarity using our previously defined cosine_similarity function. The results are appended to a list sorted by the similarity score in descending order.

Explanation of inefficiencies

While this method works for small datasets, it becomes inefficient as the vector database grows. Here are the main issues with naive pairwise search code:

  • Computational complexity: The naive approach requires calculating cosine similarity 𝑚 times, where 𝑚 is the number of vectors in the database. This alone makes it scale poorly with large datasets.

  • Dimensional scaling: For each similarity computation, we must consider the dimensionality of the vectors. High-dimensional vectors (common in AI applications) require more time to compute their cosine similarity.

  • Sorting overhead: After calculating the similarities, the function creates and sorts an array of length 𝑚 to produce ranked results. Sorting further adds computational overhead.

This naive approach becomes impractical for large databases with high-dimensional vectors. The sheer volume of computations makes it a severe bottleneck for performance.

Nearest neighbors search algorithms

The process of ranking vectors based on similarity is called nearest neighbors (NN) search. Various algorithms and techniques have been developed to improve the efficiency of similarity searches. These methods optimize the search by adding extra structures to the vector data and reducing the number of complete pairwise comparisons.

HNSW (hierarchical navigable small world)

HNSW is an algorithm designed to efficiently search large vector databases. It organizes the data into multiple layers, starting with a sparse layer containing only a few vectors. The algorithm searches through the layers, moving in the direction of the query vector, from lower to higher similarity.

  • How it works: Starting at the sparse top layer, the algorithm moves through each layer to get closer to the most similar vectors. The search progressively refines itself as it navigates through denser layers.

  • Performance: This method significantly speeds up the search process while maintaining high accuracy.

More information on HNSW can be found here.

Centroid indexing

Centroid indexing is another optimization technique for searching for nearest neighbors. In this approach, the vectors in the database are clustered, and each cluster's centroid (average vector) is calculated.

  • How it works: Instead of comparing the query vector against all database vectors, the algorithm first finds the most similar centroid. It then searches only within that cluster for the closest vectors.

  • Performance: This method improves efficiency for large datasets by reducing the number of vectors that need to be searched.

A detailed explanation of centroid indexing can be found here.

Approximate nearest neighbor (ANN) methods

ANN methods are designed to significantly speed up similarity computations by sacrificing a small degree of accuracy. These methods use statistical techniques to approximate the nearest neighbors, trading off perfect accuracy for faster search times.

  • How it works: Rather than doing an exhaustive search, ANN algorithms use approximations that may mis-rank some vectors but will return the most relevant results for most cases.

  • Example: Microsoft’s DiskANN, an ANN algorithm, provides substantial performance improvements while only losing about five percent in accuracy. It is optimized to run on standard hardware, like 64 GB of RAM and SSD storage, making it scalable for massive datasets.

You can learn more about DiskANN here.

Cosine Similarity Optimization

Optimization techniques can significantly improve the performance of cosine similarity calculations when dealing with high-dimensional vector spaces. One key area for optimization is using sparse vectors—vectors where many entries are zero. For vectors with billions of dimensions, most entries are often zero, and ignoring them in computations can drastically reduce the workload.

Sparse vector optimization

High-dimensional AI and machine learning vectors often contain many zero entries. These are known as sparse vectors. Zero entries contribute nothing to the inner product's final result and cosine similarity magnitude calculations. So, instead of performing computations on every entry in the vector, we can optimize by focusing only on the non-zero elements.

Non-zero entry optimization

The idea behind optimizing cosine similarity for sparse vectors is first to identify the vectors' non-zero indices. Then, rather than wasting resources computing with zeros, we compute the inner product and magnitude only on the index that matters.

Here’s a function that returns the indices of non-zero elements in a vector:

def non_zero(X):   return [i for i, x in enumerate(X) if x != 0]

Using this non_zero function, we can optimize our inner product calculation by computing only the product of the non-zero elements from both vectors.

def optimized_inner_prod(X, Y):   non_zero_X = non_zero(X)   non_zero_Y = non_zero(Y)   common_indices = set(non_zero_X).intersection(set(non_zero_Y))     inner_product = sum(X[i] * Y[i] for i in common_indices)   return inner_product

In this code, optimized_inner_prod calculates the inner product of two vectors, but only for non-zero indices in both vectors. This calculation avoids unnecessary multiplications involving zeros, making it highly efficient for sparse data.

Storage optimization with sparse vectors

For extremely high-dimensional data systems, optimizing storage becomes crucial. Instead of storing the entire vector—mostly filled with zeros—we can only store the non-zero entries and their corresponding indices. This optimization saves memory and speeds up computation.

For example, a sparse vector can be stored like this:

sparse_vector = {   "indices": [0, 3, 7],   "values": [0.5, -1.2, 3.1] } We can expand the full vector by inserting zeros in the appropriate places when we need it. Storing the non-zero elements in this compressed format can significantly reduce the size of your vector database and improve search times.

Benefits of sparse vector optimization

  • Reduced computational complexity: We skip zero elements, reducing the number of calculations for the inner product and magnitude.

  • Efficient storage: Storing only the non-zero entries of sparse vectors can reduce memory requirements, making the storage of large datasets of high-dimensional vectors feasible.

  • Scalable search: Sparse vectors naturally arise in AI systems that deal with high-dimensional data. Hence, incorporating optimizations like non_zero computations into your data structure ensures scalability, even for billions of entries.

Focusing on the non-zero elements of sparse vectors makes the cosine similarity calculation and vector storage much more efficient, making it feasible to work with high-dimensional data at scale. This is a crucial optimization for AI applications where vectors often have sparse representations.

Cosine Distance Tools

The implementation above still requires further optimizations to be suitable for a production environment. Fortunately, numerous tools are available with built-in cosine similarity functions optimized explicitly for scalability and production use.

Pgvector: Cosine distance in PostgreSQL

Pgvector is an extension designed to store and search high-dimensional vector data within PostgreSQL. It includes a variety of vector distance metrics, including cosine distance, Euclidean distance, and L² distance. Here are some others:

Symbol

Distance Metric

<#>

Negative Inner Product

<~>

Hamming Distance 

<%>

Jaccard Distance

In pgvector, cosine distance is defined as:

image

This metric ranks vector pairs based on how close they are in direction (rather than magnitude), with smaller values representing more similar results. In search queries, vectors are ranked from low to high, with the lowest cosine distance corresponding to the most similar items. 

How to enhance cosine similarity in PostgreSQL

To turn PostgreSQL into a full-fledged platform for AI development that is accessible to all developers, Timescale created an open-source PostgreSQL stack with purpose-built extensions for AI that complement pgvector:

  • pgai brings more AI workflows to PostgreSQL, making it easier for developers to build search and retrieval-augmented generation (RAG) applications.

  • pgvectorscale enables developers to build more scalable AI applications with higher-performance embedding search and cost-efficient storage. It adds a StreamingDiskANN index to pgvector, as well as Statistical Binary Quantization, unlocking large-scale, high-performance AI use cases previously only achievable with specialized vector databases like Pinecone. Compared to Pinecone’s storage-optimized index (s1), PostgreSQL with pgvector and pgvectorscale achieves 28x lower p95 latency and 16x higher query throughput.

  • pgai Vectorizer enables embedding creation within PostgreSQL—no more complicated vector databases or clunky add-ons. Stale embeddings are a thing of the past, and you can test different embedding models and chunking/formatting strategies within PostgreSQL. Compare, tweak, and refine—all in one place.  

Conclusion

Operators like cosine similarity serve as an essential foundation of semantic search. Optimized and efficient cosine similarity computation is critical in a vector-based AI system. Cosine similarity-based nearest-neighbor search opens up many possibilities for AI applications—even the most popular ones, like RAG. 

With Timescale’s open-source stack for AI applications, you can leverage state-of-the-arnearest-neighboror algorithms, combining cosine similarity with other similarity metrics to power your AI tools. 

Timescale made PostgreSQL the powerful database you trust—now it’s your AI platform, too. Pick your deployment option today: you can find self-hosting installation instructions on the pgai, pgvectorscale, and pgai Vectorizer GitHub repositories or quickly access all these extensions on any database service on Timescale’s cloud PostgreSQL platform.

Learn more

  • Building Multi-Tenant RAG Applications With PostgreSQL: Choosing the Right Approach

  • Which OpenAI Embedding Model Is Best for Your RAG App With Pgvector?

On this page

    Explore for free

    AI development for all developers, not just AI experts. Build your AI app with Tiger Cloud today.