Add support for Cosine Similarity by enzofrnt · Pull Request #109 · pgvector/pgvector-python

This pull request introduces a new CosineSimilarity function to the pgvector Django integration and updates the corresponding tests. The most important changes include adding the CosineSimilarity function, updating imports, and adding a new test case for CosineSimilarity.

CosineSimilarity must be useful for people who are wondering to use similarity instead of distance.

New feature addition:

  • pgvector/django/functions.py: Added a new class CosineSimilarity that inherits from DistanceBase and overrides the as_sql method to compute cosine similarity.

Import updates:

Test updates:

  • tests/test_django.py: Added
    This pull request introduces a new CosineSimilarity function to the pgvector Django package, along with corresponding tests. The changes primarily involve adding this new function and ensuring it is properly tested across different vector types.

Key Changes:

New Functionality:

  • Added CosineSimilarity class to pgvector/django/functions.py to calculate cosine similarity.

Import Adjustments:

  • Updated imports in pgvector/django/__init__.py to include CosineSimilarity.
  • Updated imports in tests/test_django.py to include CosineSimilarity.

Testing Enhancements:

  • Added test_vector_cosine_similarity method to test cosine similarity for regular vectors in tests/test_django.py.
  • Added test_halfvec_cosine_similarity method to test cosine similarity for half vectors in tests/test_django.py.
  • Added test_sparsevec_cosine_similarity method to test cosine similarity for sparse vectors in tests/test_django.py.