Skip to content

Conversation

@Fujio-Turner
Copy link

Summary

Add vector search support to cbl-reactnative, enabling APPROX_VECTOR_DISTANCE() queries for similarity search.

Changes

Android:

  • android/src/main/java/com/cblreactnative/CollectionManagerVector.kt - Vector index creation helper

Features

  • Create vector indexes with VectorIndexConfiguration
  • Support all distance metrics (cosine, euclidean, euclideanSquared, dot)
  • Support encoding options (none, SQ, PQ)
  • Support training size and probe parameters

Related PRs

This PR depends on:

Usage

import {
  VectorIndexConfiguration,
  DistanceMetric,
} from 'cbl-reactnative';

// Create vector index
const config = new VectorIndexConfiguration('embedding', 512, 100);
config.metric = DistanceMetric.COSINE;
await collection.createIndex('embedding_idx', config);

// Query with vector distance
const query = \`
  SELECT META().id, APPROX_VECTOR_DISTANCE(embedding, \$qv) AS distance
  FROM catalog.vectors
  ORDER BY APPROX_VECTOR_DISTANCE(embedding, \$qv)
  LIMIT 10
\`;

Closes #86

Add vector index creation support for Android:
- CollectionManagerVector.kt helper for vector indexes
- Handle 'vector' case in createIndex

Ref: Couchbase-Ecosystem#86
@gemini-code-assist
Copy link

Summary of Changes

Hello @Fujio-Turner, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request integrates vector search functionality into the cbl-reactnative library, allowing developers to perform efficient similarity searches within their Couchbase Lite databases. It introduces a new mechanism for creating and configuring vector indexes with support for multiple distance metrics and encoding strategies, significantly enhancing the data querying capabilities for React Native applications.

Highlights

  • Vector Search Support: Introduces vector search capabilities to cbl-reactnative, enabling similarity searches using APPROX_VECTOR_DISTANCE() queries.
  • Flexible Index Configuration: Allows creation of vector indexes with VectorIndexConfiguration, supporting various distance metrics (cosine, euclidean, euclideanSquared, dot) and encoding options (none, Scalar Quantizer (SQ), Product Quantizer (PQ)).
  • Training and Probe Parameters: Supports configuration of optional training parameters such as minTrainingSize, maxTrainingSize, numProbes, and isLazy for fine-tuning index behavior.
  • Android Implementation: Adds a new Kotlin file, CollectionManagerVector.kt, which provides the core logic for creating and configuring vector indexes on the Android platform.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for creating vector indexes on Android. The new createVectorIndex function in CollectionManagerVector.kt correctly parses the configuration map to build a VectorIndexConfiguration.

My review includes a few suggestions to improve robustness and error handling:

  • Using more specific exceptions (IllegalArgumentException) for invalid parameters.
  • Implementing stricter validation for configuration options like metric and encoding to prevent silent failures from typos.
  • Fixing a potential runtime crash in Product Quantizer (PQ) configuration due to an invalid default value.

Overall, the changes are a great addition. Once these suggestions are addressed, the code will be more robust.

Comment on lines +60 to +79
vectorConfig.encoding = when (encodingType) {
"none" -> VectorEncoding.none()
"SQ" -> {
// Scalar Quantizer - determine type from config or default to SQ8
val sqType = encodingConfig["sqType"] as? String
when (sqType) {
"SQ4" -> VectorEncoding.scalarQuantizer(ScalarQuantizerType.SQ4)
"SQ6" -> VectorEncoding.scalarQuantizer(ScalarQuantizerType.SQ6)
"SQ8" -> VectorEncoding.scalarQuantizer(ScalarQuantizerType.SQ8)
else -> VectorEncoding.scalarQuantizer(ScalarQuantizerType.SQ8)
}
}
"PQ" -> {
// Product Quantizer
val subquantizers = (encodingConfig["subquantizers"] as? Number)?.toLong() ?: 0
val bits = (encodingConfig["bits"] as? Number)?.toLong() ?: 8
VectorEncoding.productQuantizer(subquantizers, bits)
}
else -> VectorEncoding.none()
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This block has a few areas for improvement:

  1. Strict Validation: The when statements for encodingType and sqType use default fallbacks for unknown values, which can hide configuration errors. It's better to throw an IllegalArgumentException for invalid values.
  2. Invalid subquantizers default: For "PQ" encoding, subquantizers defaults to 0, which is an invalid value and will cause a runtime error. This parameter should be required and validated for "PQ" encoding.

Here is a suggested refactoring that addresses these points.

        vectorConfig.encoding = when (encodingType) {
            "none", null -> VectorEncoding.none()
            "SQ" -> {
                // Scalar Quantizer - determine type from config or default to SQ8
                val sqType = encodingConfig["sqType"] as? String
                when (sqType) {
                    "SQ4" -> VectorEncoding.scalarQuantizer(ScalarQuantizerType.SQ4)
                    "SQ6" -> VectorEncoding.scalarQuantizer(ScalarQuantizerType.SQ6)
                    "SQ8", null -> VectorEncoding.scalarQuantizer(ScalarQuantizerType.SQ8)
                    else -> throw IllegalArgumentException("Unknown Scalar Quantizer type: $sqType")
                }
            }
            "PQ" -> {
                // Product Quantizer
                val subquantizers = (encodingConfig["subquantizers"] as? Number)?.toLong()
                    ?: throw IllegalArgumentException("Product Quantizer encoding requires 'subquantizers' parameter")
                if (subquantizers <= 0) {
                    throw IllegalArgumentException("'subquantizers' must be a positive number")
                }
                val bits = (encodingConfig["bits"] as? Number)?.toLong() ?: 8
                VectorEncoding.productQuantizer(subquantizers, bits)
            }
            else -> throw IllegalArgumentException("Unknown vector encoding type: $encodingType")
        }

Comment on lines +32 to +39
val expression = indexConfig["expression"] as? String
?: throw Exception("Vector index requires 'expression' parameter")

val dimensions = (indexConfig["dimensions"] as? Number)?.toLong()
?: throw Exception("Vector index requires 'dimensions' parameter")

val centroids = (indexConfig["centroids"] as? Number)?.toLong()
?: throw Exception("Vector index requires 'centroids' parameter")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For better error handling and clarity, it's recommended to throw a more specific exception like IllegalArgumentException instead of the generic Exception when a required parameter is missing. This helps callers to better understand and handle the error. Please apply this to all three required parameter checks (expression, dimensions, centroids) and update the function's KDoc @throws tag accordingly.

Suggested change
val expression = indexConfig["expression"] as? String
?: throw Exception("Vector index requires 'expression' parameter")
val dimensions = (indexConfig["dimensions"] as? Number)?.toLong()
?: throw Exception("Vector index requires 'dimensions' parameter")
val centroids = (indexConfig["centroids"] as? Number)?.toLong()
?: throw Exception("Vector index requires 'centroids' parameter")
val expression = indexConfig["expression"] as? String
?: throw IllegalArgumentException("Vector index requires 'expression' parameter")
val dimensions = (indexConfig["dimensions"] as? Number)?.toLong()
?: throw IllegalArgumentException("Vector index requires 'dimensions' parameter")
val centroids = (indexConfig["centroids"] as? Number)?.toLong()
?: throw IllegalArgumentException("Vector index requires 'centroids' parameter")

Comment on lines +47 to +53
vectorConfig.metric = when (metricStr) {
"cosine" -> DistanceMetric.COSINE
"euclidean" -> DistanceMetric.EUCLIDEAN
"euclideanSquared" -> DistanceMetric.EUCLIDEAN_SQUARED
"dot" -> DistanceMetric.DOT
else -> DistanceMetric.EUCLIDEAN_SQUARED // Default
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The when statement for metric has a default case that silently uses DistanceMetric.EUCLIDEAN_SQUARED for any unrecognized string. This can hide configuration mistakes (e.g., a typo in the metric name). It would be safer to throw an IllegalArgumentException for unknown values to provide clear feedback to the developer.

Suggested change
vectorConfig.metric = when (metricStr) {
"cosine" -> DistanceMetric.COSINE
"euclidean" -> DistanceMetric.EUCLIDEAN
"euclideanSquared" -> DistanceMetric.EUCLIDEAN_SQUARED
"dot" -> DistanceMetric.DOT
else -> DistanceMetric.EUCLIDEAN_SQUARED // Default
}
vectorConfig.metric = when (metricStr) {
"cosine" -> DistanceMetric.COSINE
"euclidean" -> DistanceMetric.EUCLIDEAN
"euclideanSquared" -> DistanceMetric.EUCLIDEAN_SQUARED
"dot" -> DistanceMetric.DOT
else -> throw IllegalArgumentException("Unknown distance metric: $metricStr")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Support for Vector Search (APPROX_VECTOR_DISTANCE) in SQL++ Queries

1 participant