|
| 1 | +# Copyright 2024 Google LLC All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Classes for representing vector queries for the Google Cloud Firestore API. |
| 16 | +""" |
| 17 | + |
| 18 | +import abc |
| 19 | + |
| 20 | +from abc import ABC |
| 21 | +from enum import Enum |
| 22 | +from typing import Iterable, Optional, Tuple, Union |
| 23 | +from google.api_core import gapic_v1 |
| 24 | +from google.api_core import retry as retries |
| 25 | +from google.cloud.firestore_v1.base_document import DocumentSnapshot |
| 26 | +from google.cloud.firestore_v1.types import query |
| 27 | +from google.cloud.firestore_v1.vector import Vector |
| 28 | +from google.cloud.firestore_v1 import _helpers |
| 29 | + |
| 30 | + |
| 31 | +class DistanceMeasure(Enum): |
| 32 | + EUCLIDEAN = 1 |
| 33 | + COSINE = 2 |
| 34 | + DOT_PRODUCT = 3 |
| 35 | + |
| 36 | + |
| 37 | +class BaseVectorQuery(ABC): |
| 38 | + """Represents a vector query to the Firestore API.""" |
| 39 | + |
| 40 | + def __init__(self, nested_query) -> None: |
| 41 | + self._nested_query = nested_query |
| 42 | + self._collection_ref = nested_query._parent |
| 43 | + self._vector_field: Optional[str] = None |
| 44 | + self._query_vector: Optional[Vector] = None |
| 45 | + self._limit: Optional[int] = None |
| 46 | + self._distance_measure: Optional[DistanceMeasure] = None |
| 47 | + |
| 48 | + @property |
| 49 | + def _client(self): |
| 50 | + return self._collection_ref._client |
| 51 | + |
| 52 | + def _to_protobuf(self) -> query.StructuredQuery: |
| 53 | + pb = query.StructuredQuery() |
| 54 | + |
| 55 | + distance_measure_proto = None |
| 56 | + if self._distance_measure == DistanceMeasure.EUCLIDEAN: |
| 57 | + distance_measure_proto = ( |
| 58 | + query.StructuredQuery.FindNearest.DistanceMeasure.EUCLIDEAN |
| 59 | + ) |
| 60 | + elif self._distance_measure == DistanceMeasure.COSINE: |
| 61 | + distance_measure_proto = ( |
| 62 | + query.StructuredQuery.FindNearest.DistanceMeasure.COSINE |
| 63 | + ) |
| 64 | + elif self._distance_measure == DistanceMeasure.DOT_PRODUCT: |
| 65 | + distance_measure_proto = ( |
| 66 | + query.StructuredQuery.FindNearest.DistanceMeasure.DOT_PRODUCT |
| 67 | + ) |
| 68 | + else: |
| 69 | + raise ValueError("Invalid distance_measure") |
| 70 | + |
| 71 | + pb = self._nested_query._to_protobuf() |
| 72 | + pb.find_nearest = query.StructuredQuery.FindNearest( |
| 73 | + vector_field=query.StructuredQuery.FieldReference( |
| 74 | + field_path=self._vector_field |
| 75 | + ), |
| 76 | + query_vector=_helpers.encode_value(self._query_vector), |
| 77 | + distance_measure=distance_measure_proto, |
| 78 | + limit=self._limit, |
| 79 | + ) |
| 80 | + return pb |
| 81 | + |
| 82 | + def _prep_stream( |
| 83 | + self, |
| 84 | + transaction=None, |
| 85 | + retry: Union[retries.Retry, None, gapic_v1.method._MethodDefault] = None, |
| 86 | + timeout: Optional[float] = None, |
| 87 | + ) -> Tuple[dict, str, dict]: |
| 88 | + parent_path, expected_prefix = self._collection_ref._parent_info() |
| 89 | + request = { |
| 90 | + "parent": parent_path, |
| 91 | + "structured_query": self._to_protobuf(), |
| 92 | + "transaction": _helpers.get_transaction_id(transaction), |
| 93 | + } |
| 94 | + kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout) |
| 95 | + |
| 96 | + return request, expected_prefix, kwargs |
| 97 | + |
| 98 | + @abc.abstractmethod |
| 99 | + def get( |
| 100 | + self, |
| 101 | + transaction=None, |
| 102 | + retry: retries.Retry = gapic_v1.method.DEFAULT, |
| 103 | + timeout: Optional[float] = None, |
| 104 | + ) -> Iterable[DocumentSnapshot]: |
| 105 | + """Runs the vector query.""" |
| 106 | + |
| 107 | + def find_nearest( |
| 108 | + self, |
| 109 | + vector_field: str, |
| 110 | + query_vector: Vector, |
| 111 | + limit: int, |
| 112 | + distance_measure: DistanceMeasure, |
| 113 | + ): |
| 114 | + """Finds the closest vector embeddings to the given query vector.""" |
| 115 | + self._vector_field = vector_field |
| 116 | + self._query_vector = query_vector |
| 117 | + self._limit = limit |
| 118 | + self._distance_measure = distance_measure |
| 119 | + return self |
0 commit comments