From 0cc5208c4768242c430e5bf168d88011f3a0c3d6 Mon Sep 17 00:00:00 2001 From: ilai Date: Wed, 21 Dec 2022 16:30:38 +0200 Subject: [PATCH 01/25] [config] Added TCP Keep Alive mechanism This fixes the error of "Connection Reset by peer" after a long idle period --- pinecone/config.py | 56 ++++++++++++++++++++++++++++++-- pinecone/core/utils/constants.py | 4 +++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/pinecone/config.py b/pinecone/config.py index 876b34d10..272ee3a50 100644 --- a/pinecone/config.py +++ b/pinecone/config.py @@ -2,17 +2,22 @@ # Copyright (c) 2020-2021 Pinecone Systems Inc. All right reserved. # import logging -from typing import NamedTuple +import sys +from typing import NamedTuple, List import os import certifi import requests import configparser +import socket + +from urllib3.connection import HTTPConnection from pinecone.core.client.exceptions import ApiKeyError from pinecone.core.api_action import ActionAPI, WhoAmIResponse from pinecone.core.utils import warn_deprecated -from pinecone.core.utils.constants import CLIENT_VERSION, PARENT_LOGGER_NAME, DEFAULT_PARENT_LOGGER_LEVEL +from pinecone.core.utils.constants import CLIENT_VERSION, PARENT_LOGGER_NAME, DEFAULT_PARENT_LOGGER_LEVEL, \ + TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT from pinecone.core.client.configuration import Configuration as OpenApiConfiguration __all__ = [ @@ -109,6 +114,8 @@ def reset(self, config_file=None, **kwargs): or default_openapi_config ) + openapi_config.socket_options = self._get_socket_options() + config = config._replace(openapi_config=openapi_config) self._config = config @@ -144,6 +151,51 @@ def _load_config_file(self, config_file: str) -> dict: config_obj = {**parser["default"]} return config_obj + @staticmethod + def _get_socket_options(do_keep_alive: bool = True, + keep_alive_idle_sec: int = TCP_KEEPIDLE, + keep_alive_interval_sec: int = TCP_KEEPINTVL, + keep_alive_tries: int = TCP_KEEPCNT + ) -> List[tuple]: + """ + Returns the socket options to pass to OpenAPI's Rest client + Args: + do_keep_alive: Whether to enable TCP keep alive mechanism + keep_alive_idle_sec: Time in seconds of connection idleness before starting to send keep alive probes + keep_alive_interval_sec: Interval time in seconds between keep alive probe messages + keep_alive_tries: Number of failed keep alive tries (unanswered KA messages) before terminating the connection + + Returns: + A list of socket options for the Rest client's connection pool + """ + # Source: https://www.finbourne.com/blog/the-mysterious-hanging-client-tcp-keep-alives + + socket_params = HTTPConnection.default_socket_options + if not do_keep_alive: + return socket_params + + socket_params += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] + + # TCP Keep Alive Probes for different platforms + platform = sys.platform + # TCP Keep Alive Probes for Linux + if platform == 'linux' and hasattr(socket, "TCP_KEEPIDLE") and hasattr(socket, "TCP_KEEPINTVL") \ + and hasattr(socket, "TCP_KEEPCNT"): + socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, keep_alive_idle_sec)] + socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, keep_alive_interval_sec)] + socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, keep_alive_tries)] + + # TCP Keep Alive Probes for Windows OS + elif platform == 'win32' and hasattr(socket, "SIO_KEEPALIVE_VALS"): + socket_params += [(socket.SIO_KEEPALIVE_VALS, (1, keep_alive_idle_sec * 1000, keep_alive_interval_sec * 1000))] + + # TCP Keep Alive Probes for Mac OS + elif platform == 'darwin': + TCP_KEEPALIVE = 0x10 + socket_params += [(socket.IPPROTO_TCP, TCP_KEEPALIVE, keep_alive_interval_sec)] + + return socket_params + @property def ENVIRONMENT(self): return self._config.environment diff --git a/pinecone/core/utils/constants.py b/pinecone/core/utils/constants.py index e7ed81b54..d03f1a71c 100644 --- a/pinecone/core/utils/constants.py +++ b/pinecone/core/utils/constants.py @@ -33,3 +33,7 @@ class NodeType(str, enum.Enum): PACKAGE_ENVIRONMENT = get_environment() or "development" CLIENT_VERSION = get_version() CLIENT_ID = f'python-client-{CLIENT_VERSION}' + +TCP_KEEPINTVL = 60 # Sec +TCP_KEEPIDLE = 300 # Sec +TCP_KEEPCNT = 4 From 53ec4741d017219690015c5aa578538aae9285d0 Mon Sep 17 00:00:00 2001 From: ilai Date: Thu, 22 Dec 2022 10:55:52 +0200 Subject: [PATCH 02/25] [config] Use default KeepAlive params on windows Changing TCP params on windows requires a different mechanism than socket.setopts(). Since Open API's Rest client doesn't expose the socket itself (easily) - we will need to use the default params for now. I tested on a Windows Server 2022 machine and this solution seems to be sufficient to aviod the "connection reset after idle" bug. --- pinecone/config.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pinecone/config.py b/pinecone/config.py index 272ee3a50..c365c99c3 100644 --- a/pinecone/config.py +++ b/pinecone/config.py @@ -186,8 +186,11 @@ def _get_socket_options(do_keep_alive: bool = True, socket_params += [(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, keep_alive_tries)] # TCP Keep Alive Probes for Windows OS - elif platform == 'win32' and hasattr(socket, "SIO_KEEPALIVE_VALS"): - socket_params += [(socket.SIO_KEEPALIVE_VALS, (1, keep_alive_idle_sec * 1000, keep_alive_interval_sec * 1000))] + # NOTE: Changing TCP KA params on windows is done via a different mechanism which OpenAPI's Rest client doesn't expose. + # Since the default values work well, it seems setting `(socket.SO_KEEPALIVE, 1)` is sufficient. + # Leaving this code here for future reference. + # elif platform == 'win32' and hasattr(socket, "SIO_KEEPALIVE_VALS"): + # socket.ioctl((socket.SIO_KEEPALIVE_VALS, (1, keep_alive_idle_sec * 1000, keep_alive_interval_sec * 1000))) # TCP Keep Alive Probes for Mac OS elif platform == 'darwin': From f94ec4a4cd2eaf33c09ec241cade1ae9cdba8840 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 22 Dec 2022 11:46:28 +0200 Subject: [PATCH 03/25] add args for rest index --- pinecone/index.py | 87 +++++++++++++++++++++++++++++++++------- tests/unit/test_index.py | 8 ++-- 2 files changed, 76 insertions(+), 19 deletions(-) diff --git a/pinecone/index.py b/pinecone/index.py index 945130e22..42477e206 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -3,9 +3,10 @@ # from collections.abc import Iterable +from typing import Union, List, Tuple, Optional, Dict, Any from pinecone import Config -from pinecone.core.client import ApiClient, Configuration +from pinecone.core.client import ApiClient from .core.client.models import FetchResponse, ProtobufAny, QueryRequest, QueryResponse, QueryVector, RpcStatus, \ ScoredVector, SingleQueryResults, DescribeIndexStatsResponse, UpsertRequest, UpsertResponse, UpdateRequest, \ Vector, DeleteRequest, UpdateRequest, DescribeIndexStatsRequest @@ -56,8 +57,12 @@ def __init__(self, index_name: str, pool_threads=1): self._vector_api = VectorOperationsApi(self) @validate_and_convert_errors - def upsert(self, vectors, **kwargs): + def upsert(self, + vectors: Union[List[Vector], List[Tuple]], + namespace: Optional[str] = None, + **kwargs) -> UpsertResponse: _check_type = kwargs.pop('_check_type', False) + args_dict = self._parse_args_to_dict([('namespace', namespace)]) def _vector_transform(item): if isinstance(item, Vector): @@ -70,6 +75,7 @@ def _vector_transform(item): return self._vector_api.upsert( UpsertRequest( vectors=list(map(_vector_transform, vectors)), + **args_dict, _check_type=_check_type, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS} ), @@ -77,24 +83,64 @@ def _vector_transform(item): ) @validate_and_convert_errors - def delete(self, *args, **kwargs): + def delete(self, + ids: Optional[List[str]] = None, + delete_all: Optional[bool] = None, + namespace: Optional[str] = None, + filter: Optional[Dict[str, Any]] = None, + **kwargs) -> Dict[str, Any]: _check_type = kwargs.pop('_check_type', False) + args_dict = self._parse_args_to_dict([('ids', ids), + ('delete_all', delete_all), + ('namespace', namespace), + ('filter', filter)]) + return self._vector_api.delete( DeleteRequest( - *args, - **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS}, + **args_dict, + **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS and v is not None}, _check_type=_check_type ), **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS} ) @validate_and_convert_errors - def fetch(self, *args, **kwargs): - return self._vector_api.fetch(*args, **kwargs) + def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> FetchResponse: + args_dict = self._parse_args_to_dict([('namespace', namespace)]) + return self._vector_api.fetch(ids, **args_dict, **kwargs) @validate_and_convert_errors - def query(self, vector=[], id='', queries=[], **kwargs): + def query(self, + vector: Optional[List[float]] = None, + id: Optional[str] = None, + queries: Optional[List[QueryVector]] = None, + top_k: Optional[int] = None, + namespace: Optional[str] = None, + filter: Optional[Dict[str, Any]] = None, + include_values: Optional[bool] = None, + include_metadata: Optional[bool] = None, + **kwargs) -> QueryResponse: + + def _query_transform(item): + if isinstance(item, QueryVector): + return item + if isinstance(item, tuple): + values, filter = fix_tuple_length(item, 2) + return QueryVector(values=values, filter=filter, _check_type=_check_type) + if isinstance(item, Iterable): + return QueryVector(values=item, _check_type=_check_type) + raise ValueError(f"Invalid query vector value passed: cannot interpret type {type(item)}") + _check_type = kwargs.pop('_check_type', False) + queries = list(map(_query_transform, queries)) if queries is not None else None + args_dict = self._parse_args_to_dict([('vector', vector), + ('id', id), + ('queries', queries), + ('top_k', top_k), + ('namespace', namespace), + ('filter', filter), + ('include_values', include_values), + ('include_metadata', include_metadata)]) def _query_transform(item): if isinstance(item, QueryVector): @@ -108,34 +154,45 @@ def _query_transform(item): response = self._vector_api.query( QueryRequest( - queries=list(map(_query_transform, queries)), - vector=vector, - id=id, + **args_dict, _check_type=_check_type, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS} ), **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS} ) - return parse_query_response(response, vector or id) + return parse_query_response(response, vector is not None or id) @validate_and_convert_errors - def update(self, id, **kwargs): + def update(self, + id: str, + values: Optional[List[float]] = None, + set_metadata: Optional[Dict[str, Any]] = None, + namespace: Optional[str] = None, + **kwargs): _check_type = kwargs.pop('_check_type', False) + args_dict = self._parse_args_to_dict([('values', values), + ('set_metadata', set_metadata), + ('namespace', namespace)]) return self._vector_api.update(UpdateRequest( id=id, + **args_dict, _check_type=_check_type, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS} ), **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS}) @validate_and_convert_errors - def describe_index_stats(self, *args, **kwargs): + def describe_index_stats(self, filter: Dict[str, Any] = {}, **kwargs) -> DescribeIndexStatsResponse: _check_type = kwargs.pop('_check_type', False) return self._vector_api.describe_index_stats( DescribeIndexStatsRequest( - *args, + filter=filter, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS}, _check_type=_check_type ), **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS} ) + + @staticmethod + def _parse_args_to_dict(args: List[Tuple[str, Any]]) -> Dict[str, Any]: + return {arg_name: val for arg_name, val in args if val is not None} diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 142f1ed7b..25991a89c 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -12,12 +12,12 @@ def test_upsert_request_tuples_id_data(mocker): pinecone.init(api_key='example-key') index = pinecone.Index('example-name') mocker.patch.object(index._vector_api, 'upsert', autospec=True) - index.upsert([('vec1', vals1), ('vec2', vals2)]) + index.upsert([('vec1', vals1), ('vec2', vals2)], namespace='ns') index._vector_api.upsert.assert_called_once_with( pinecone.UpsertRequest(vectors=[ pinecone.Vector(id='vec1', values=vals1, metadata={}), pinecone.Vector(id='vec2', values=vals2, metadata={}) - ]) + ], namespace='ns') ) @@ -43,7 +43,7 @@ def test_query_request_tuples_query_only(mocker): mocker.patch.object(index._vector_api, 'query', autospec=True) index.query(top_k=10, vector=vals1) index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, vector=vals1, id='', queries=[]) + pinecone.QueryRequest(top_k=10, vector=vals1) ) @@ -57,7 +57,7 @@ def test_query_request_tuples_query_filter(mocker): (vals2, filter2) ]) index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, vector=[], id='', queries=[ + pinecone.QueryRequest(top_k=10, queries=[ pinecone.QueryVector(values=vals1, filter=filter1), pinecone.QueryVector(values=vals2, filter=filter2) ]) From 21b8fdd5774ddb50116678e68011edc11fe48ae8 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 22 Dec 2022 13:40:44 +0200 Subject: [PATCH 04/25] add args to grpc index --- pinecone/core/grpc/index_grpc.py | 132 +++++++++++++++++++++---------- pinecone/index.py | 6 +- 2 files changed, 92 insertions(+), 46 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index b7704f520..217d563cb 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -4,20 +4,19 @@ import logging from abc import ABC, abstractmethod from functools import wraps -from typing import NamedTuple, Optional, Dict, Iterable +from typing import NamedTuple, Optional, Dict, Iterable, Union, List, Tuple, Any import certifi import grpc from google.protobuf import json_format from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous -from pinecone import FetchResponse, QueryResponse, ScoredVector, SingleQueryResults, \ - UpsertResponse, DescribeIndexStatsResponse +from pinecone import FetchResponse, QueryResponse, ScoredVector, SingleQueryResults, DescribeIndexStatsResponse from pinecone.config import Config from pinecone.core.client.model.namespace_summary import NamespaceSummary from pinecone.core.client.model.vector import Vector as _Vector from pinecone.core.grpc.protos.vector_service_pb2 import Vector as GRPCVector, \ - QueryVector as GRPCQueryVector, UpsertRequest, DeleteRequest, QueryRequest, \ - FetchRequest, UpdateRequest, DescribeIndexStatsRequest + QueryVector as GRPCQueryVector, UpsertRequest, UpsertResponse, DeleteRequest, QueryRequest, \ + FetchRequest, UpdateRequest, DescribeIndexStatsRequest, DeleteResponse, UpdateResponse from pinecone.core.grpc.protos.vector_service_pb2_grpc import VectorServiceStub from pinecone.core.grpc.retry import RetryOnRpcErrorClientInterceptor, RetryConfig from pinecone.core.utils import _generate_request_id, dict_to_proto_struct, fix_tuple_length @@ -199,11 +198,6 @@ def parse_query_response(response: dict, unary_query: bool): return QueryResponse(**kwargs) -def parse_upsert_response(response): - response = json_format.MessageToDict(response) - return UpsertResponse(upserted_count=response['upsertedCount'], _check_type=False) - - def parse_stats_response(response: dict): fullness = response.get('indexFullness', 0.0) total_vector_count = response.get('totalVectorCount', 0) @@ -255,7 +249,13 @@ class GRPCIndex(GRPCIndexBase): def stub_class(self): return VectorServiceStub - def upsert(self, vectors, async_req=False, **kwargs): + def upsert(self, + vectors: Union[List[GRPCVector], List[Tuple]], + async_req: bool = False, + namespace: Optional[str] = None, + **kwargs) -> Union[UpsertResponse, PineconeGrpcFuture]: + args_dict = self._parse_args_to_dict([('namespace', namespace)]) + def _vector_transform(item): if isinstance(item, GRPCVector): return item @@ -264,7 +264,7 @@ def _vector_transform(item): return GRPCVector(id=id, values=values, metadata=dict_to_proto_struct(metadata) or {}) raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") - request = UpsertRequest(vectors=list(map(_vector_transform, vectors)), **kwargs) + request = UpsertRequest(vectors=list(map(_vector_transform, vectors)), **args_dict, **kwargs) timeout = kwargs.pop('timeout', None) if async_req: future = self._wrap_grpc_call(self.stub.Upsert.future, request, timeout=timeout) @@ -272,12 +272,22 @@ def _vector_transform(item): else: return self._wrap_grpc_call(self.stub.Upsert, request, timeout=timeout) - def delete(self, *args, async_req=False, **kwargs): - _filter = dict_to_proto_struct(kwargs.pop('filter', None)) - filter_param = {} - if _filter: - filter_param['filter'] = _filter - request = DeleteRequest(*args, **kwargs, **filter_param) + def delete(self, + ids: Optional[List[str]] = None, + delete_all: Optional[bool] = None, + namespace: Optional[str] = None, + filter: Optional[Dict[str, Any]] = None, + async_req: bool = False, + **kwargs) -> Union[DeleteResponse, PineconeGrpcFuture]: + if filter is not None: + filter = dict_to_proto_struct(filter) + + args_dict = self._parse_args_to_dict([('ids', ids), + ('delete_all', delete_all), + ('namespace', namespace), + ('filter', filter)]) + + request = DeleteRequest(**args_dict, **kwargs) timeout = kwargs.pop('timeout', None) if async_req: future = self._wrap_grpc_call(self.stub.Delete.future, request, timeout=timeout) @@ -285,16 +295,29 @@ def delete(self, *args, async_req=False, **kwargs): else: return self._wrap_grpc_call(self.stub.Delete, request, timeout=timeout) - def fetch(self, *args, **kwargs): + def fetch(self, + ids: Optional[List[str]], + namespace: Optional[str] = None, + **kwargs) -> FetchResponse: timeout = kwargs.pop('timeout', None) - request = FetchRequest(*args, **kwargs) + + args_dict = self._parse_args_to_dict([('namespace', namespace)]) + + request = FetchRequest(ids=ids, **args_dict, **kwargs) response = self._wrap_grpc_call(self.stub.Fetch, request, timeout=timeout) json_response = json_format.MessageToDict(response) return parse_fetch_response(json_response) - def query(self, vector=[], id='', queries=[], **kwargs): - timeout = kwargs.pop('timeout', None) - + def query(self, + vector: Optional[List[float]] = None, + id: Optional[str] = None, + queries: Optional[Union[List[GRPCQueryVector], List[Tuple]]] = None, + namespace: Optional[str] = None, + top_k: Optional[int] = None, + filter: Optional[Dict[str, Any]] = None, + include_values: Optional[bool] = None, + include_metadata: Optional[bool] = None, + **kwargs) -> QueryResponse: def _query_transform(item): if isinstance(item, GRPCQueryVector): return item @@ -306,22 +329,42 @@ def _query_transform(item): return GRPCQueryVector(values=item) raise ValueError(f"Invalid query vector value passed: cannot interpret type {type(item)}") - _QUERY_ARGS = ['namespace', 'top_k', 'filter', 'include_values', 'include_metadata'] - if 'filter' in kwargs: - kwargs['filter'] = dict_to_proto_struct(kwargs['filter']) - request = QueryRequest(queries=list(map(_query_transform, queries)), - vector=vector, - id=id, - **{k: v for k, v in kwargs.items() if k in _QUERY_ARGS}) + queries = list(map(_query_transform, queries)) if queries is not None else None + + if filter is not None: + filter = dict_to_proto_struct(filter) + + args_dict = self._parse_args_to_dict([('vector', vector), + ('id', id), + ('queries', queries), + ('namespace', namespace), + ('top_k', top_k), + ('filter', filter), + ('include_values', include_values), + ('include_metadata', include_metadata)]) + + request = QueryRequest(**args_dict) + + timeout = kwargs.pop('timeout', None) response = self._wrap_grpc_call(self.stub.Query, request, timeout=timeout) json_response = json_format.MessageToDict(response) - return parse_query_response(json_response, vector or id) - - def update(self, id, async_req=False, **kwargs): - _UPDATE_ARGS = ['values', 'set_metadata', 'namespace'] - if 'set_metadata' in kwargs: - kwargs['set_metadata'] = dict_to_proto_struct(kwargs['set_metadata']) - request = UpdateRequest(id=id, **{k: v for k, v in kwargs.items() if k in _UPDATE_ARGS}) + return parse_query_response(json_response, vector is not None or id) + + def update(self, + id: str, + async_req: bool = False, + values: Optional[List[float]] = None, + set_metadata: Optional[Dict[str, Any]] = None, + namespace: Optional[str] = None, + **kwargs) -> Union[UpdateResponse, PineconeGrpcFuture]: + if set_metadata is not None: + set_metadata = dict_to_proto_struct(set_metadata) + + args_dict = self._parse_args_to_dict([('values', values), + ('set_metadata', set_metadata), + ('namespace', namespace)]) + + request = UpdateRequest(id=id, **args_dict) timeout = kwargs.pop('timeout', None) if async_req: future = self._wrap_grpc_call(self.stub.Update.future, request, timeout=timeout) @@ -329,13 +372,16 @@ def update(self, id, async_req=False, **kwargs): else: return self._wrap_grpc_call(self.stub.Update, request, timeout=timeout) - def describe_index_stats(self, **kwargs): - _filter = dict_to_proto_struct(kwargs.pop('filter', None)) - filter_param = {} - if _filter: - filter_param['filter'] = _filter + def describe_index_stats(self, + filter: Dict[str, Any] = {}, + **kwargs) -> DescribeIndexStatsResponse: + filter = dict_to_proto_struct(filter) timeout = kwargs.pop('timeout', None) - request = DescribeIndexStatsRequest(**filter_param) + request = DescribeIndexStatsRequest(filter=filter) response = self._wrap_grpc_call(self.stub.DescribeIndexStats, request, timeout=timeout) json_response = json_format.MessageToDict(response) return parse_stats_response(json_response) + + @staticmethod + def _parse_args_to_dict(args: List[Tuple[str, Any]]) -> Dict[str, Any]: + return {arg_name: val for arg_name, val in args if val is not None} diff --git a/pinecone/index.py b/pinecone/index.py index 42477e206..f08131ea2 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -107,13 +107,13 @@ def delete(self, @validate_and_convert_errors def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> FetchResponse: args_dict = self._parse_args_to_dict([('namespace', namespace)]) - return self._vector_api.fetch(ids, **args_dict, **kwargs) + return self._vector_api.fetch(ids=ids, **args_dict, **kwargs) @validate_and_convert_errors def query(self, vector: Optional[List[float]] = None, id: Optional[str] = None, - queries: Optional[List[QueryVector]] = None, + queries: Optional[Union[List[QueryVector], List[Tuple]]] = None, top_k: Optional[int] = None, namespace: Optional[str] = None, filter: Optional[Dict[str, Any]] = None, @@ -168,7 +168,7 @@ def update(self, values: Optional[List[float]] = None, set_metadata: Optional[Dict[str, Any]] = None, namespace: Optional[str] = None, - **kwargs): + **kwargs) -> Dict[str, Any]: _check_type = kwargs.pop('_check_type', False) args_dict = self._parse_args_to_dict([('values', values), ('set_metadata', set_metadata), From 6a16e1fb5e4267e0e9b28c4c4e51c54ac6f3bcdb Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 22 Dec 2022 15:58:41 +0200 Subject: [PATCH 05/25] add docstring to index --- pinecone/index.py | 184 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 182 insertions(+), 2 deletions(-) diff --git a/pinecone/index.py b/pinecone/index.py index f08131ea2..b2dcd22a9 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -39,6 +39,11 @@ def parse_query_response(response: QueryResponse, unary_query: bool): class Index(ApiClient): + """ + A class for interacting with a Pinecone index via REST API. + For improved performance, use the Pinecone GRPC index client (https://docs.pinecone.io/docs/performance-tuning) + """ + def __init__(self, index_name: str, pool_threads=1): openapi_client_config = copy.deepcopy(Config.OPENAPI_CONFIG) openapi_client_config.api_key = openapi_client_config.api_key or {} @@ -61,6 +66,41 @@ def upsert(self, vectors: Union[List[Vector], List[Tuple]], namespace: Optional[str] = None, **kwargs) -> UpsertResponse: + """ + The upsert operation writes vectors into a namespace. + If a new value is upserted for an existing vector id, it will overwrite the previous value. + + API reference: https://docs.pinecone.io/reference/upsert + + Args: + vectors (Union[List[Vector], List[Tuple]]): A list of vectors to upsert. + + A vector can be represented by a 1) Vector object or a 2) tuple. + 1) if a tuple is used, it must be of the form (id, vector, metadata) or (id, vector). + where id is a string, vector is a list of floats, and metadata is a dict. + Examples: ('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0]) + + 2) if a Vector object is used, a Vector object must be of the form Vector(id, vector, metadata), + where metadata is an optional argument. + Examples: Vector(id='id1', vector=[1.0, 2.0, 3.0], metadata={'key': 'value'}), + Vector(id='id2', vector=[1.0, 2.0, 3.0]) + + Note: the dimension of each vector must match the dimension of the index. + + namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] + + Keyword Args: + Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpsertRequest for more details. + + Returns: UpsertResponse object which basically contains the number of vectors upserted. + + Call Examples: + index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0])]) + index.upsert([Vector(id='id1', vector=[1.0, 2.0, 3.0], metadata={'key': 'value'}), + Vector(id='id2', vector=[1.0, 2.0, 3.0])]) + + """ + _check_type = kwargs.pop('_check_type', False) args_dict = self._parse_args_to_dict([('namespace', namespace)]) @@ -89,6 +129,41 @@ def delete(self, namespace: Optional[str] = None, filter: Optional[Dict[str, Any]] = None, **kwargs) -> Dict[str, Any]: + """ + The Delete operation deletes vectors from the index, from a single namespace. + No error raised if the vector id does not exist. + Note: for any delete call, if namespace is not specified, the default namespace is used. + + Delete can occur in the following mutual exclusive ways: + 1. Delete by ids from a single namespace + 2. Delete all vectors from a single namespace by setting delete_all to True + 3. Delete all vectors from a single namespace by specifying a metadata filter + (note that for this option delete all must be set to False) + + API reference: https://docs.pinecone.io/reference/delete_post + + Args: + ids (List[str]): Vector ids to delete [optional] + delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] + Default is False. + namespace (str): The namespace to delete vectors from [optional] + If not specified, the default namespace is used. + filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + If specified, the metadata filter here will be used to select the vectors to delete. + This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. + See https://www.pinecone.io/docs/metadata-filtering/.. [optional] + + Keyword Args: + Supports OpenAPI client keyword arguments. See pinecone.core.client.models.DeleteRequest for more details. + + + Returns: An empty dictionary if the delete operation was successful. + + Call Examples: + index.delete(ids=['id1', 'id2'], namespace='my_namespace') + index.delete(delete_all=True, namespace='my_namespace') + index.delete(filter={'key': 'value'}, namespace='my_namespace') + """ _check_type = kwargs.pop('_check_type', False) args_dict = self._parse_args_to_dict([('ids', ids), ('delete_all', delete_all), @@ -105,7 +180,30 @@ def delete(self, ) @validate_and_convert_errors - def fetch(self, ids: List[str], namespace: Optional[str] = None, **kwargs) -> FetchResponse: + def fetch(self, + ids: List[str], + namespace: Optional[str] = None, + **kwargs) -> FetchResponse: + """ + The fetch operation looks up and returns vectors, by ID, from a single namespace. + The returned vectors include the vector data and/or metadata. + + API reference: https://docs.pinecone.io/reference/fetch + + Args: + ids (List[str]): The vector IDs to fetch. + namespace (str): The namespace to fetch vectors from. + If not specified, the default namespace is used. [optional] + Keyword Args: + Supports OpenAPI client keyword arguments. See pinecone.core.client.models.FetchResponse for more details. + + + Returns: FetchResponse object which contains the list of Vector objects, and namespace name. + + Call Examples: + index.fetch(ids=['id1', 'id2'], namespace='my_namespace') + index.fetch(ids=['id1', 'id2']) + """ args_dict = self._parse_args_to_dict([('namespace', namespace)]) return self._vector_api.fetch(ids=ids, **args_dict, **kwargs) @@ -121,6 +219,45 @@ def query(self, include_metadata: Optional[bool] = None, **kwargs) -> QueryResponse: + """ + The Query operation searches a namespace, using a query vector. + It retrieves the ids of the most similar items in a namespace, along with their similarity scores. + + API reference: https://docs.pinecone.io/reference/query + + Args: + vector (List[float]): The query vector. This should be the same length as the dimension of the index + being queried. Each `query()` request can contain only one of the parameters + `queries`, `id` or `vector`.. [optional] + id (str): The unique ID of the vector to be used as a query vector. + Each `query()` request can contain only one of the parameters + `queries`, `vector`, or `id`.. [optional] + queries ([QueryVector]): DEPRECATED. The query vectors. + Each `query()` request can contain only one of the parameters + `queries`, `vector`, or `id`.. [optional] + top_k (int): The number of results to return for each query. Must be an integer greater than 1. + namespace (str): The namespace to fetch vectors from. + If not specified, the default namespace is used. [optional] + filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + The filter to apply. You can use vector metadata to limit your search. + See https://www.pinecone.io/docs/metadata-filtering/.. [optional] + include_values (bool): Indicates whether vector values are included in the response. + If omitted the server will use the default value of False [optional] + include_metadata (bool): Indicates whether metadata is included in the response as well as the ids. + If omitted the server will use the default value of False [optional] + + Keyword Args: + Supports OpenAPI client keyword arguments. See pinecone.core.client.models.QueryRequest for more details. + + Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, + and namespace name. + + Call Examples: + index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') + index.query(id='id1', top_k=10, namespace='my_namespace') + index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) + index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) + """ def _query_transform(item): if isinstance(item, QueryVector): return item @@ -169,6 +306,30 @@ def update(self, set_metadata: Optional[Dict[str, Any]] = None, namespace: Optional[str] = None, **kwargs) -> Dict[str, Any]: + """ + The Update operation updates vector in a namespace. + If a value is included, it will overwrite the previous value. + If a set_metadata is included, + the values of the fields specified in it will be added or overwrite the previous value. + + API reference: https://docs.pinecone.io/reference/update + + Args: + id (str): Vector's unique id. + values (List[float]): vector values to set. [optional] + set_metadata (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + metadata to set for vector. [optional] + namespace (str): Namespace name where to update the vector.. [optional] + + Keyword Args: + Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpdateRequest for more details. + + Returns: An empty dictionary if the update was successful. + + Call Examples: + index.update(id='id1', values=[1, 2, 3], namespace='my_namespace') + index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace') + """ _check_type = kwargs.pop('_check_type', False) args_dict = self._parse_args_to_dict([('values', values), ('set_metadata', set_metadata), @@ -182,7 +343,26 @@ def update(self, **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS}) @validate_and_convert_errors - def describe_index_stats(self, filter: Dict[str, Any] = {}, **kwargs) -> DescribeIndexStatsResponse: + def describe_index_stats(self, + filter: Dict[str, Any] = {}, + **kwargs) -> DescribeIndexStatsResponse: + """ + The DescribeIndexStats operation returns statistics about the index's contents. + For example: The vector count per namespace and the number of dimensions. + + API reference: https://docs.pinecone.io/reference/describe_index_stats_post + + Args: + filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. + See https://www.pinecone.io/docs/metadata-filtering/.. [optional] + + Returns: DescribeIndexStatsResponse object which contains stats about the index. + + Call Examples: + index.describe_index_stats() + index.describe_index_stats(filter={'key': 'value'}) + """ _check_type = kwargs.pop('_check_type', False) return self._vector_api.describe_index_stats( DescribeIndexStatsRequest( From 971250261fd40386fb1f9c2f38251efd8fef0a3d Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 22 Dec 2022 16:48:07 +0200 Subject: [PATCH 06/25] add docstring to grpc index --- pinecone/core/grpc/index_grpc.py | 151 +++++++++++++++++++++++++++++++ pinecone/index.py | 14 +-- 2 files changed, 158 insertions(+), 7 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index 217d563cb..43eb4b354 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -245,6 +245,8 @@ def traceback(self, timeout=None): class GRPCIndex(GRPCIndexBase): + """A client for interacting with a Pinecone index via GRPC API.""" + @property def stub_class(self): return VectorServiceStub @@ -254,6 +256,37 @@ def upsert(self, async_req: bool = False, namespace: Optional[str] = None, **kwargs) -> Union[UpsertResponse, PineconeGrpcFuture]: + """ + The upsert operation writes vectors into a namespace. + If a new value is upserted for an existing vector id, it will overwrite the previous value. + + Args: + vectors (Union[List[Vector], List[Tuple]]): A list of vectors to upsert. + + A vector can be represented by a 1) GRPCVector object or a 2) tuple. + 1) if a tuple is used, it must be of the form (id, values, metadata) or (id, values). + where id is a string, vector is a list of floats, and metadata is a dict. + Examples: ('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0]) + + 2) if a GRPCVector object is used, a GRPCVector object must be of the form + GRPCVector(id, values, metadata), where metadata is an optional argument. + Examples: GRPCVector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), + GRPCVector(id='id2', values=[1.0, 2.0, 3.0]) + + Note: the dimension of each vector must match the dimension of the index. + async_req (bool): If True, the upsert operation will be performed asynchronously. + Defaults to False. [optional] + namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] + + Returns: UpsertResponse object which basically contains the number of vectors upserted + or a PineconeGrpcFuture object if async_req is True. + + Call Examples: + index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0])], namespace='ns1') + index.upsert([GRPCVector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), + GRPCVector(id='id2', values=[1.0, 2.0, 3.0])], async_req=True) + """ + args_dict = self._parse_args_to_dict([('namespace', namespace)]) def _vector_transform(item): @@ -279,6 +312,38 @@ def delete(self, filter: Optional[Dict[str, Any]] = None, async_req: bool = False, **kwargs) -> Union[DeleteResponse, PineconeGrpcFuture]: + """ + The Delete operation deletes vectors from the index, from a single namespace. + No error raised if the vector id does not exist. + Note: for any delete call, if namespace is not specified, the default namespace is used. + + Delete can occur in the following mutual exclusive ways: + 1. Delete by ids from a single namespace + 2. Delete all vectors from a single namespace by setting delete_all to True + 3. Delete all vectors from a single namespace by specifying a metadata filter + (note that for this option delete all must be set to False) + + Args: + ids (List[str]): Vector ids to delete [optional] + delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] + Default is False. + namespace (str): The namespace to delete vectors from [optional] + If not specified, the default namespace is used. + filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + If specified, the metadata filter here will be used to select the vectors to delete. + This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. + See https://www.pinecone.io/docs/metadata-filtering/.. [optional] + async_req (bool): If True, the delete operation will be performed asynchronously. + Defaults to False. [optional] + + Returns: DeleteResponse (contains no data) or a PineconeGrpcFuture object if async_req is True. + + Call Examples: + index.delete(ids=['id1', 'id2'], namespace='my_namespace') + index.delete(delete_all=True, namespace='my_namespace') + index.delete(filter={'key': 'value'}, namespace='my_namespace', async_req=True) + """ + if filter is not None: filter = dict_to_proto_struct(filter) @@ -299,6 +364,21 @@ def fetch(self, ids: Optional[List[str]], namespace: Optional[str] = None, **kwargs) -> FetchResponse: + """ + The fetch operation looks up and returns vectors, by ID, from a single namespace. + The returned vectors include the vector data and/or metadata. + + Args: + ids (List[str]): The vector IDs to fetch. + namespace (str): The namespace to fetch vectors from. + If not specified, the default namespace is used. [optional] + + Returns: FetchResponse object which contains the list of Vector objects, and namespace name. + + Call Examples: + index.fetch(ids=['id1', 'id2'], namespace='my_namespace') + index.fetch(ids=['id1', 'id2']) + """ timeout = kwargs.pop('timeout', None) args_dict = self._parse_args_to_dict([('namespace', namespace)]) @@ -318,6 +398,40 @@ def query(self, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, **kwargs) -> QueryResponse: + """ + The Query operation searches a namespace, using a query vector. + It retrieves the ids of the most similar items in a namespace, along with their similarity scores. + + Args: + vector (List[float]): The query vector. This should be the same length as the dimension of the index + being queried. Each `query()` request can contain only one of the parameters + `queries`, `id` or `vector`.. [optional] + id (str): The unique ID of the vector to be used as a query vector. + Each `query()` request can contain only one of the parameters + `queries`, `vector`, or `id`.. [optional] + queries ([GRPCQueryVector]): DEPRECATED. The query vectors. + Each `query()` request can contain only one of the parameters + `queries`, `vector`, or `id`.. [optional] + top_k (int): The number of results to return for each query. Must be an integer greater than 1. + namespace (str): The namespace to fetch vectors from. + If not specified, the default namespace is used. [optional] + filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + The filter to apply. You can use vector metadata to limit your search. + See https://www.pinecone.io/docs/metadata-filtering/.. [optional] + include_values (bool): Indicates whether vector values are included in the response. + If omitted the server will use the default value of False [optional] + include_metadata (bool): Indicates whether metadata is included in the response as well as the ids. + If omitted the server will use the default value of False [optional] + + Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, + and namespace name. + + Call Examples: + index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') + index.query(id='id1', top_k=10, namespace='my_namespace') + index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) + index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) + """ def _query_transform(item): if isinstance(item, GRPCQueryVector): return item @@ -357,6 +471,27 @@ def update(self, set_metadata: Optional[Dict[str, Any]] = None, namespace: Optional[str] = None, **kwargs) -> Union[UpdateResponse, PineconeGrpcFuture]: + """ + The Update operation updates vector in a namespace. + If a value is included, it will overwrite the previous value. + If a set_metadata is included, + the values of the fields specified in it will be added or overwrite the previous value. + + Args: + id (str): Vector's unique id. + async_req (bool): If True, the update operation will be performed asynchronously. + Defaults to False. [optional] + values (List[float]): vector values to set. [optional] + set_metadata (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + metadata to set for vector. [optional] + namespace (str): Namespace name where to update the vector.. [optional] + + Returns: UpdateResponse (contains no data) or a PineconeGrpcFuture object if async_req is True. + + Call Examples: + index.update(id='id1', values=[1, 2, 3], namespace='my_namespace') + index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace', async_req=True) + """ if set_metadata is not None: set_metadata = dict_to_proto_struct(set_metadata) @@ -375,6 +510,22 @@ def update(self, def describe_index_stats(self, filter: Dict[str, Any] = {}, **kwargs) -> DescribeIndexStatsResponse: + """ + The DescribeIndexStats operation returns statistics about the index's contents. + For example: The vector count per namespace and the number of dimensions. + + Args: + filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. + See https://www.pinecone.io/docs/metadata-filtering/.. [optional] + + Returns: DescribeIndexStatsResponse object which contains stats about the index. + + Call Examples: + index.describe_index_stats() + index.describe_index_stats(filter={'key': 'value'}) + """ + filter = dict_to_proto_struct(filter) timeout = kwargs.pop('timeout', None) request = DescribeIndexStatsRequest(filter=filter) diff --git a/pinecone/index.py b/pinecone/index.py index b2dcd22a9..27d52ed19 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -40,7 +40,7 @@ def parse_query_response(response: QueryResponse, unary_query: bool): class Index(ApiClient): """ - A class for interacting with a Pinecone index via REST API. + A client for interacting with a Pinecone index via REST API. For improved performance, use the Pinecone GRPC index client (https://docs.pinecone.io/docs/performance-tuning) """ @@ -76,14 +76,14 @@ def upsert(self, vectors (Union[List[Vector], List[Tuple]]): A list of vectors to upsert. A vector can be represented by a 1) Vector object or a 2) tuple. - 1) if a tuple is used, it must be of the form (id, vector, metadata) or (id, vector). + 1) if a tuple is used, it must be of the form (id, values, metadata) or (id, values). where id is a string, vector is a list of floats, and metadata is a dict. Examples: ('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0]) - 2) if a Vector object is used, a Vector object must be of the form Vector(id, vector, metadata), + 2) if a Vector object is used, a Vector object must be of the form Vector(id, values, metadata), where metadata is an optional argument. - Examples: Vector(id='id1', vector=[1.0, 2.0, 3.0], metadata={'key': 'value'}), - Vector(id='id2', vector=[1.0, 2.0, 3.0]) + Examples: Vector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), + Vector(id='id2', values=[1.0, 2.0, 3.0]) Note: the dimension of each vector must match the dimension of the index. @@ -96,8 +96,8 @@ def upsert(self, Call Examples: index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0])]) - index.upsert([Vector(id='id1', vector=[1.0, 2.0, 3.0], metadata={'key': 'value'}), - Vector(id='id2', vector=[1.0, 2.0, 3.0])]) + index.upsert([Vector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), + Vector(id='id2', values=[1.0, 2.0, 3.0])]) """ From f033db509dac7b8d43ea65c17852fe8221aef7d5 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Sun, 25 Dec 2022 14:33:09 +0200 Subject: [PATCH 07/25] move unit tests to a class --- tests/unit/test_index.py | 114 +++++++++++++++++++-------------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 25991a89c..5e263fd92 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -1,64 +1,64 @@ -vector_dim = 8 -vals1 = [0.1] * vector_dim -vals2 = [0.2] * vector_dim -md1 = {'genre': 'action', 'year': 2021} -md2 = {'genre': 'documentary', 'year': 2020} -filter1 = {'genre': {'$in': ['action']}} -filter2 = {'year': {'$eq': 2020}} +class TestRestIndex: -def test_upsert_request_tuples_id_data(mocker): - import pinecone - pinecone.init(api_key='example-key') - index = pinecone.Index('example-name') - mocker.patch.object(index._vector_api, 'upsert', autospec=True) - index.upsert([('vec1', vals1), ('vec2', vals2)], namespace='ns') - index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=vals1, metadata={}), - pinecone.Vector(id='vec2', values=vals2, metadata={}) - ], namespace='ns') - ) + def setup_method(self): + self.vector_dim = 8 + self.vals1 = [0.1] * self.vector_dim + self.vals2 = [0.2] * self.vector_dim + self.md1 = {'genre': 'action', 'year': 2021} + self.md2 = {'genre': 'documentary', 'year': 2020} + self.filter1 = {'genre': {'$in': ['action']}} + self.filter2 = {'year': {'$eq': 2020}} + def test_upsert_request_tuples_id_data(self, mocker): + import pinecone + pinecone.init(api_key='example-key') + index = pinecone.Index('example-name') + mocker.patch.object(index._vector_api, 'upsert', autospec=True) + index.upsert([('vec1', self.vals1), ('vec2', self.vals2)], namespace='ns') + index._vector_api.upsert.assert_called_once_with( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata={}), + pinecone.Vector(id='vec2', values=self.vals2, metadata={}) + ], namespace='ns') + ) -def test_upsert_request_tuples_id_data_metadata(mocker): - import pinecone - pinecone.init(api_key='example-key') - index = pinecone.Index('example-name') - mocker.patch.object(index._vector_api, 'upsert', autospec=True) - index.upsert([('vec1', vals1, md1), - ('vec2', vals2, md2)]) - index._vector_api.upsert.assert_called_once_with( - pinecone.UpsertRequest(vectors=[ - pinecone.Vector(id='vec1', values=vals1, metadata=md1), - pinecone.Vector(id='vec2', values=vals2, metadata=md2) - ]) - ) - - -def test_query_request_tuples_query_only(mocker): - import pinecone - pinecone.init(api_key='example-key') - index = pinecone.Index('example-name') - mocker.patch.object(index._vector_api, 'query', autospec=True) - index.query(top_k=10, vector=vals1) - index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, vector=vals1) - ) + def test_upsert_request_tuples_id_data_metadata(self, mocker): + import pinecone + pinecone.init(api_key='example-key') + index = pinecone.Index('example-name') + mocker.patch.object(index._vector_api, 'upsert', autospec=True) + index.upsert([('vec1', self.vals1, self.md1), + ('vec2', self.vals2, self.md2)]) + index._vector_api.upsert.assert_called_once_with( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2) + ]) + ) + def test_query_request_tuples_query_only(self, mocker): + import pinecone + pinecone.init(api_key='example-key') + index = pinecone.Index('example-name') + mocker.patch.object(index._vector_api, 'query', autospec=True) + index.query(top_k=10, vector=self.vals1) + index._vector_api.query.assert_called_once_with( + pinecone.QueryRequest(top_k=10, vector=self.vals1) + ) -def test_query_request_tuples_query_filter(mocker): - import pinecone - pinecone.init(api_key='example-key') - index = pinecone.Index('example-name') - mocker.patch.object(index._vector_api, 'query', autospec=True) - index.query(top_k=10, queries=[ - (vals1, filter1), - (vals2, filter2) - ]) - index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, queries=[ - pinecone.QueryVector(values=vals1, filter=filter1), - pinecone.QueryVector(values=vals2, filter=filter2) + def test_query_request_tuples_query_filter(self, mocker): + import pinecone + pinecone.init(api_key='example-key') + index = pinecone.Index('example-name') + mocker.patch.object(index._vector_api, 'query', autospec=True) + index.query(top_k=10, queries=[ + (self.vals1, self.filter1), + (self.vals2, self.filter2) ]) - ) + index._vector_api.query.assert_called_once_with( + pinecone.QueryRequest(top_k=10, queries=[ + pinecone.QueryVector(values=self.vals1, filter=self.filter1), + pinecone.QueryVector(values=self.vals2, filter=self.filter2) + ]) + ) From dfd52ae83e45a1c737f3858f6ad391588993c9d5 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Sun, 25 Dec 2022 15:13:15 +0200 Subject: [PATCH 08/25] add unit tests to all rest methods --- pinecone/index.py | 5 +- tests/unit/test_index.py | 154 ++++++++++++++++++++++++++++++++------- 2 files changed, 131 insertions(+), 28 deletions(-) diff --git a/pinecone/index.py b/pinecone/index.py index 27d52ed19..26fadafe8 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -263,7 +263,10 @@ def _query_transform(item): return item if isinstance(item, tuple): values, filter = fix_tuple_length(item, 2) - return QueryVector(values=values, filter=filter, _check_type=_check_type) + if filter is None: + return QueryVector(values=values, _check_type=_check_type) + else: + return QueryVector(values=values, filter=filter, _check_type=_check_type) if isinstance(item, Iterable): return QueryVector(values=item, _check_type=_check_type) raise ValueError(f"Invalid query vector value passed: cannot interpret type {type(item)}") diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 5e263fd92..9a7d8b638 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -1,3 +1,6 @@ +import pinecone +from pinecone import DescribeIndexStatsRequest + class TestRestIndex: @@ -10,55 +13,152 @@ def setup_method(self): self.filter1 = {'genre': {'$in': ['action']}} self.filter2 = {'year': {'$eq': 2020}} - def test_upsert_request_tuples_id_data(self, mocker): - import pinecone pinecone.init(api_key='example-key') - index = pinecone.Index('example-name') - mocker.patch.object(index._vector_api, 'upsert', autospec=True) - index.upsert([('vec1', self.vals1), ('vec2', self.vals2)], namespace='ns') - index._vector_api.upsert.assert_called_once_with( + self.index = pinecone.Index('example-name') + + # region: upsert tests + + def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker): + mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) + self.index.upsert([('vec1', self.vals1), ('vec2', self.vals2)], namespace='ns') + self.index._vector_api.upsert.assert_called_once_with( pinecone.UpsertRequest(vectors=[ pinecone.Vector(id='vec1', values=self.vals1, metadata={}), pinecone.Vector(id='vec2', values=self.vals2, metadata={}) ], namespace='ns') ) - def test_upsert_request_tuples_id_data_metadata(self, mocker): - import pinecone - pinecone.init(api_key='example-key') - index = pinecone.Index('example-name') - mocker.patch.object(index._vector_api, 'upsert', autospec=True) - index.upsert([('vec1', self.vals1, self.md1), + def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD(self, mocker): + mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) + self.index.upsert([('vec1', self.vals1, self.md1), ('vec2', self.vals2, self.md2)]) - index._vector_api.upsert.assert_called_once_with( + self.index._vector_api.upsert.assert_called_once_with( pinecone.UpsertRequest(vectors=[ pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2) ]) ) - def test_query_request_tuples_query_only(self, mocker): - import pinecone - pinecone.init(api_key='example-key') - index = pinecone.Index('example-name') - mocker.patch.object(index._vector_api, 'query', autospec=True) - index.query(top_k=10, vector=self.vals1) - index._vector_api.query.assert_called_once_with( + # endregion + + # region: query tests + + def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): + mocker.patch.object(self.index._vector_api, 'query', autospec=True) + self.index.query(top_k=10, vector=self.vals1) + self.index._vector_api.query.assert_called_once_with( pinecone.QueryRequest(top_k=10, vector=self.vals1) ) - def test_query_request_tuples_query_filter(self, mocker): - import pinecone - pinecone.init(api_key='example-key') - index = pinecone.Index('example-name') - mocker.patch.object(index._vector_api, 'query', autospec=True) - index.query(top_k=10, queries=[ + def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker): + mocker.patch.object(self.index._vector_api, 'query', autospec=True) + self.index.query(top_k=10, vector=self.vals1, filter=self.filter1, namespace='ns') + self.index._vector_api.query.assert_called_once_with( + pinecone.QueryRequest(top_k=10, vector=self.vals1, filter=self.filter1, namespace='ns') + ) + + def test_query_byTuplesNoFilter_queryVectorsNoFilter(self, mocker): + mocker.patch.object(self.index._vector_api, 'query', autospec=True) + self.index.query(top_k=10, queries=[ + (self.vals1,), + (self.vals2,) + ]) + self.index._vector_api.query.assert_called_once_with( + pinecone.QueryRequest(top_k=10, queries=[ + pinecone.QueryVector(values=self.vals1), + pinecone.QueryVector(values=self.vals2) + ]) + ) + + def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker): + mocker.patch.object(self.index._vector_api, 'query', autospec=True) + self.index.query(top_k=10, queries=[ (self.vals1, self.filter1), (self.vals2, self.filter2) ]) - index._vector_api.query.assert_called_once_with( + self.index._vector_api.query.assert_called_once_with( pinecone.QueryRequest(top_k=10, queries=[ pinecone.QueryVector(values=self.vals1, filter=self.filter1), pinecone.QueryVector(values=self.vals2, filter=self.filter2) ]) ) + + def test_query_byVecId_queryByVecId(self, mocker): + mocker.patch.object(self.index._vector_api, 'query', autospec=True) + self.index.query(top_k=10, id='vec1', include_metadata=True, include_vector=False) + self.index._vector_api.query.assert_called_once_with( + pinecone.QueryRequest(top_k=10, id='vec1', include_metadata=True, include_vector=False) + ) + + # endregion + + # region: delete tests + + def test_delete_byIds_deleteByIds(self, mocker): + mocker.patch.object(self.index._vector_api, 'delete', autospec=True) + self.index.delete(ids=['vec1', 'vec2']) + self.index._vector_api.delete.assert_called_once_with( + pinecone.DeleteRequest(ids=['vec1', 'vec2']) + ) + + def test_delete_deleteAllByFilter_deleteAllByFilter(self, mocker): + mocker.patch.object(self.index._vector_api, 'delete', autospec=True) + self.index.delete(delete_all=True, filter=self.filter1, namespace='ns') + self.index._vector_api.delete.assert_called_once_with( + pinecone.DeleteRequest(delete_all=True, filter=self.filter1, namespace='ns') + ) + + def test_delete_deleteAllNoFilter_deleteNoFilter(self, mocker): + mocker.patch.object(self.index._vector_api, 'delete', autospec=True) + self.index.delete(delete_all=True) + self.index._vector_api.delete.assert_called_once_with( + pinecone.DeleteRequest(delete_all=True) + ) + + # endregion + + # region: fetch tests + + def test_fetch_byIds_fetchByIds(self, mocker): + mocker.patch.object(self.index._vector_api, 'fetch', autospec=True) + self.index.fetch(ids=['vec1', 'vec2']) + self.index._vector_api.fetch.assert_called_once_with( + ids=['vec1', 'vec2'] + ) + + def test_fetch_byIdsAndNS_fetchByIdsAndNS(self, mocker): + mocker.patch.object(self.index._vector_api, 'fetch', autospec=True) + self.index.fetch(ids=['vec1', 'vec2'], namespace='ns') + self.index._vector_api.fetch.assert_called_once_with( + ids=['vec1', 'vec2'], namespace='ns' + ) + + # endregion + + # region: update tests + + def test_update_byIdAnValues_updateByIdAndValues(self, mocker): + mocker.patch.object(self.index._vector_api, 'update', autospec=True) + self.index.update(id='vec1', values=self.vals1, namespace='ns') + self.index._vector_api.update.assert_called_once_with( + pinecone.UpdateRequest(id='vec1', values=self.vals1, namespace='ns') + ) + + def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, mocker): + mocker.patch.object(self.index._vector_api, 'update', autospec=True) + self.index.update('vec1', values=self.vals1, metadata=self.md1) + self.index._vector_api.update.assert_called_once_with( + pinecone.UpdateRequest(id='vec1', values=self.vals1, metadata=self.md1) + ) + + # endregion + + # region: describe index tests + + def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): + mocker.patch.object(self.index._vector_api, 'describe_index_stats', autospec=True) + self.index.describe_index_stats(filter=self.filter1) + self.index._vector_api.describe_index_stats.assert_called_once_with( + DescribeIndexStatsRequest(filter=self.filter1)) + + # endregion From 8e28b71ab14efdc8af2cb4af7d5ce82b5841f8ad Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Sun, 25 Dec 2022 16:30:28 +0200 Subject: [PATCH 09/25] add unit test for grpc index --- pinecone/core/grpc/index_grpc.py | 7 +- tests/unit/test_grpc_index.py | 229 +++++++++++++++++++++++++++++++ tests/unit/test_index.py | 19 ++- 3 files changed, 249 insertions(+), 6 deletions(-) create mode 100644 tests/unit/test_grpc_index.py diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index 43eb4b354..9b05867bd 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -297,8 +297,9 @@ def _vector_transform(item): return GRPCVector(id=id, values=values, metadata=dict_to_proto_struct(metadata) or {}) raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") - request = UpsertRequest(vectors=list(map(_vector_transform, vectors)), **args_dict, **kwargs) timeout = kwargs.pop('timeout', None) + + request = UpsertRequest(vectors=list(map(_vector_transform, vectors)), **args_dict, **kwargs) if async_req: future = self._wrap_grpc_call(self.stub.Upsert.future, request, timeout=timeout) return PineconeGrpcFuture(future) @@ -351,9 +352,9 @@ def delete(self, ('delete_all', delete_all), ('namespace', namespace), ('filter', filter)]) + timeout = kwargs.pop('timeout', None) request = DeleteRequest(**args_dict, **kwargs) - timeout = kwargs.pop('timeout', None) if async_req: future = self._wrap_grpc_call(self.stub.Delete.future, request, timeout=timeout) return PineconeGrpcFuture(future) @@ -494,13 +495,13 @@ def update(self, """ if set_metadata is not None: set_metadata = dict_to_proto_struct(set_metadata) + timeout = kwargs.pop('timeout', None) args_dict = self._parse_args_to_dict([('values', values), ('set_metadata', set_metadata), ('namespace', namespace)]) request = UpdateRequest(id=id, **args_dict) - timeout = kwargs.pop('timeout', None) if async_req: future = self._wrap_grpc_call(self.stub.Update.future, request, timeout=timeout) return PineconeGrpcFuture(future) diff --git a/tests/unit/test_grpc_index.py b/tests/unit/test_grpc_index.py new file mode 100644 index 000000000..9a6f3a01c --- /dev/null +++ b/tests/unit/test_grpc_index.py @@ -0,0 +1,229 @@ +import pinecone +from core.utils import dict_to_proto_struct +from pinecone import DescribeIndexStatsRequest +from pinecone.core.grpc.protos.vector_service_pb2 import Vector, DescribeIndexStatsRequest, UpdateRequest, \ + UpsertRequest, FetchRequest, QueryRequest, DeleteRequest, QueryVector + + +class TestRestIndex: + + def setup_method(self): + self.vector_dim = 8 + self.vals1 = [0.1] * self.vector_dim + self.vals2 = [0.2] * self.vector_dim + self.md1 = {'genre': 'action', 'year': 2021} + self.md2 = {'genre': 'documentary', 'year': 2020} + self.filter1 = {'genre': {'$in': ['action']}} + self.filter2 = {'year': {'$eq': 2020}} + + pinecone.init(api_key='example-key') + self.index = pinecone.GRPCIndex('example-name') + + # region: upsert tests + + def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.upsert([('vec1', self.vals1), ('vec2', self.vals2)], namespace='ns') + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata={}), + Vector(id='vec2', values=self.vals2, metadata={})], + namespace='ns'), + timeout=None + ) + + def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.upsert([('vec1', self.vals1, self.md1), ('vec2', self.vals2, self.md2)], namespace='ns') + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + def test_upsert_vectors_upsertInputVectors(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns') + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + # endregion + + # region: query tests + + def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.query(top_k=10, vector=self.vals1) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest(top_k=10, vector=self.vals1), + timeout=None, + ) + + def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.query(top_k=10, vector=self.vals1, filter=self.filter1, namespace='ns', timeout=10) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest(top_k=10, vector=self.vals1, filter=dict_to_proto_struct(self.filter1), namespace='ns'), + timeout=10, + ) + + def test_query_byTuplesNoFilter_queryVectorsNoFilter(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.query(top_k=10, queries=[ + (self.vals1,), + (self.vals2,) + ]) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest(queries=[ + QueryVector(values=self.vals1, filter={}), + QueryVector(values=self.vals2, filter={}) + ], top_k=10), + timeout=None, + ) + + def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.query(top_k=10, queries=[ + (self.vals1, self.filter1), + (self.vals2, self.filter2) + ]) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest(queries=[ + QueryVector(values=self.vals1, filter=dict_to_proto_struct(self.filter1)), + QueryVector(values=self.vals2, filter=dict_to_proto_struct(self.filter2)) + ], top_k=10), + timeout=None, + ) + + def test_query_byVecId_queryByVecId(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.query(top_k=10, id='vec1', include_metadata=True, include_values=False) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Query, + QueryRequest(top_k=10, id='vec1', include_metadata=True, include_values=False), + timeout=None, + ) + + # endregion + + # region: delete tests + + def test_delete_byIds_deleteByIds(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.delete(ids=['vec1', 'vec2']) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Delete, + DeleteRequest(ids=['vec1', 'vec2']), + timeout=None, + ) + + def test_delete_byIdsAsync_deleteByIdsAsync(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.delete(ids=['vec1', 'vec2'], async_req=True) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Delete.future, + DeleteRequest(ids=['vec1', 'vec2']), + timeout=None, + ) + + def test_delete_deleteAllByFilter_deleteAllByFilter(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.delete(delete_all=True, filter=self.filter1, namespace='ns', timeout=30) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Delete, + DeleteRequest(delete_all=True, filter=dict_to_proto_struct(self.filter1), namespace='ns'), + timeout=30, + ) + + def test_delete_deleteAllNoFilter_deleteNoFilter(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.delete(delete_all=True) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Delete, + DeleteRequest(delete_all=True), + timeout=None, + ) + + # endregion + + # region: fetch tests + + def test_fetch_byIds_fetchByIds(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.fetch(['vec1', 'vec2']) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Fetch, + FetchRequest(ids=['vec1', 'vec2']), + timeout=None, + ) + + def test_fetch_byIdsAndNS_fetchByIdsAndNS(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.fetch(['vec1', 'vec2'], namespace='ns', timeout=30) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Fetch, + FetchRequest(ids=['vec1', 'vec2'], namespace='ns'), + timeout=30, + ) + + # endregion + + # region: update tests + + def test_update_byIdAnValues_updateByIdAndValues(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.update(id='vec1', values=self.vals1, namespace='ns', timeout=30) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Update, + UpdateRequest(id='vec1', values=self.vals1, namespace='ns'), + timeout=30, + ) + + def test_update_byIdAnValuesAsync_updateByIdAndValuesAsync(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.update(id='vec1', values=self.vals1, namespace='ns', timeout=30, async_req=True) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Update.future, + UpdateRequest(id='vec1', values=self.vals1, namespace='ns'), + timeout=30, + ) + + def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.update('vec1', values=self.vals1, set_metadata=self.md1) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Update, + UpdateRequest(id='vec1', values=self.vals1, set_metadata=dict_to_proto_struct(self.md1)), + timeout=None, + ) + + # endregion + + # region: describe index tests + + def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.describe_index_stats(filter=self.filter1) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.DescribeIndexStats, + DescribeIndexStatsRequest(filter=dict_to_proto_struct(self.filter1)), + timeout=None, + ) + # endregion diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 9a7d8b638..cdeec7c44 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -31,7 +31,7 @@ def test_upsert_tuplesOfIdVec_UpserWithoutMD(self, mocker): def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD(self, mocker): mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) self.index.upsert([('vec1', self.vals1, self.md1), - ('vec2', self.vals2, self.md2)]) + ('vec2', self.vals2, self.md2)]) self.index._vector_api.upsert.assert_called_once_with( pinecone.UpsertRequest(vectors=[ pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), @@ -39,6 +39,19 @@ def test_upsert_tuplesOfIdVecMD_UpsertVectorsWithMD(self, mocker): ]) ) + def test_upsert_vectors_upsertInputVectors(self, mocker): + mocker.patch.object(self.index._vector_api, 'upsert', autospec=True) + self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2)], + namespace='ns') + self.index._vector_api.upsert.assert_called_once_with( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2) + ], namespace='ns') + ) + # endregion # region: query tests @@ -85,9 +98,9 @@ def test_query_byTuplesWithFilter_queryVectorsWithFilter(self, mocker): def test_query_byVecId_queryByVecId(self, mocker): mocker.patch.object(self.index._vector_api, 'query', autospec=True) - self.index.query(top_k=10, id='vec1', include_metadata=True, include_vector=False) + self.index.query(top_k=10, id='vec1', include_metadata=True, include_values=False) self.index._vector_api.query.assert_called_once_with( - pinecone.QueryRequest(top_k=10, id='vec1', include_metadata=True, include_vector=False) + pinecone.QueryRequest(top_k=10, id='vec1', include_metadata=True, include_values=False) ) # endregion From 60100519df59f2d318755d4d45b269cebc132328 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Sun, 25 Dec 2022 16:37:51 +0200 Subject: [PATCH 10/25] add grpc to test env --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 8e3d6c252..6451958bf 100644 --- a/tox.ini +++ b/tox.ini @@ -15,7 +15,7 @@ deps= old_deps_yes: urllib3==1.21.1 -r {toxinidir}/requirements.txt -r {toxinidir}/test-requirements.txt - pcgrpc_yes: -r {toxinidir}/requirements-grpc.txt + -r {toxinidir}/requirements-grpc.txt commands = pytest --cov=pinecone --timeout=120 tests/unit {posargs} From 10fb42c2983b731700ffe89183994cd4e1844020 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Sun, 25 Dec 2022 16:42:40 +0200 Subject: [PATCH 11/25] temp try --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 6451958bf..c38a0d1dc 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py{36,37,38,39}-pcgrpc_{yes,no}-old_deps_{yes,no},flake8,docs +envlist = flake8,docs skip_missing_interpreters = true [testenv] From 8227b176557b47e313329108ba45ab88d045314c Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Tue, 27 Dec 2022 17:10:34 +0200 Subject: [PATCH 12/25] PR review changes for docstring --- pinecone/core/client/model/query_request.py | 2 +- pinecone/core/grpc/index_grpc.py | 58 ++++++++--------- pinecone/index.py | 70 ++++++++++----------- 3 files changed, 63 insertions(+), 67 deletions(-) diff --git a/pinecone/core/client/model/query_request.py b/pinecone/core/client/model/query_request.py index b90f33951..dee6245f8 100644 --- a/pinecone/core/client/model/query_request.py +++ b/pinecone/core/client/model/query_request.py @@ -308,4 +308,4 @@ def __init__(self, top_k, *args, **kwargs): # noqa: E501 setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + f"class with read only attributes.") diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index 9b05867bd..f5d0d8a43 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -260,6 +260,11 @@ def upsert(self, The upsert operation writes vectors into a namespace. If a new value is upserted for an existing vector id, it will overwrite the previous value. + Examples: + >>> index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0])], namespace='ns1') + >>> index.upsert([GRPCVector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), + >>> GRPCVector(id='id2', values=[1.0, 2.0, 3.0])], async_req=True) + Args: vectors (Union[List[Vector], List[Tuple]]): A list of vectors to upsert. @@ -278,13 +283,8 @@ def upsert(self, Defaults to False. [optional] namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] - Returns: UpsertResponse object which basically contains the number of vectors upserted + Returns: UpsertResponse, contains the number of vectors upserted or a PineconeGrpcFuture object if async_req is True. - - Call Examples: - index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0])], namespace='ns1') - index.upsert([GRPCVector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), - GRPCVector(id='id2', values=[1.0, 2.0, 3.0])], async_req=True) """ args_dict = self._parse_args_to_dict([('namespace', namespace)]) @@ -324,6 +324,11 @@ def delete(self, 3. Delete all vectors from a single namespace by specifying a metadata filter (note that for this option delete all must be set to False) + Examples: + >>> index.delete(ids=['id1', 'id2'], namespace='my_namespace') + >>> index.delete(delete_all=True, namespace='my_namespace') + >>> index.delete(filter={'key': 'value'}, namespace='my_namespace', async_req=True) + Args: ids (List[str]): Vector ids to delete [optional] delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] @@ -338,11 +343,6 @@ def delete(self, Defaults to False. [optional] Returns: DeleteResponse (contains no data) or a PineconeGrpcFuture object if async_req is True. - - Call Examples: - index.delete(ids=['id1', 'id2'], namespace='my_namespace') - index.delete(delete_all=True, namespace='my_namespace') - index.delete(filter={'key': 'value'}, namespace='my_namespace', async_req=True) """ if filter is not None: @@ -369,16 +369,16 @@ def fetch(self, The fetch operation looks up and returns vectors, by ID, from a single namespace. The returned vectors include the vector data and/or metadata. + Examples: + >>> index.fetch(ids=['id1', 'id2'], namespace='my_namespace') + >>> index.fetch(ids=['id1', 'id2']) + Args: ids (List[str]): The vector IDs to fetch. namespace (str): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] Returns: FetchResponse object which contains the list of Vector objects, and namespace name. - - Call Examples: - index.fetch(ids=['id1', 'id2'], namespace='my_namespace') - index.fetch(ids=['id1', 'id2']) """ timeout = kwargs.pop('timeout', None) @@ -403,6 +403,12 @@ def query(self, The Query operation searches a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. + Examples: + >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') + >>> index.query(id='id1', top_k=10, namespace='my_namespace') + >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) + >>> index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) + Args: vector (List[float]): The query vector. This should be the same length as the dimension of the index being queried. Each `query()` request can contain only one of the parameters @@ -426,12 +432,6 @@ def query(self, Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, and namespace name. - - Call Examples: - index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') - index.query(id='id1', top_k=10, namespace='my_namespace') - index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) - index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) """ def _query_transform(item): if isinstance(item, GRPCQueryVector): @@ -478,6 +478,10 @@ def update(self, If a set_metadata is included, the values of the fields specified in it will be added or overwrite the previous value. + Examples: + >>> index.update(id='id1', values=[1, 2, 3], namespace='my_namespace') + >>> index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace', async_req=True) + Args: id (str): Vector's unique id. async_req (bool): If True, the update operation will be performed asynchronously. @@ -488,10 +492,6 @@ def update(self, namespace (str): Namespace name where to update the vector.. [optional] Returns: UpdateResponse (contains no data) or a PineconeGrpcFuture object if async_req is True. - - Call Examples: - index.update(id='id1', values=[1, 2, 3], namespace='my_namespace') - index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace', async_req=True) """ if set_metadata is not None: set_metadata = dict_to_proto_struct(set_metadata) @@ -515,16 +515,16 @@ def describe_index_stats(self, The DescribeIndexStats operation returns statistics about the index's contents. For example: The vector count per namespace and the number of dimensions. + Examples: + >>> index.describe_index_stats() + >>> index.describe_index_stats(filter={'key': 'value'}) + Args: filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] Returns: DescribeIndexStatsResponse object which contains stats about the index. - - Call Examples: - index.describe_index_stats() - index.describe_index_stats(filter={'key': 'value'}) """ filter = dict_to_proto_struct(filter) diff --git a/pinecone/index.py b/pinecone/index.py index 26fadafe8..0e47dac87 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -41,9 +41,8 @@ class Index(ApiClient): """ A client for interacting with a Pinecone index via REST API. - For improved performance, use the Pinecone GRPC index client (https://docs.pinecone.io/docs/performance-tuning) + For improved performance, use the Pinecone GRPC index client. """ - def __init__(self, index_name: str, pool_threads=1): openapi_client_config = copy.deepcopy(Config.OPENAPI_CONFIG) openapi_client_config.api_key = openapi_client_config.api_key or {} @@ -72,6 +71,11 @@ def upsert(self, API reference: https://docs.pinecone.io/reference/upsert + Examples: + >>> index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0])]) + >>> index.upsert([Vector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), + >>> Vector(id='id2', values=[1.0, 2.0, 3.0])]) + Args: vectors (Union[List[Vector], List[Tuple]]): A list of vectors to upsert. @@ -92,15 +96,8 @@ def upsert(self, Keyword Args: Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpsertRequest for more details. - Returns: UpsertResponse object which basically contains the number of vectors upserted. - - Call Examples: - index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0])]) - index.upsert([Vector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), - Vector(id='id2', values=[1.0, 2.0, 3.0])]) - + Returns: UpsertResponse, includes the number of vectors upserted. """ - _check_type = kwargs.pop('_check_type', False) args_dict = self._parse_args_to_dict([('namespace', namespace)]) @@ -142,6 +139,11 @@ def delete(self, API reference: https://docs.pinecone.io/reference/delete_post + Examples: + >>> index.delete(ids=['id1', 'id2'], namespace='my_namespace') + >>> index.delete(delete_all=True, namespace='my_namespace') + >>> index.delete(filter={'key': 'value'}, namespace='my_namespace') + Args: ids (List[str]): Vector ids to delete [optional] delete_all (bool): This indicates that all vectors in the index namespace should be deleted.. [optional] @@ -158,11 +160,6 @@ def delete(self, Returns: An empty dictionary if the delete operation was successful. - - Call Examples: - index.delete(ids=['id1', 'id2'], namespace='my_namespace') - index.delete(delete_all=True, namespace='my_namespace') - index.delete(filter={'key': 'value'}, namespace='my_namespace') """ _check_type = kwargs.pop('_check_type', False) args_dict = self._parse_args_to_dict([('ids', ids), @@ -190,19 +187,19 @@ def fetch(self, API reference: https://docs.pinecone.io/reference/fetch + Examples: + >>> index.fetch(ids=['id1', 'id2'], namespace='my_namespace') + >>> index.fetch(ids=['id1', 'id2']) + Args: ids (List[str]): The vector IDs to fetch. namespace (str): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] Keyword Args: - Supports OpenAPI client keyword arguments. See pinecone.core.client.models.FetchResponse for more details. + Supports OpenAPI client keyword arguments. See pinecone.core.client.models.FetchResponse for more details. Returns: FetchResponse object which contains the list of Vector objects, and namespace name. - - Call Examples: - index.fetch(ids=['id1', 'id2'], namespace='my_namespace') - index.fetch(ids=['id1', 'id2']) """ args_dict = self._parse_args_to_dict([('namespace', namespace)]) return self._vector_api.fetch(ids=ids, **args_dict, **kwargs) @@ -218,13 +215,18 @@ def query(self, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, **kwargs) -> QueryResponse: - """ The Query operation searches a namespace, using a query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. API reference: https://docs.pinecone.io/reference/query + Examples: + >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') + >>> index.query(id='id1', top_k=10, namespace='my_namespace') + >>> index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) + >>> index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) + Args: vector (List[float]): The query vector. This should be the same length as the dimension of the index being queried. Each `query()` request can contain only one of the parameters @@ -247,16 +249,10 @@ def query(self, If omitted the server will use the default value of False [optional] Keyword Args: - Supports OpenAPI client keyword arguments. See pinecone.core.client.models.QueryRequest for more details. + Supports OpenAPI client keyword arguments. See pinecone.core.client.models.QueryRequest for more details. Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects, and namespace name. - - Call Examples: - index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace') - index.query(id='id1', top_k=10, namespace='my_namespace') - index.query(vector=[1, 2, 3], top_k=10, namespace='my_namespace', filter={'key': 'value'}) - index.query(id='id1', top_k=10, namespace='my_namespace', include_metadata=True, include_values=True) """ def _query_transform(item): if isinstance(item, QueryVector): @@ -317,6 +313,10 @@ def update(self, API reference: https://docs.pinecone.io/reference/update + Examples: + >>> index.update(id='id1', values=[1, 2, 3], namespace='my_namespace') + >>> index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace') + Args: id (str): Vector's unique id. values (List[float]): vector values to set. [optional] @@ -325,13 +325,9 @@ def update(self, namespace (str): Namespace name where to update the vector.. [optional] Keyword Args: - Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpdateRequest for more details. + Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpdateRequest for more details. Returns: An empty dictionary if the update was successful. - - Call Examples: - index.update(id='id1', values=[1, 2, 3], namespace='my_namespace') - index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace') """ _check_type = kwargs.pop('_check_type', False) args_dict = self._parse_args_to_dict([('values', values), @@ -355,16 +351,16 @@ def describe_index_stats(self, API reference: https://docs.pinecone.io/reference/describe_index_stats_post + Examples: + >>> index.describe_index_stats() + >>> index.describe_index_stats(filter={'key': 'value'}) + Args: filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] Returns: DescribeIndexStatsResponse object which contains stats about the index. - - Call Examples: - index.describe_index_stats() - index.describe_index_stats(filter={'key': 'value'}) """ _check_type = kwargs.pop('_check_type', False) return self._vector_api.describe_index_stats( From 12382095ef6f2ef6ea5ff98e2bfa086f87379e8a Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Wed, 28 Dec 2022 12:18:07 +0200 Subject: [PATCH 13/25] detalied md types --- pinecone/core/grpc/index_grpc.py | 28 ++++++++++++++++------------ pinecone/index.py | 24 ++++++++++++++---------- tests/unit/test_grpc_index.py | 10 ++++++++++ tests/unit/test_index.py | 6 ++++++ 4 files changed, 46 insertions(+), 22 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index f5d0d8a43..d55491706 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -274,7 +274,8 @@ def upsert(self, Examples: ('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0]) 2) if a GRPCVector object is used, a GRPCVector object must be of the form - GRPCVector(id, values, metadata), where metadata is an optional argument. + GRPCVector(id, values, metadata), where metadata is an optional argument of type + Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]] Examples: GRPCVector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), GRPCVector(id='id2', values=[1.0, 2.0, 3.0]) @@ -310,7 +311,7 @@ def delete(self, ids: Optional[List[str]] = None, delete_all: Optional[bool] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Any]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, async_req: bool = False, **kwargs) -> Union[DeleteResponse, PineconeGrpcFuture]: """ @@ -335,7 +336,7 @@ def delete(self, Default is False. namespace (str): The namespace to delete vectors from [optional] If not specified, the default namespace is used. - filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + filter (Dict[str, Union[str, float, int, bool, List, Dict]]): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] @@ -395,7 +396,7 @@ def query(self, queries: Optional[Union[List[GRPCQueryVector], List[Tuple]]] = None, namespace: Optional[str] = None, top_k: Optional[int] = None, - filter: Optional[Dict[str, Any]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, **kwargs) -> QueryResponse: @@ -422,7 +423,7 @@ def query(self, top_k (int): The number of results to return for each query. Must be an integer greater than 1. namespace (str): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + filter (Dict[str, Union[str, float, int, bool, List, Dict]]): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] include_values (bool): Indicates whether vector values are included in the response. @@ -469,7 +470,8 @@ def update(self, id: str, async_req: bool = False, values: Optional[List[float]] = None, - set_metadata: Optional[Dict[str, Any]] = None, + set_metadata: Optional[Dict[str, + Union[str, float, int, bool, List[int], List[float], List[str]]]] = None, namespace: Optional[str] = None, **kwargs) -> Union[UpdateResponse, PineconeGrpcFuture]: """ @@ -487,7 +489,7 @@ def update(self, async_req (bool): If True, the update operation will be performed asynchronously. Defaults to False. [optional] values (List[float]): vector values to set. [optional] - set_metadata (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + set_metadata (Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]]): metadata to set for vector. [optional] namespace (str): Namespace name where to update the vector.. [optional] @@ -509,7 +511,7 @@ def update(self, return self._wrap_grpc_call(self.stub.Update, request, timeout=timeout) def describe_index_stats(self, - filter: Dict[str, Any] = {}, + filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, **kwargs) -> DescribeIndexStatsResponse: """ The DescribeIndexStats operation returns statistics about the index's contents. @@ -520,16 +522,18 @@ def describe_index_stats(self, >>> index.describe_index_stats(filter={'key': 'value'}) Args: - filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + filter (Dict[str, Union[str, float, int, bool, List, Dict]]): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] Returns: DescribeIndexStatsResponse object which contains stats about the index. """ - - filter = dict_to_proto_struct(filter) + if filter is not None: + filter = dict_to_proto_struct(filter) + args_dict = self._parse_args_to_dict([('filter', filter)]) timeout = kwargs.pop('timeout', None) - request = DescribeIndexStatsRequest(filter=filter) + + request = DescribeIndexStatsRequest(**args_dict) response = self._wrap_grpc_call(self.stub.DescribeIndexStats, request, timeout=timeout) json_response = json_format.MessageToDict(response) return parse_stats_response(json_response) diff --git a/pinecone/index.py b/pinecone/index.py index 0e47dac87..9a263a222 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -85,7 +85,8 @@ def upsert(self, Examples: ('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0]) 2) if a Vector object is used, a Vector object must be of the form Vector(id, values, metadata), - where metadata is an optional argument. + where metadata is an optional argument of the type + Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]. Examples: Vector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), Vector(id='id2', values=[1.0, 2.0, 3.0]) @@ -124,7 +125,7 @@ def delete(self, ids: Optional[List[str]] = None, delete_all: Optional[bool] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Any]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, **kwargs) -> Dict[str, Any]: """ The Delete operation deletes vectors from the index, from a single namespace. @@ -150,7 +151,7 @@ def delete(self, Default is False. namespace (str): The namespace to delete vectors from [optional] If not specified, the default namespace is used. - filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + filter (Dict[str, Union[str, float, int, bool, List, Dict]]): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] @@ -211,7 +212,7 @@ def query(self, queries: Optional[Union[List[QueryVector], List[Tuple]]] = None, top_k: Optional[int] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Any]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, **kwargs) -> QueryResponse: @@ -240,7 +241,7 @@ def query(self, top_k (int): The number of results to return for each query. Must be an integer greater than 1. namespace (str): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + filter (Dict[str, Union[str, float, int, bool, List, Dict]]): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] include_values (bool): Indicates whether vector values are included in the response. @@ -302,7 +303,8 @@ def _query_transform(item): def update(self, id: str, values: Optional[List[float]] = None, - set_metadata: Optional[Dict[str, Any]] = None, + set_metadata: Optional[Dict[str, + Union[str, float, int, bool, List[int], List[float], List[str]]]] = None, namespace: Optional[str] = None, **kwargs) -> Dict[str, Any]: """ @@ -320,7 +322,7 @@ def update(self, Args: id (str): Vector's unique id. values (List[float]): vector values to set. [optional] - set_metadata (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + set_metadata (Dict[str, Union[str, float, int, bool, List[int], List[float], List[str]]]]): metadata to set for vector. [optional] namespace (str): Namespace name where to update the vector.. [optional] @@ -343,7 +345,7 @@ def update(self, @validate_and_convert_errors def describe_index_stats(self, - filter: Dict[str, Any] = {}, + filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, **kwargs) -> DescribeIndexStatsResponse: """ The DescribeIndexStats operation returns statistics about the index's contents. @@ -356,16 +358,18 @@ def describe_index_stats(self, >>> index.describe_index_stats(filter={'key': 'value'}) Args: - filter (Dict[str, Union[bool, date, dict, float, int, list, str, none_type)]]): + filter (Dict[str, Union[str, float, int, bool, List, Dict]]): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] Returns: DescribeIndexStatsResponse object which contains stats about the index. """ _check_type = kwargs.pop('_check_type', False) + args_dict = self._parse_args_to_dict([('filter', filter)]) + return self._vector_api.describe_index_stats( DescribeIndexStatsRequest( - filter=filter, + **args_dict, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS}, _check_type=_check_type ), diff --git a/tests/unit/test_grpc_index.py b/tests/unit/test_grpc_index.py index 9a6f3a01c..280f077dd 100644 --- a/tests/unit/test_grpc_index.py +++ b/tests/unit/test_grpc_index.py @@ -218,6 +218,15 @@ def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, moc # region: describe index tests + def test_describeIndexStats_callWithoutFilter_CalledWithoutFilter(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.describe_index_stats() + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.DescribeIndexStats, + DescribeIndexStatsRequest(), + timeout=None, + ) + def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) self.index.describe_index_stats(filter=self.filter1) @@ -226,4 +235,5 @@ def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): DescribeIndexStatsRequest(filter=dict_to_proto_struct(self.filter1)), timeout=None, ) + # endregion diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index cdeec7c44..24fe975b4 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -168,6 +168,12 @@ def test_update_byIdAnValuesAndMetadata_updateByIdAndValuesAndMetadata(self, moc # region: describe index tests + def test_describeIndexStats_callWithoutFilter_CalledWithoutFilter(self, mocker): + mocker.patch.object(self.index._vector_api, 'describe_index_stats', autospec=True) + self.index.describe_index_stats() + self.index._vector_api.describe_index_stats.assert_called_once_with( + DescribeIndexStatsRequest()) + def test_describeIndexStats_callWithFilter_CalledWithFilter(self, mocker): mocker.patch.object(self.index._vector_api, 'describe_index_stats', autospec=True) self.index.describe_index_stats(filter=self.filter1) From cd326b51a2f9eb11c9b39728f95bb4875879aba7 Mon Sep 17 00:00:00 2001 From: ilai Date: Wed, 28 Dec 2022 15:57:50 +0200 Subject: [PATCH 14/25] [grpc] Use _check_type=False in GRPCIndex.query() We believe the type checking takes a long time, so it's better to skip it. --- pinecone/core/grpc/index_grpc.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index b7704f520..29df38321 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -171,9 +171,10 @@ def parse_fetch_response(response: dict): return FetchResponse(vectors=vd, namespace=namespace, _check_type=False) -def parse_query_response(response: dict, unary_query: bool): +def parse_query_response(response: dict, unary_query: bool, _check_type: bool = False): res = [] + # TODO: consider deleting this deprecated case for match in response.get('results', []): namespace = match.get('namespace', '') m = [] @@ -187,10 +188,10 @@ def parse_query_response(response: dict, unary_query: bool): m = [] for item in response.get('matches', []): sc = ScoredVector(id=item['id'], score=item.get('score', 0.0), values=item.get('values', []), - metadata=item.get('metadata', {})) + metadata=item.get('metadata', {}), _check_type=_check_type) m.append(sc) - kwargs = {'check_type': False} + kwargs = {'_check_type': _check_type} if unary_query: kwargs['namespace'] = response.get('namespace', '') kwargs['matches'] = m @@ -294,6 +295,7 @@ def fetch(self, *args, **kwargs): def query(self, vector=[], id='', queries=[], **kwargs): timeout = kwargs.pop('timeout', None) + _check_type = kwargs.pop('_check_type', False) def _query_transform(item): if isinstance(item, GRPCQueryVector): @@ -315,7 +317,7 @@ def _query_transform(item): **{k: v for k, v in kwargs.items() if k in _QUERY_ARGS}) response = self._wrap_grpc_call(self.stub.Query, request, timeout=timeout) json_response = json_format.MessageToDict(response) - return parse_query_response(json_response, vector or id) + return parse_query_response(json_response, vector or id, _check_type) def update(self, id, async_req=False, **kwargs): _UPDATE_ARGS = ['values', 'set_metadata', 'namespace'] From e3cc60b39a87dfc0e66cf2e66822714c927bdfe4 Mon Sep 17 00:00:00 2001 From: ilai Date: Wed, 28 Dec 2022 19:00:01 +0200 Subject: [PATCH 15/25] [grpc] Make _check_type=Flase hardcoded Following comment in PR #118 --- pinecone/core/grpc/index_grpc.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index 29df38321..1ae2c10e6 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -295,7 +295,6 @@ def fetch(self, *args, **kwargs): def query(self, vector=[], id='', queries=[], **kwargs): timeout = kwargs.pop('timeout', None) - _check_type = kwargs.pop('_check_type', False) def _query_transform(item): if isinstance(item, GRPCQueryVector): @@ -317,7 +316,7 @@ def _query_transform(item): **{k: v for k, v in kwargs.items() if k in _QUERY_ARGS}) response = self._wrap_grpc_call(self.stub.Query, request, timeout=timeout) json_response = json_format.MessageToDict(response) - return parse_query_response(json_response, vector or id, _check_type) + return parse_query_response(json_response, vector or id, _check_type=False) def update(self, id, async_req=False, **kwargs): _UPDATE_ARGS = ['values', 'set_metadata', 'namespace'] From 197820457cbc469d8976d7b2c791a3697ec0dba3 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Wed, 28 Dec 2022 22:05:06 +0200 Subject: [PATCH 16/25] implement batching --- pinecone/index.py | 50 ++++++++++++++++++++++++++++++++++++----------- requirements.txt | 3 ++- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/pinecone/index.py b/pinecone/index.py index 9a263a222..5a57a6ef5 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -1,7 +1,7 @@ # # Copyright (c) 2020-2021 Pinecone Systems Inc. All right reserved. # - +from tqdm import tqdm from collections.abc import Iterable from typing import Union, List, Tuple, Optional, Dict, Any @@ -64,6 +64,8 @@ def __init__(self, index_name: str, pool_threads=1): def upsert(self, vectors: Union[List[Vector], List[Tuple]], namespace: Optional[str] = None, + batch_size: Optional[int] = None, + show_progress: bool = True, **kwargs) -> UpsertResponse: """ The upsert operation writes vectors into a namespace. @@ -93,26 +95,43 @@ def upsert(self, Note: the dimension of each vector must match the dimension of the index. namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] - + batch_size (int): The number of vectors to upsert in each batch. + If not specified, all vectors will be upserted in a single batch. [optional] + show_progress (bool): Whether to show a progress bar using tqdm. + Applied only if batch_size is provided. Defaults to True. Keyword Args: Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpsertRequest for more details. Returns: UpsertResponse, includes the number of vectors upserted. """ _check_type = kwargs.pop('_check_type', False) - args_dict = self._parse_args_to_dict([('namespace', namespace)]) - def _vector_transform(item): - if isinstance(item, Vector): - return item - if isinstance(item, tuple): - id, values, metadata = fix_tuple_length(item, 3) - return Vector(id=id, values=values, metadata=metadata or {}, _check_type=_check_type) - raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") + if batch_size is None: + return self._upsert_batch(vectors, namespace, **kwargs) + + if not isinstance(batch_size, int) or batch_size <= 0: + raise ValueError('batch_size must be a positive integer') + + pbar = tqdm(total=len(vectors), disable=not show_progress, desc='Upserted vectors') + total_upserted = 0 + for i in range(0, len(vectors), batch_size): + batch = vectors[i:i + batch_size] + batch_result = self._upsert_batch(batch, namespace, **kwargs) + total_upserted += batch_result.upserted_count + pbar.update(len(batch)) + return UpsertResponse(upserted_count=total_upserted) + + def _upsert_batch(self, + vectors: List[Vector], + namespace: Optional[str], + _check_type: bool, + **kwargs) -> UpsertResponse: + vectors = list(map(self._transform_upsert_vector, vectors)) + args_dict = self._parse_args_to_dict([('namespace', namespace)]) return self._vector_api.upsert( UpsertRequest( - vectors=list(map(_vector_transform, vectors)), + vectors=vectors, **args_dict, _check_type=_check_type, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS} @@ -120,6 +139,15 @@ def _vector_transform(item): **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS} ) + @staticmethod + def _transform_upsert_vector(item: Union[Vector, Tuple], _check_type): + if isinstance(item, Vector): + return item + if isinstance(item, tuple): + id, values, metadata = fix_tuple_length(item, 3) + return Vector(id=id, values=values, metadata=metadata or {}, _check_type=_check_type) + raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") + @validate_and_convert_errors def delete(self, ids: Optional[List[str]] = None, diff --git a/requirements.txt b/requirements.txt index 05b55a2ad..823317270 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,5 @@ typing-extensions>=3.7.4 dnspython>=2.0.0 # openapi generated client: python_dateutil >= 2.5.3 -urllib3 >= 1.21.1 \ No newline at end of file +urllib3 >= 1.21.1 +tqdm >= 4.64.1 \ No newline at end of file From 19493223625a5a189a65a9871f666be59eba68aa Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Wed, 28 Dec 2022 22:06:41 +0200 Subject: [PATCH 17/25] use dict instead of Dict --- pinecone/core/grpc/index_grpc.py | 12 ++++++------ pinecone/index.py | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index d55491706..f672e35ed 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -311,7 +311,7 @@ def delete(self, ids: Optional[List[str]] = None, delete_all: Optional[bool] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, async_req: bool = False, **kwargs) -> Union[DeleteResponse, PineconeGrpcFuture]: """ @@ -336,7 +336,7 @@ def delete(self, Default is False. namespace (str): The namespace to delete vectors from [optional] If not specified, the default namespace is used. - filter (Dict[str, Union[str, float, int, bool, List, Dict]]): + filter (Dict[str, Union[str, float, int, bool, List, dict]]): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] @@ -396,7 +396,7 @@ def query(self, queries: Optional[Union[List[GRPCQueryVector], List[Tuple]]] = None, namespace: Optional[str] = None, top_k: Optional[int] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, **kwargs) -> QueryResponse: @@ -423,7 +423,7 @@ def query(self, top_k (int): The number of results to return for each query. Must be an integer greater than 1. namespace (str): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - filter (Dict[str, Union[str, float, int, bool, List, Dict]]): + filter (Dict[str, Union[str, float, int, bool, List, dict]]): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] include_values (bool): Indicates whether vector values are included in the response. @@ -511,7 +511,7 @@ def update(self, return self._wrap_grpc_call(self.stub.Update, request, timeout=timeout) def describe_index_stats(self, - filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, **kwargs) -> DescribeIndexStatsResponse: """ The DescribeIndexStats operation returns statistics about the index's contents. @@ -522,7 +522,7 @@ def describe_index_stats(self, >>> index.describe_index_stats(filter={'key': 'value'}) Args: - filter (Dict[str, Union[str, float, int, bool, List, Dict]]): + filter (Dict[str, Union[str, float, int, bool, List, dict]]): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] diff --git a/pinecone/index.py b/pinecone/index.py index 9a263a222..f86555403 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -125,7 +125,7 @@ def delete(self, ids: Optional[List[str]] = None, delete_all: Optional[bool] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, **kwargs) -> Dict[str, Any]: """ The Delete operation deletes vectors from the index, from a single namespace. @@ -151,7 +151,7 @@ def delete(self, Default is False. namespace (str): The namespace to delete vectors from [optional] If not specified, the default namespace is used. - filter (Dict[str, Union[str, float, int, bool, List, Dict]]): + filter (Dict[str, Union[str, float, int, bool, List, dict]]): If specified, the metadata filter here will be used to select the vectors to delete. This is mutually exclusive with specifying ids to delete in the ids param or using delete_all=True. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] @@ -212,7 +212,7 @@ def query(self, queries: Optional[Union[List[QueryVector], List[Tuple]]] = None, top_k: Optional[int] = None, namespace: Optional[str] = None, - filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, include_values: Optional[bool] = None, include_metadata: Optional[bool] = None, **kwargs) -> QueryResponse: @@ -241,7 +241,7 @@ def query(self, top_k (int): The number of results to return for each query. Must be an integer greater than 1. namespace (str): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional] - filter (Dict[str, Union[str, float, int, bool, List, Dict]]): + filter (Dict[str, Union[str, float, int, bool, List, dict]): The filter to apply. You can use vector metadata to limit your search. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] include_values (bool): Indicates whether vector values are included in the response. @@ -345,7 +345,7 @@ def update(self, @validate_and_convert_errors def describe_index_stats(self, - filter: Optional[Dict[str, Union[str, float, int, bool, List, Dict]]] = None, + filter: Optional[Dict[str, Union[str, float, int, bool, List, dict]]] = None, **kwargs) -> DescribeIndexStatsResponse: """ The DescribeIndexStats operation returns statistics about the index's contents. @@ -358,7 +358,7 @@ def describe_index_stats(self, >>> index.describe_index_stats(filter={'key': 'value'}) Args: - filter (Dict[str, Union[str, float, int, bool, List, Dict]]): + filter (Dict[str, Union[str, float, int, bool, List, dict]]): If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/.. [optional] From ea057f7c4142ebe61a3379763d2c095a9048de7a Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Wed, 28 Dec 2022 22:33:10 +0200 Subject: [PATCH 18/25] rename --- tests/unit/test_grpc_index.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_grpc_index.py b/tests/unit/test_grpc_index.py index 280f077dd..e43d6bf1d 100644 --- a/tests/unit/test_grpc_index.py +++ b/tests/unit/test_grpc_index.py @@ -5,7 +5,7 @@ UpsertRequest, FetchRequest, QueryRequest, DeleteRequest, QueryVector -class TestRestIndex: +class TestGrpcIndex: def setup_method(self): self.vector_dim = 8 From 6811fa189c9d44f2346288bee7511c5a74e6de5a Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 29 Dec 2022 10:16:13 +0200 Subject: [PATCH 19/25] cover parse query in tests --- tests/unit/test_index.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 24fe975b4..3234fccd4 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -1,5 +1,5 @@ import pinecone -from pinecone import DescribeIndexStatsRequest +from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse class TestRestIndex: @@ -57,11 +57,27 @@ def test_upsert_vectors_upsertInputVectors(self, mocker): # region: query tests def test_query_byVectorNoFilter_queryVectorNoFilter(self, mocker): - mocker.patch.object(self.index._vector_api, 'query', autospec=True) - self.index.query(top_k=10, vector=self.vals1) + response = QueryResponse(results=[], + matches=[ScoredVector(id="1", + score=0.9, + values=[0.0], + metadata={"a": 2})], + namespace="test") + + mocker.patch.object(self.index._vector_api, 'query', autospec=True, return_value=response) + + actual = self.index.query(top_k=10, vector=self.vals1) + self.index._vector_api.query.assert_called_once_with( pinecone.QueryRequest(top_k=10, vector=self.vals1) ) + expected = QueryResponse(matches=[ScoredVector(id="1", + score=0.9, + values=[0.0], + metadata={"a": 2})], + namespace="test") + expected._data_store.pop('results', None) + assert actual == expected def test_query_byVectorWithFilter_queryVectorWithFilter(self, mocker): mocker.patch.object(self.index._vector_api, 'query', autospec=True) From 0d019e0b0031eb0255e36c11d0de571184d0fd70 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 29 Dec 2022 14:00:12 +0200 Subject: [PATCH 20/25] test and doc parallel upserts --- pinecone/core/grpc/index_grpc.py | 3 +-- pinecone/index.py | 2 ++ tests/unit/test_grpc_index.py | 15 +++++++++++++++ tests/unit/test_index.py | 33 ++++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 2 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index f672e35ed..ee0502f5b 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -281,11 +281,10 @@ def upsert(self, Note: the dimension of each vector must match the dimension of the index. async_req (bool): If True, the upsert operation will be performed asynchronously. - Defaults to False. [optional] + Defaults to False. See: https://docs.pinecone.io/docs/performance-tuning [optional] namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] Returns: UpsertResponse, contains the number of vectors upserted - or a PineconeGrpcFuture object if async_req is True. """ args_dict = self._parse_args_to_dict([('namespace', namespace)]) diff --git a/pinecone/index.py b/pinecone/index.py index f86555403..db40290d8 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -71,6 +71,8 @@ def upsert(self, API reference: https://docs.pinecone.io/reference/upsert + To upsert in parallel follow: https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel + Examples: >>> index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}), ('id2', [1.0, 2.0, 3.0])]) >>> index.upsert([Vector(id='id1', values=[1.0, 2.0, 3.0], metadata={'key': 'value'}), diff --git a/tests/unit/test_grpc_index.py b/tests/unit/test_grpc_index.py index e43d6bf1d..74f4cdb51 100644 --- a/tests/unit/test_grpc_index.py +++ b/tests/unit/test_grpc_index.py @@ -60,6 +60,21 @@ def test_upsert_vectors_upsertInputVectors(self, mocker): namespace='ns'), timeout=None) + def test_upsert_async_upsertInputVectorsAsync(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True) + self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns', + async_req=True) + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Upsert.future, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + # endregion # region: query tests diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index 3234fccd4..f805c5415 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -1,3 +1,5 @@ +from pinecone.core.client.api_client import Endpoint + import pinecone from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse @@ -52,6 +54,37 @@ def test_upsert_vectors_upsertInputVectors(self, mocker): ], namespace='ns') ) + def test_upsert_parallelUpsert_callUpsertParallel(self, mocker): + mocker.patch.object(Endpoint, '__call__', autospec=True) + chunks = [[pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], + [pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2)]] + with pinecone.Index('example-index', pool_threads=30) as index: + # Send requests in parallel + async_results = [ + index.upsert(vectors=ids_vectors_chunk, namespace="ns", async_req=True) + for ids_vectors_chunk in chunks + ] + # Wait for and retrieve responses (this raises in case of error) + [async_result.get() for async_result in async_results] + + Endpoint.__call__.assert_any_call( + index._vector_api.upsert, + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + ], + namespace='ns'), + async_req=True + ) + + Endpoint.__call__.assert_any_call( + index._vector_api.upsert, + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + ], + namespace='ns'), + async_req=True + ) + # endregion # region: query tests From 648a547086a6ab60962c52ed87ea40a54f5f369f Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 29 Dec 2022 14:06:11 +0200 Subject: [PATCH 21/25] rename parse args --- pinecone/core/grpc/index_grpc.py | 38 ++++++++++++++++---------------- pinecone/index.py | 38 ++++++++++++++++---------------- 2 files changed, 38 insertions(+), 38 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index ee0502f5b..6fe2c971f 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -287,7 +287,7 @@ def upsert(self, Returns: UpsertResponse, contains the number of vectors upserted """ - args_dict = self._parse_args_to_dict([('namespace', namespace)]) + args_dict = self._parse_non_empty_args([('namespace', namespace)]) def _vector_transform(item): if isinstance(item, GRPCVector): @@ -348,10 +348,10 @@ def delete(self, if filter is not None: filter = dict_to_proto_struct(filter) - args_dict = self._parse_args_to_dict([('ids', ids), - ('delete_all', delete_all), - ('namespace', namespace), - ('filter', filter)]) + args_dict = self._parse_non_empty_args([('ids', ids), + ('delete_all', delete_all), + ('namespace', namespace), + ('filter', filter)]) timeout = kwargs.pop('timeout', None) request = DeleteRequest(**args_dict, **kwargs) @@ -382,7 +382,7 @@ def fetch(self, """ timeout = kwargs.pop('timeout', None) - args_dict = self._parse_args_to_dict([('namespace', namespace)]) + args_dict = self._parse_non_empty_args([('namespace', namespace)]) request = FetchRequest(ids=ids, **args_dict, **kwargs) response = self._wrap_grpc_call(self.stub.Fetch, request, timeout=timeout) @@ -449,14 +449,14 @@ def _query_transform(item): if filter is not None: filter = dict_to_proto_struct(filter) - args_dict = self._parse_args_to_dict([('vector', vector), - ('id', id), - ('queries', queries), - ('namespace', namespace), - ('top_k', top_k), - ('filter', filter), - ('include_values', include_values), - ('include_metadata', include_metadata)]) + args_dict = self._parse_non_empty_args([('vector', vector), + ('id', id), + ('queries', queries), + ('namespace', namespace), + ('top_k', top_k), + ('filter', filter), + ('include_values', include_values), + ('include_metadata', include_metadata)]) request = QueryRequest(**args_dict) @@ -498,9 +498,9 @@ def update(self, set_metadata = dict_to_proto_struct(set_metadata) timeout = kwargs.pop('timeout', None) - args_dict = self._parse_args_to_dict([('values', values), - ('set_metadata', set_metadata), - ('namespace', namespace)]) + args_dict = self._parse_non_empty_args([('values', values), + ('set_metadata', set_metadata), + ('namespace', namespace)]) request = UpdateRequest(id=id, **args_dict) if async_req: @@ -529,7 +529,7 @@ def describe_index_stats(self, """ if filter is not None: filter = dict_to_proto_struct(filter) - args_dict = self._parse_args_to_dict([('filter', filter)]) + args_dict = self._parse_non_empty_args([('filter', filter)]) timeout = kwargs.pop('timeout', None) request = DescribeIndexStatsRequest(**args_dict) @@ -538,5 +538,5 @@ def describe_index_stats(self, return parse_stats_response(json_response) @staticmethod - def _parse_args_to_dict(args: List[Tuple[str, Any]]) -> Dict[str, Any]: + def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: return {arg_name: val for arg_name, val in args if val is not None} diff --git a/pinecone/index.py b/pinecone/index.py index db40290d8..a18477ff1 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -102,7 +102,7 @@ def upsert(self, Returns: UpsertResponse, includes the number of vectors upserted. """ _check_type = kwargs.pop('_check_type', False) - args_dict = self._parse_args_to_dict([('namespace', namespace)]) + args_dict = self._parse_non_empty_args([('namespace', namespace)]) def _vector_transform(item): if isinstance(item, Vector): @@ -165,10 +165,10 @@ def delete(self, Returns: An empty dictionary if the delete operation was successful. """ _check_type = kwargs.pop('_check_type', False) - args_dict = self._parse_args_to_dict([('ids', ids), - ('delete_all', delete_all), - ('namespace', namespace), - ('filter', filter)]) + args_dict = self._parse_non_empty_args([('ids', ids), + ('delete_all', delete_all), + ('namespace', namespace), + ('filter', filter)]) return self._vector_api.delete( DeleteRequest( @@ -204,7 +204,7 @@ def fetch(self, Returns: FetchResponse object which contains the list of Vector objects, and namespace name. """ - args_dict = self._parse_args_to_dict([('namespace', namespace)]) + args_dict = self._parse_non_empty_args([('namespace', namespace)]) return self._vector_api.fetch(ids=ids, **args_dict, **kwargs) @validate_and_convert_errors @@ -272,14 +272,14 @@ def _query_transform(item): _check_type = kwargs.pop('_check_type', False) queries = list(map(_query_transform, queries)) if queries is not None else None - args_dict = self._parse_args_to_dict([('vector', vector), - ('id', id), - ('queries', queries), - ('top_k', top_k), - ('namespace', namespace), - ('filter', filter), - ('include_values', include_values), - ('include_metadata', include_metadata)]) + args_dict = self._parse_non_empty_args([('vector', vector), + ('id', id), + ('queries', queries), + ('top_k', top_k), + ('namespace', namespace), + ('filter', filter), + ('include_values', include_values), + ('include_metadata', include_metadata)]) def _query_transform(item): if isinstance(item, QueryVector): @@ -334,9 +334,9 @@ def update(self, Returns: An empty dictionary if the update was successful. """ _check_type = kwargs.pop('_check_type', False) - args_dict = self._parse_args_to_dict([('values', values), - ('set_metadata', set_metadata), - ('namespace', namespace)]) + args_dict = self._parse_non_empty_args([('values', values), + ('set_metadata', set_metadata), + ('namespace', namespace)]) return self._vector_api.update(UpdateRequest( id=id, **args_dict, @@ -367,7 +367,7 @@ def describe_index_stats(self, Returns: DescribeIndexStatsResponse object which contains stats about the index. """ _check_type = kwargs.pop('_check_type', False) - args_dict = self._parse_args_to_dict([('filter', filter)]) + args_dict = self._parse_non_empty_args([('filter', filter)]) return self._vector_api.describe_index_stats( DescribeIndexStatsRequest( @@ -379,5 +379,5 @@ def describe_index_stats(self, ) @staticmethod - def _parse_args_to_dict(args: List[Tuple[str, Any]]) -> Dict[str, Any]: + def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: return {arg_name: val for arg_name, val in args if val is not None} From 534812d9645172e274d9b5f6257e343789699e13 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 29 Dec 2022 16:41:10 +0200 Subject: [PATCH 22/25] add tests and impel for grpc index --- pinecone/core/grpc/index_grpc.py | 47 +++++++++-- pinecone/index.py | 18 +++-- tests/unit/test_grpc_index.py | 126 ++++++++++++++++++++++++++++- tests/unit/test_index.py | 135 ++++++++++++++++++++++++++++++- 4 files changed, 313 insertions(+), 13 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index 6fe2c971f..fa1b6de12 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -10,6 +10,8 @@ import grpc from google.protobuf import json_format from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous +from tqdm import tqdm + from pinecone import FetchResponse, QueryResponse, ScoredVector, SingleQueryResults, DescribeIndexStatsResponse from pinecone.config import Config from pinecone.core.client.model.namespace_summary import NamespaceSummary @@ -255,6 +257,8 @@ def upsert(self, vectors: Union[List[GRPCVector], List[Tuple]], async_req: bool = False, namespace: Optional[str] = None, + batch_size: Optional[int] = None, + show_progress: bool = True, **kwargs) -> Union[UpsertResponse, PineconeGrpcFuture]: """ The upsert operation writes vectors into a namespace. @@ -281,13 +285,21 @@ def upsert(self, Note: the dimension of each vector must match the dimension of the index. async_req (bool): If True, the upsert operation will be performed asynchronously. + Cannot be used with batch_size. Defaults to False. See: https://docs.pinecone.io/docs/performance-tuning [optional] namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] + batch_size (int): The number of vectors to upsert in each batch. + Cannot be used with async_req=Ture. + If not specified, all vectors will be upserted in a single batch. [optional] + show_progress (bool): Whether to show a progress bar using tqdm. + Applied only if batch_size is provided. Default is True. Returns: UpsertResponse, contains the number of vectors upserted """ - - args_dict = self._parse_non_empty_args([('namespace', namespace)]) + if async_req and batch_size is not None: + raise ValueError('async_req is not supported when batch_size is provided.' + 'To upsert in parallel, please follow: ' + 'https://docs.pinecone.io/docs/performance-tuning') def _vector_transform(item): if isinstance(item, GRPCVector): @@ -299,12 +311,37 @@ def _vector_transform(item): timeout = kwargs.pop('timeout', None) - request = UpsertRequest(vectors=list(map(_vector_transform, vectors)), **args_dict, **kwargs) + vectors = list(map(_vector_transform, vectors)) if async_req: + args_dict = self._parse_non_empty_args([('namespace', namespace)]) + request = UpsertRequest(vectors=vectors, **args_dict, **kwargs) future = self._wrap_grpc_call(self.stub.Upsert.future, request, timeout=timeout) return PineconeGrpcFuture(future) - else: - return self._wrap_grpc_call(self.stub.Upsert, request, timeout=timeout) + + if batch_size is None: + return self._upsert_batch(vectors, namespace, timeout=timeout, **kwargs) + + if not isinstance(batch_size, int) or batch_size <= 0: + raise ValueError('batch_size must be a positive integer') + + pbar = tqdm(total=len(vectors), disable=not show_progress, desc='Upserted vectors') + total_upserted = 0 + for i in range(0, len(vectors), batch_size): + batch_result = self._upsert_batch(vectors[i:i + batch_size], namespace, timeout=timeout, **kwargs) + pbar.update(batch_result.upserted_count) + # we can't use here pbar.n for the case show_progress=False + total_upserted += batch_result.upserted_count + + return UpsertResponse(upserted_count=total_upserted) + + def _upsert_batch(self, + vectors: List[GRPCVector], + namespace: Optional[str], + timeout: Optional[float], + **kwargs) -> UpsertResponse: + args_dict = self._parse_non_empty_args([('namespace', namespace)]) + request = UpsertRequest(vectors=vectors, **args_dict) + return self._wrap_grpc_call(self.stub.Upsert, request, timeout=timeout, **kwargs) def delete(self, ids: Optional[List[str]] = None, diff --git a/pinecone/index.py b/pinecone/index.py index aa6b02bff..2f8260ec0 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -100,7 +100,7 @@ def upsert(self, batch_size (int): The number of vectors to upsert in each batch. If not specified, all vectors will be upserted in a single batch. [optional] show_progress (bool): Whether to show a progress bar using tqdm. - Applied only if batch_size is provided. Defaults to True. + Applied only if batch_size is provided. Default is True. Keyword Args: Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpsertRequest for more details. @@ -108,6 +108,11 @@ def upsert(self, """ _check_type = kwargs.pop('_check_type', False) + if kwargs.get('async_req', False) and batch_size is not None: + raise ValueError('async_req is not supported when batch_size is provided.' + 'To upsert in parallel, please follow: ' + 'https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel') + if batch_size is None: return self._upsert_batch(vectors, namespace, _check_type, **kwargs) elif kwargs.get('async_req', False): @@ -121,10 +126,11 @@ def upsert(self, pbar = tqdm(total=len(vectors), disable=not show_progress, desc='Upserted vectors') total_upserted = 0 for i in range(0, len(vectors), batch_size): - batch = vectors[i:i + batch_size] - batch_result = self._upsert_batch(batch, namespace, _check_type, **kwargs) + batch_result = self._upsert_batch(vectors[i:i + batch_size], namespace, _check_type, **kwargs) + pbar.update(batch_result.upserted_count) + # we can't use here pbar.n for the case show_progress=False total_upserted += batch_result.upserted_count - pbar.update(len(batch)) + return UpsertResponse(upserted_count=total_upserted) def _upsert_batch(self, @@ -135,7 +141,7 @@ def _upsert_batch(self, args_dict = self._parse_non_empty_args([('namespace', namespace)]) - def transform_upsert_vector(item: Union[Vector, Tuple]): + def _vector_transform(item: Union[Vector, Tuple]): if isinstance(item, Vector): return item if isinstance(item, tuple): @@ -145,7 +151,7 @@ def transform_upsert_vector(item: Union[Vector, Tuple]): return self._vector_api.upsert( UpsertRequest( - vectors=list(map(transform_upsert_vector, vectors)), + vectors=list(map(_vector_transform, vectors)), **args_dict, _check_type=_check_type, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS} diff --git a/tests/unit/test_grpc_index.py b/tests/unit/test_grpc_index.py index 74f4cdb51..3d1921675 100644 --- a/tests/unit/test_grpc_index.py +++ b/tests/unit/test_grpc_index.py @@ -1,8 +1,10 @@ +import pytest + import pinecone from core.utils import dict_to_proto_struct from pinecone import DescribeIndexStatsRequest from pinecone.core.grpc.protos.vector_service_pb2 import Vector, DescribeIndexStatsRequest, UpdateRequest, \ - UpsertRequest, FetchRequest, QueryRequest, DeleteRequest, QueryVector + UpsertRequest, FetchRequest, QueryRequest, DeleteRequest, QueryVector, UpsertResponse class TestGrpcIndex: @@ -75,6 +77,128 @@ def test_upsert_async_upsertInputVectorsAsync(self, mocker): namespace='ns'), timeout=None) + def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns', + batch_size=1, + show_progress=False) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns'), + timeout=None) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + assert result.upserted_count == 2 + + def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2)), + Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns', + batch_size=2) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns'), + timeout=None) + + assert result.upserted_count == 3 + + def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns', + batch_size=5) + + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + assert result.upserted_count == 2 + + def test_upsert_tuplesList_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert([('vec1', self.vals1, self.md1), + ('vec2', self.vals2, self.md2), + ('vec3', self.vals1, self.md1)], + namespace='ns', + batch_size=2) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns'), + timeout=None) + + assert result.upserted_count == 3 + + def test_upsert_batchSizeIsNotPositive_errorIsRaised(self): + with pytest.raises(ValueError, match='batch_size must be a positive integer'): + self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns', + batch_size=0) + + with pytest.raises(ValueError, match='batch_size must be a positive integer'): + self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns', + batch_size=-1) + + def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self): + with pytest.raises(ValueError, match='async_req is not supported when batch_size is provided.'): + self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns', + batch_size=2, + async_req=True) + # endregion # region: query tests diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index f805c5415..6c89467aa 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -1,7 +1,9 @@ +import pytest + from pinecone.core.client.api_client import Endpoint import pinecone -from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse +from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse, UpsertResponse class TestRestIndex: @@ -85,6 +87,137 @@ def test_upsert_parallelUpsert_callUpsertParallel(self, mocker): async_req=True ) + def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index._vector_api, + 'upsert', + autospec=True, + side_effect=lambda upsert_request: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2)], + namespace='ns', + batch_size=1, + show_progress=False) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + ], namespace='ns') + ) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + ], namespace='ns') + ) + + assert result.upserted_count == 2 + + def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index._vector_api, + 'upsert', + autospec=True, + side_effect=lambda upsert_request: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=2) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + ], namespace='ns') + ) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), + ], namespace='ns') + ) + + assert result.upserted_count == 3 + + def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index._vector_api, + 'upsert', + autospec=True, + side_effect=lambda upsert_request: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=5) + + self.index._vector_api.upsert.assert_called_once_with( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), + ], namespace='ns') + ) + + assert result.upserted_count == 3 + + def test_upsert_tuplesList_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index._vector_api, + 'upsert', + autospec=True, + side_effect=lambda upsert_request: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert(vectors= + [('vec1', self.vals1, self.md1), + ('vec2', self.vals2, self.md2), + ('vec3', self.vals1, self.md1)], + namespace='ns', + batch_size=2) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + ], namespace='ns') + ) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), + ], namespace='ns') + ) + + assert result.upserted_count == 3 + + def test_upsert_batchSizeIsNotPositive_errorIsRaised(self): + with pytest.raises(ValueError, match='batch_size must be a positive integer'): + self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=0) + + with pytest.raises(ValueError, match='batch_size must be a positive integer'): + self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=-1) + + def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self): + with pytest.raises(ValueError, match='async_req is not supported when batch_size is provided.'): + self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=1, + async_req=True) + # endregion # region: query tests From f82f5e81f904eef32612b75dd7d993f1a746333f Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Sun, 1 Jan 2023 12:55:15 +0200 Subject: [PATCH 23/25] remove redundant code --- pinecone/index.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pinecone/index.py b/pinecone/index.py index 2f8260ec0..b14b39e71 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -115,10 +115,6 @@ def upsert(self, if batch_size is None: return self._upsert_batch(vectors, namespace, _check_type, **kwargs) - elif kwargs.get('async_req', False): - raise ValueError('async_req is not supported when batch_size is provided.' - 'To upsert in parallel, please follow: ' - 'https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel') if not isinstance(batch_size, int) or batch_size <= 0: raise ValueError('batch_size must be a positive integer') From b85cdfcd839107cd357d95bcc80fc66c5ac90a6f Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Sun, 1 Jan 2023 18:08:00 +0200 Subject: [PATCH 24/25] v2.1.0 change version and changlog --- CHANGELOG.md | 13 ++++++++++--- pinecone/__version__ | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ddc5b2f3..a79616838 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,15 @@ ## Unreleased Changes None +## [2.1.0](https://github.com/pinecone-io/pinecone-python-client/compare/v2.0.13...v2.1.0) +- Fix "Connection Reset by peer" error after long idle periods +- Add typing and explicit names for arguments in all client operations +- Add docstrings to all client operations +- Support batch upsert by passing `batch_size` to `upsert` method +- Improve gRPC query results parsing performance -## [2.0.13](https://github.com/pinecone-io/pinecone-python-client/compare/v2.0.13...v2.0.12) + +## [2.0.13](https://github.com/pinecone-io/pinecone-python-client/compare/v2.0.12...v2.0.13) - Added support for collections - Users can manage collections using ``create_collection`` , ``describe_collection`` and ``delete_collection`` calls. - Users can specify additional ``source_collection`` parameter during index creation to create index from a collection @@ -11,13 +18,13 @@ None - Added support for vertical scaling. This can be done by changing ```pod_type ``` via the ```configure_index``` call or during index creation. - Updated dependency requirements for grpc client. -## [2.0.12](https://github.com/pinecone-io/pinecone-python-client/compare/v2.0.12...v2.0.11) +## [2.0.12](https://github.com/pinecone-io/pinecone-python-client/compare/v2.0.11...v2.0.12) - Changed grpcio verison to be > 1.44.1 - Sanitized repo by removing leftover files from old versions. - Added more info to ```describe_index_stats``` call. The call now gives a namespace wise vector count breakdown. -## [2.0.11](https://github.com/pinecone-io/pinecone-python-client/compare/v2.0.11...v2.0.10) +## [2.0.11](https://github.com/pinecone-io/pinecone-python-client/compare/v2.0.10...v2.0.11) ### Changed - Added support of querying by a single vector. - This is a step in deprecating batch queries. diff --git a/pinecone/__version__ b/pinecone/__version__ index 82bd22f9c..7ec1d6db4 100644 --- a/pinecone/__version__ +++ b/pinecone/__version__ @@ -1 +1 @@ -2.0.13 +2.1.0 From b627cc391a4d3d8fa8864464b566d9e1216c122f Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Mon, 2 Jan 2023 11:56:15 +0200 Subject: [PATCH 25/25] typo --- pinecone/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pinecone/config.py b/pinecone/config.py index c365c99c3..84b5793a5 100644 --- a/pinecone/config.py +++ b/pinecone/config.py @@ -42,7 +42,7 @@ class _CONFIG: Order of configs to load: - - configs specified explictly in reset + - configs specified explicitly in reset - environment variables - configs specified in the INI file - default configs