
    D8i                       d dl mZ d dlZd dlmZmZmZmZmZm	Z	m
Z
 d dlmZ d dlmZ d dlmZmZ ddlmZmZmZmZmZmZmZmZmZmZmZ dd	lmZ dd
l m!Z! d dl"m#Z$m%Z%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z, d dl-m.Z/m0Z0 d dl1m2Z3m4Z5m,Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z@mAZAmBZBmCZCmDZDmEZEmFZF d dlGmHZH d dlIm2Z2m?Z? d dlJmKZKmLZL ddlMmNZN ddlOmPZP e
rd dlmQZQ ddlRmSZSmTZTmUZUmVZVmWZW g dZX ej                  eZ      Z[	  G d deN      Z\y)    )annotationsN)ListAnyIterablecastLiteralIteratorTYPE_CHECKING)tqdm)require_kwargs)as_completedFuture   )dict_to_proto_structparse_fetch_response parse_fetch_by_metadata_responseparse_query_responsequery_response_to_dictparse_stats_responseparse_upsert_responseparse_update_responseparse_delete_responseparse_namespace_descriptionparse_list_namespaces_response)VectorFactoryGRPC)SparseValuesFactory)IndexDescriptionNamespaceDescriptionListNamespacesResponse)FetchByMetadataResponseUpdateResponseUpsertResponseFetchResponseQueryResponse)ListResponse
Pagination)VectorQueryVectorr$   UpsertRequestDeleteRequestQueryRequestFetchRequestFetchByMetadataRequestUpdateRequestListRequestDescribeIndexStatsRequestSparseValuesDescribeNamespaceRequestDeleteNamespaceRequestListNamespacesRequestCreateNamespaceRequestMetadataSchemaMetadataFieldPropertiesVectorServiceStub)r'   r1   )QueryNamespacesResultsQueryResultsAggregator)GRPCIndexBase)PineconeGrpcFuture)Type   )SparseVectorTypedDictVectorTypedDictVectorTupleFilterTypedDictVectorMetadataTypedDict)	GRPCIndex
GRPCVectorGRPCQueryVectorGRPCSparseValuesr   r   c                     e Zd ZdZedd       Z	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZe	dd       Z
	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 d dZ	 	 d!	 	 	 	 	 	 	 d"d	Z	 	 	 	 d#	 	 	 	 	 	 	 	 	 	 	 d$d
Z	 	 	 	 	 	 	 	 d%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&dZ	 	 	 	 	 	 	 	 	 d'	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d(dZ	 	 	 	 	 d)	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d*dZ	 	 	 	 	 	 	 	 d+	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,dZ	 	 	 	 d-	 	 	 	 	 	 	 	 	 d.dZd/dZ	 d0	 	 	 d1dZe	 d!	 	 	 	 	 	 	 d2d       Zed3d       Zed4d       Ze	 d5	 	 	 	 	 d6d       Zed0d7d       Ze	d8d       Zy)9rE   z<A client for interacting with a Pinecone index via GRPC API.c                    t         S )z:meta private:r8   )selfs    n/var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/pinecone/grpc/index_grpc.py
stub_classzGRPCIndex.stub_class^   s
     !     Nc                   |r|t        d      |j                  dd      }t        t        t        j
                  |            }|r| j                  d|fg      }t        dd|i||}	| j                  j                  | j                  j                  j                  |	|      }
t        |
t              r|
d   n|
}t        ||t               S | | j"                  ||fd|i|S t        |t$              r|dk  rt        d	      t'        t)        |      | d
      }d}d}t+        dt)        |      |      D ]J  } | j"                  ||||z    |fd|i|}|j-                  |j.                         ||j.                  z  }|}L ddlm} d}|rt5        |d      r|j6                  }nddlm}  |i       } |||      S )a<  
        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:

        .. code-block:: python

            >>> index.upsert([('id1', [1.0, 2.0, 3.0], {'key': 'value'}),
                              ('id2', [1.0, 2.0, 3.0])
                              ],
                              namespace='ns1', async_req=True)
            >>> index.upsert([{'id': 'id1', 'values': [1.0, 2.0, 3.0], 'metadata': {'key': 'value'}},
                              {'id': 'id2',
                                        'values': [1.0, 2.0, 3.0],
                                        'sparse_values': {'indices': [1, 8], 'values': [0.2, 0.4]},
                              ])
            >>> 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]),
                              GRPCVector(id='id3',
                                         values=[1.0, 2.0, 3.0],
                                         sparse_values=GRPCSparseValues(indices=[1, 2], values=[0.2, 0.4]))])

        Args:
            vectors (Union[list[Vector], list[Tuple]]): A list of vectors to upsert.

                     A vector can be represented by a 1) GRPCVector object, a 2) tuple or 3) a dictionary
                     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 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]),
                                 GRPCVector(id='id3',
                                            values=[1.0, 2.0, 3.0],
                                            sparse_values=GRPCSparseValues(indices=[1, 2], values=[0.2, 0.4]))

                    3) if a dictionary is used, it must be in the form
                       {'id': str, 'values': list[float], 'sparse_values': {'indices': list[int], 'values': list[float]},
                        'metadata': dict}

                    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=True.
                               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
        Nzasync_req is not supported when batch_size is provided.To upsert in parallel, please follow: https://docs.pinecone.io/docs/performance-tuningtimeout	namespacevectorsrP   r   rP   result_transformerz%batch_size must be a positive integerzUpserted vectorstotaldisabledesc)r"   _response_infoextract_response_infoupserted_countrZ    )
ValueErrorpoplistmapr   build_parse_non_empty_argsr)   runnerrunstubUpsertfuture
isinstancetupler=   r   _upsert_batchintr   lenrangeupdater^   pinecone.db_data.dataclassesr"   hasattrrZ   pinecone.utils.response_infor\   )rK   rR   	async_reqrQ   
batch_sizeshow_progresskwargsrP   	args_dictrequestfuture_resultrj   pbartotal_upsertedlast_batch_resultibatch_resultr"   response_infor\   s                       rL   upsertzGRPCIndex.upsertc   s   D /C  **Y-s,22G<=22[)4L3MNI#KGKyKFKG KKOODII,<,<,C,CWV]O^M *4M5)I]1%}F%<Q  %4%%gyT'TVTT*c*jAoDEE#g,M0AHZ[ q#g,
3 	-A-4--A
N+Y@GKQL KK334l999N ,	- 	@):<L!M-<<MJ1"5M^MZZrN   c                    | j                  d|fg      }t        dd|i|} | j                  j                  | j                  j
                  |fd|i|\  }}t        ||      S )NrQ   rR   rP   initial_metadatar_   )re   r)   rf   rg   rh   ri   r   )	rK   rR   rQ   rP   rx   ry   rz   responser   s	            rL   rm   zGRPCIndex._upsert_batch   sw     ..i0H/IJ	==9=%4T[[__IIg&
/6&
:@&
"" %X@PQQrN   c                *   	 ddl }t        ||j                        st        dt        |             t        t        |      | d      }g }| j                  ||      D ]V  }	| j                  t        t        t           |	      ||      }
|j                  t        |	             |j                  |
       X |rAt        t        t            |      }t        || d	
      D cg c]  }|j#                          }}d}d}|D ];  }
t%        |
d      st        |
j&                  t(              s+||
j&                  z  }|
}= d}|rt%        |d      r|j*                  }nddlm}  |i       }t1        ||      S # t        $ r t        d      w xY wc c}w )a  Upserts a dataframe into the index.

        Args:
            df: A pandas dataframe with the following columns: id, values, sparse_values, and metadata.
            namespace: The namespace to upsert into.
            batch_size: The number of rows to upsert in a single batch.
            use_async_requests: Whether to upsert multiple requests at the same time using asynchronous request mechanism.
                                Set to ``False``
            show_progress: Whether to show a progress bar.
        r   Nz]The `pandas` package is not installed. Please install pandas to use `upsert_from_dataframe()`z-Only pandas dataframes are supported. Found: zsending upsert requestsrV   )rv   )rR   rQ   ru   zcollecting async responses)iterablerX   rY   r^   rZ   r[   r]   )pandasImportErrorRuntimeErrorrk   	DataFramer`   typer   ro   _iter_dataframer   r   rb   rA   rq   appendr=   resultrs   r^   rn   rZ   rt   r\   r"   )rK   dfrQ   rv   use_async_requestsrw   pdr|   resultschunkrescast_resultsasync_resultr^   last_resultr   r\   s                    rL   upsert_from_dataframezGRPCIndex.upsert_from_dataframe   s   $	 "bll+LTRTXJWXX#b'}+<C\]))")D 	 E++T/2E:#,  C
 KKE
#NN3	  %7 8'BL %)) --5%  ##%G   	"Cs,-*S=O=OQT2U#"4"44!	"
 7;0@A'66MJ1"5M^MZZ]  	o 	,s   E8 #F8Fc              #     K   t        dt        |       |      D ](  }| j                  |||z    j                  d      }| * y w)Nr   records)orient)rp   ro   ilocto_dict)r   rv   r   batchs       rL   r   zGRPCIndex._iter_dataframe'  sI     q#b':. 	AGGAJ/77y7IEK	s   AAc                   |t        |      }nd}| j                  d|fd|fd|fd|fg      }|j                  dd      }	t        di ||}
|re| j                  j                  | j                  j                  j                  |
|	      }t        |t              r|d   n|}t        ||	t        	      S | j                  j                  | j                  j                  |
|	      \  }}t        ||
      S )a  
        The Delete operation deletes vectors from the index, from a single namespace.
        No error raised if the vector id does not exist.

        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 (FilterTypedDict):
                    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 `metadata filtering <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.

        .. admonition:: 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)

        Examples:

        .. code-block:: python

            >>> 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)
        Nids
delete_allrQ   filterrP   rS   r   rT   r   r_   )r   re   ra   r*   rf   rg   rh   Deleterj   rk   rl   r=   r   )rK   r   r   rQ   r   ru   rx   filter_structry   rP   rz   r{   rj   r   r   s                  rL   deletezGRPCIndex.delete-  s   ` 08M M..z*i(=)	
	 **Y-6)6v6 KKOODII,<,<,C,CWV]O^M)3M5)I]1%}F%<Q  *.9I9I7\c)d&H&(DTUUrN   c                   |j                  dd      }| j                  d|fg      }t        d	d|i||}|re| j                  j	                  | j
                  j                  j                  ||      }t        |t              r|d   n|}	t        |	t        |      S | j                  j	                  | j
                  j                  ||      \  }
}t        |
|      S )
a  
        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:

        .. code-block:: python

            >>> 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.
        rP   NrQ   r   rS   r   rU   rP   r   r_   )ra   re   r,   rf   rg   rh   Fetchrj   rk   rl   r=   r   )rK   r   rQ   ru   rx   rP   ry   rz   r{   rj   r   r   s               rL   fetchzGRPCIndex.fetchx  s    2 **Y-..i0H/IJ	>3>)>v> KKOODIIOO,B,BGU\O]M)3M5)I]1%}F%+?  *.'[b)c&H&'CSTTrN   c                   |j                  dd      }|t        |      }nd}| j                  d|fd|fd|fd|fg      }	t        di |	|}
|re| j                  j                  | j                  j                  j                  |
|      }t        |t              r|d   n|}t        |t        |	      S | j                  j                  | j                  j                  |
|      \  }}t        ||
      S )a  
        Fetch vectors by metadata filter.

        Look up and return vectors by metadata filter from a single namespace.
        The returned vectors include the vector data and/or metadata.

        Examples:

        .. code-block:: python

            >>> index.fetch_by_metadata(
            ...     filter={'genre': {'$in': ['comedy', 'drama']}, 'year': {'$eq': 2019}},
            ...     namespace='my_namespace',
            ...     limit=50
            ... )
            >>> index.fetch_by_metadata(
            ...     filter={'status': 'active'},
            ...     pagination_token='token123'
            ... )

        Args:
            filter (dict[str, Union[str, float, int, bool, List, dict]]):
                Metadata filter expression to select vectors.
                See `metadata filtering <https://www.pinecone.io/docs/metadata-filtering/>_`
            namespace (str): The namespace to fetch vectors from.
                            If not specified, the default namespace is used. [optional]
            limit (int): Max number of vectors to return. Defaults to 100. [optional]
            pagination_token (str): Pagination token to continue a previous listing operation. [optional]
            async_req (bool): If True, the fetch operation will be performed asynchronously.
                             Defaults to False. [optional]

        Returns:
            FetchByMetadataResponse: Object containing the fetched vectors, namespace, usage, and pagination token.
        rP   NrQ   r   limitpagination_tokenrS   r   r   r   r_   )ra   r   re   r-   rf   rg   rh   FetchByMetadatarj   rk   rl   r=   r   )rK   r   rQ   r   r   ru   rx   rP   r   ry   rz   r{   rj   r   r   s                  rL   fetch_by_metadatazGRPCIndex.fetch_by_metadata  s   V **Y-08M M..i(=)% #%56	
	 )?9?? KKOO		))00'7 , M *4M5)I]1%}F%+KU\  *.		))7G *9 *&H& 4HO_``rN   c	                h   ||t        d      |t        |      }
nd}
t        j                  |      }| j	                  d|fd|fd|fd|fd|
fd|fd	|fd
|fg      }t        di |}|	j                  dd      }| j                  j                  | j                  j                  ||      \  }}||fS )a"  
        Low-level query method that returns protobuf Message and initial metadata without parsing.
        Used internally by query() and query_namespaces() for performance.

        Returns:
            Tuple of (protobuf_message, initial_metadata). initial_metadata may be None.
        N%Cannot specify both `id` and `vector`vectoridrQ   top_kr   include_valuesinclude_metadatasparse_vectorrP   rS   r_   )r`   r   r   rd   re   r+   ra   rf   rg   rh   Query)rK   r   r   rQ   r   r   r   r   r   rx   r   ry   rz   rP   r   r   s                   rL   _queryzGRPCIndex._query  s    & ".DEE08M M+11-@..6"r
i(% =)!>2#%56 -0	
	 ++**Y-%)[[__TYY__gW^_%_"")))rN   c
                   |
j                  dd      }|	r||t        d      |t        |      }nd}t        j                  |      }| j                  d|fd|fd|fd|fd|fd	|fd
|fd|fg      }t        di |}| j                  j                  | j                  j                  j                  ||      }t        |t              r|d   n|}t        |t        |      S  | j                   d|||||||||d	|
\  }}t        |d|      S )an  
        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:

        .. code-block:: python

            >>> 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)
            >>> index.query(vector=[1, 2, 3], sparse_vector={'indices': [1, 2], 'values': [0.2, 0.4]},
            >>>             top_k=10, namespace='my_namespace')
            >>> index.query(vector=[1, 2, 3], sparse_vector=GRPCSparseValues([1, 2], [0.2, 0.4]),
            >>>             top_k=10, namespace='my_namespace')

        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
                                  ``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
                      ``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[str, float, int, bool, List, dict]]):
                    The filter to apply. You can use vector metadata to limit your search.
                    See `metadata filtering <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]
            sparse_vector: (Union[SparseValues, dict[str, Union[list[float], list[int]]]]): sparse values of the query vector.
                            Expected to be either a SparseValues object or a dict of the form:
                             {'indices': list[int], 'values': list[float]}, where the lists each have the same length.

        Returns: QueryResponse object which contains the list of the closest vectors as ScoredVector objects,
                 and namespace name.
        rP   Nr   r   r   rQ   r   r   r   r   r   rS   r   r   )	r   r   rQ   r   r   r   r   r   rP   F)_check_typer   r_   )ra   r`   r   r   rd   re   r+   rf   rg   rh   r   rj   rk   rl   r=   r   r   )rK   r   r   rQ   r   r   r   r   r   ru   rx   rP   r   ry   rz   r{   rj   r   r   s                      rL   queryzGRPCIndex.query  sa   n **Y-!bn !HII! 4V < $/55mDM22v&2J ),e$}-%~6')9:$m4	I #/Y/G KKOODIIOO,B,BGU\O]M)3M5)I]1%}F%+? 
 *5 *#-!1+* *&H& (e>N rN   c	                   |t        |      dk(  rt        d      t        |      dk(  rt        d      ||nd}
t        |
|      }t        |      }|D cg c]1  } | j                  j
                  | j                  f|||
||||d|	3 }}t        t        t           |      }t        |      D ]1  }|j                         \  }}t        |      }|j                  |       3 |j                         }|S c c}w )Nr   z(At least one namespace must be specifiedzQuery vector must not be empty
   )r   metric)r   rQ   r   r   r   r   r   )ro   r`   r;   setthreadpool_executorsubmitr   r   r   r   r   r   r   add_resultsget_results)rK   r   
namespacesr   r   r   r   r   r   rx   overall_topk
aggregatortarget_namespacesnsfuturesonly_futuresr   proto_response_json_responsefinal_resultss                        rL   query_namespaceszGRPCIndex.query_namespaces  s%    ZA!5GHHv;!=>> % 1ur+,vN

O (
  ,D$$++
"-!1+
 

 
 HV,g6$\2 	2H ( 1NA2>BM""=1		2 #..0/
s   6C7c	           
        ||t        d      ||t        d      |t        |      }
nd}
|t        |      }nd}|	j                  dd      }t        j                  |      }| j                  d|fd|fd|
fd|fd	|fd
|fd|fg      }t        di |}|re| j                  j                  | j                  j                  j                  ||      }t        |t              r|d   n|}t        ||t              S | j                  j                  | j                  j                  ||      \  }}t        ||      S )a  
        The Update operation updates vectors in a namespace.

        This method supports two update modes:

        1. **Single vector update by ID**: Provide `id` to update a specific vector.
           - Updates the vector with the given ID
           - If `values` is included, it will overwrite the previous vector values
           - If `set_metadata` is included, the metadata will be merged with existing metadata on the vector.
             Fields specified in `set_metadata` will overwrite existing fields with the same key, while
             fields not in `set_metadata` will remain unchanged.

        2. **Bulk update by metadata filter**: Provide `filter` to update all vectors matching the filter criteria.
           - Updates all vectors in the namespace that match the filter expression
           - Useful for updating metadata across multiple vectors at once
           - If `set_metadata` is included, the metadata will be merged with existing metadata on each vector.
             Fields specified in `set_metadata` will overwrite existing fields with the same key, while
             fields not in `set_metadata` will remain unchanged.
           - The response includes `matched_records` indicating how many vectors were updated

        Either `id` or `filter` must be provided (but not both in the same call).

        Examples:

        **Single vector update by ID:**

        .. code-block:: python

            >>> # Update vector values
            >>> index.update(id='id1', values=[1, 2, 3], namespace='my_namespace')
            >>> # Update vector metadata
            >>> index.update(id='id1', set_metadata={'key': 'value'}, namespace='my_namespace', async_req=True)
            >>> # Update vector values and sparse values
            >>> index.update(id='id1', values=[1, 2, 3], sparse_values={'indices': [1, 2], 'values': [0.2, 0.4]},
            >>>              namespace='my_namespace')
            >>> index.update(id='id1', values=[1, 2, 3], sparse_values=GRPCSparseValues(indices=[1, 2], values=[0.2, 0.4]),
            >>>              namespace='my_namespace')

        **Bulk update by metadata filter:**

        .. code-block:: python

            >>> # Update metadata for all vectors matching the filter
            >>> response = index.update(set_metadata={'status': 'active'}, filter={'genre': {'$eq': 'drama'}},
            >>>                        namespace='my_namespace')
            >>> print(f"Updated {response.matched_records} vectors")
            >>> # Preview how many vectors would be updated (dry run)
            >>> response = index.update(set_metadata={'status': 'active'}, filter={'genre': {'$eq': 'drama'}},
            >>>                        namespace='my_namespace', dry_run=True)
            >>> print(f"Would update {response.matched_records} vectors")

        Args:
            id (str): Vector's unique id. Required for single vector updates. Must not be provided when using filter. [optional]
            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[str, float, int, bool, list[int], list[float], list[str]]]]):
                Metadata to merge with existing metadata on the vector(s). Fields specified will overwrite
                existing fields with the same key, while fields not specified will remain unchanged. [optional]
            namespace (str): Namespace name where to update the vector(s). [optional]
            sparse_values: (dict[str, Union[list[float], list[int]]]): Sparse values to update for the vector.
                           Expected to be either a GRPCSparseValues object or a dict of the form:
                           {'indices': list[int], 'values': list[float]} where the lists each have the same length. [optional]
            filter (dict[str, Union[str, float, int, bool, List, dict]]): A metadata filter expression.
                    When provided, updates all vectors in the namespace that match the filter criteria.
                    See `metadata filtering <https://www.pinecone.io/docs/metadata-filtering/>_`.
                    Must not be provided when using id. Either `id` or `filter` must be provided. [optional]
            dry_run (bool): If `True`, return the number of records that match the `filter` without executing
                    the update. Only meaningful when using `filter` (not with `id`). Useful for previewing
                    the impact of a bulk update before applying changes. Defaults to `False`. [optional]

        Returns:
            UpdateResponse or PineconeGrpcFuture: When using filter-based updates, the UpdateResponse includes
            `matched_records` indicating the number of vectors that were updated (or would be updated if
            `dry_run=True`). If `async_req=True`, returns a PineconeGrpcFuture object instead.
        Nz;Either 'id' or 'filter' must be provided to update vectors.zCannot provide both 'id' and 'filter' in the same update call. Use 'id' for single vector updates or 'filter' for bulk updates.rP   r   valuesset_metadatarQ   sparse_valuesr   dry_runrS   r   rT   r   r_   )r`   r   ra   r   rd   re   r.   rf   rg   rh   Updaterj   rk   rl   r=   r   )rK   r   ru   r   r   rQ   r   r   r   rx   set_metadata_structr   rP   ry   rz   r{   rj   r   r   s                      rL   rq   zGRPCIndex.update  sp   r :&.Z[[>f0 R  #"6|"D"&08M M**Y-+11-@..r
6"!45i( -0=)G$

	  ,), KKOODII,<,<,C,CWV]O^M)3M5)I]1%}F%<Q  *.9I9I7\c)d&H&(DTUUrN   c                   | j                  d|fd|fd|fd|fg      }t        di ||}|j                  dd      }| j                  j	                  | j
                  j                  ||      \  }	}
|	j                  r:|	j                  j                  dk7  r!t        |	j                  j                  	      }nd}t        |	j                  |	j                  |
      S )a  
        The list_paginated operation finds vectors based on an id prefix within a single namespace.
        It returns matching ids in a paginated form, with a pagination token to fetch the next page of results.
        This id list can then be passed to fetch or delete operations, depending on your use case.

        Consider using the ``list`` method to avoid having to handle pagination tokens manually.

        Examples:

        .. code-block:: python

            >>> results = index.list_paginated(prefix='99', limit=5, namespace='my_namespace')
            >>> [v.id for v in results.vectors]
            ['99', '990', '991', '992', '993']
            >>> results.pagination.next
            eyJza2lwX3Bhc3QiOiI5OTMiLCJwcmVmaXgiOiI5OSJ9
            >>> next_results = index.list_paginated(prefix='99', limit=5, namespace='my_namespace', pagination_token=results.pagination.next)

        Args:
            prefix (Optional[str]): The id prefix to match. If unspecified, an empty string prefix will
                                    be used with the effect of listing all ids in a namespace [optional]
            limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional]
            pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned
                in the response if additional results are available. [optional]
            namespace (Optional[str]): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional]

        Returns: SimpleListResponse object which contains the list of ids, the namespace name, pagination information, and usage showing the number of read_units consumed.
        prefixr   rQ   r   rP   NrS    )next)rQ   rR   
paginationr_   )re   r/   ra   rf   rg   rh   r   r   r   r&   SimpleListResponserQ   rR   )rK   r   r   r   rQ   rx   ry   rz   rP   r   r   r   s               rL   list_paginatedzGRPCIndex.list_paginated9  s    H ..6"% i(#%56	
	 4	4V4**Y-kkoodiinngwoO!8#6#6#;#;r#A#)<)<)A)ABJJ!(((2B2Bz
 	
rN   c              +    K   d}|s	  | j                   di |}t        |j                        dkD  r&|j                  D cg c]  }|j                   c} |j
                  r>|j
                  j                  r(|j                  d|j
                  j                  i       nd}|syy# t        $ r}|d}~ww xY wc c}w w)a  
        The list operation accepts all of the same arguments as list_paginated, and returns a generator that yields
        a list of the matching vector ids in each page of results. It automatically handles pagination tokens on your
        behalf.

        Examples:

        .. code-block:: python

            >>> for ids in index.list(prefix='99', limit=5, namespace='my_namespace'):
            >>>     print(ids)
            ['99', '990', '991', '992', '993']
            ['994', '995', '996', '997', '998']
            ['999']

        Args:
            prefix (Optional[str]): The id prefix to match. If unspecified, an empty string prefix will
                                    be used with the effect of listing all ids in a namespace [optional]
            limit (Optional[int]): The maximum number of ids to return. If unspecified, the server will use a default value. [optional]
            pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned
                in the response if additional results are available. [optional]
            namespace (Optional[str]): The namespace to fetch vectors from. If not specified, the default namespace is used. [optional]
        FNr   r   Tr_   )r   	Exceptionro   rR   r   r   r   rq   )rK   rx   doner   evs         rL   rb   zGRPCIndex.listr  s     0 -$--77 7??#a'%,__5qtt55!!g&8&8&=&=173E3E3J3JKL    6s:   CB) &C B<AC'C)	B92B44B99Cc                   |t        |      }nd}| j                  d|fg      }|j                  dd      }t        di |}| j                  j                  | j                  j                  ||      \  }}t        |      S )a  
        The DescribeIndexStats operation returns statistics about the index's contents.
        For example: The vector count per namespace and the number of dimensions.

        Examples:

        .. code-block:: python

            >>> index.describe_index_stats()
            >>> index.describe_index_stats(filter={'key': 'value'})

        Args:
            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 `metadata filtering <https://www.pinecone.io/docs/metadata-filtering/>_` [optional]

        Returns: DescribeIndexStatsResponse object which contains stats about the index.
        Nr   rP   rS   r_   )	r   re   ra   r0   rf   rg   rh   DescribeIndexStatsr   )	rK   r   rx   r   ry   rP   rz   r   r   s	            rL   describe_index_statszGRPCIndex.describe_index_stats  s    * 08M M..=0I/JK	**Y-+8i8kkoodii&B&BGU\o]!#H--rN   c                   |j                  dd      }d}|t        |t              rni }|j                  di       j	                         D ]<  \  }}	t        |	t              r"|	j                  dd      }
t        |
      ||<   8|	||<   > t        |      }n|}d|i}|||d	<   t        di |}|re| j                  j                  | j                  j                  j                  ||
      }t        |t              r|d   n|}t        ||t              S | j                  j                  | j                  j                  ||
      \  }}t        ||      S )aT  
        The create_namespace operation creates a namespace in a serverless index.

        Examples:

        .. code-block:: python

            >>> index.create_namespace(name='my_namespace')

            >>> # Create namespace asynchronously
            >>> future = index.create_namespace(name='my_namespace', async_req=True)
            >>> namespace = future.result()

        Args:
            name (str): The name of the namespace to create.
            schema (Optional[dict[str, Any]]): Optional schema configuration for the namespace as a dictionary. [optional]
            async_req (bool): If True, the create_namespace operation will be performed asynchronously. [optional]

        Returns: NamespaceDescription object which contains information about the created namespace, or a PineconeGrpcFuture object if async_req is True.
        rP   Nfields
filterableF)r   )r   nameschemarS   r   rT   r   r_   )ra   rk   dictgetitemsr7   r6   r5   rf   rg   rh   CreateNamespacerj   rl   r=   r   )rK   r   r   ru   rx   rP   metadata_schemar   keyvaluer   request_kwargsrz   r{   rj   r   r   s                    rL   create_namespacezGRPCIndex.create_namespace  s`   0 **Y- &$'"(**Xr":"@"@"B ,JC!%.%*YY|U%C
&=&Ts ',s, #1"? #)*0$&'6N8$(:>: KKOO		))00'7 , M *4M5)I]1%}F%<W  &*[[__II%%w &5 &
"" +8FVWWrN   c                    |j                  dd      }t        |      }| j                  j                  | j                  j
                  ||      \  }}t        ||      S )a  
        The describe_namespace operation returns information about a specific namespace,
        including the total number of vectors in the namespace.

        Examples:

        .. code-block:: python

            >>> index.describe_namespace(namespace='my_namespace')

        Args:
            namespace (str): The namespace to describe.

        Returns: NamespaceDescription object which contains information about the namespace.
        rP   NrQ   rS   r   )ra   r2   rf   rg   rh   DescribeNamespacer   rK   rQ   rx   rP   rz   r   r   s          rL   describe_namespacezGRPCIndex.describe_namespace  s\    " **Y-*Y?%)[[__II''' &5 &
"" +8FVWWrN   c                    |j                  dd      }t        |      }| j                  j                  | j                  j
                  ||      \  }}t        ||      S )a  
        The delete_namespace operation deletes a namespace from an index.
        This operation is irreversible and will permanently delete all data in the namespace.

        Examples:

        .. code-block:: python

            >>> index.delete_namespace(namespace='my_namespace')

        Args:
            namespace (str): The namespace to delete.

        Returns: Empty dictionary indicating successful deletion.
        rP   Nr   rS   r   )ra   r3   rf   rg   rh   DeleteNamespacer   r   s          rL   delete_namespacezGRPCIndex.delete_namespace  s\    " **Y-(9=%)[[__II%%w &5 &
"" %X@PQQrN   c                    | j                  d|fd|fg      }|j                  dd      }t        di ||}| j                  j	                  | j
                  j                  ||      \  }}t        |      S )ap  
        The list_namespaces_paginated operation returns a list of all namespaces in a serverless index.
        It returns namespaces in a paginated form, with a pagination token to fetch the next page of results.

        Examples:

        .. code-block:: python

            >>> results = index.list_namespaces_paginated(limit=10)
            >>> [ns.name for ns in results.namespaces]
            ['namespace1', 'namespace2', 'namespace3']
            >>> results.pagination.next
            eyJza2lwX3Bhc3QiOiI5OTMiLCJwcmVmaXgiOiI5OSJ9
            >>> next_results = index.list_namespaces_paginated(limit=10, pagination_token=results.pagination.next)

        Args:
            limit (Optional[int]): The maximum number of namespaces to return. If unspecified, the server will use a default value. [optional]
            pagination_token (Optional[str]): A token needed to fetch the next page of results. This token is returned
                in the response if additional results are available. [optional]

        Returns: ListNamespacesResponse object which contains the list of namespaces and pagination information.
        r   r   rP   NrS   r_   )re   ra   r4   rf   rg   rh   ListNamespacesr   )	rK   r   r   rx   ry   rP   rz   r   r   s	            rL   list_namespaces_paginatedz#GRPCIndex.list_namespaces_paginated*  s~    4 ..u 24DEF
	 **Y-'>)>v>kkoodii&>&>QXoY!-h77rN   c              +  v  K   d}|s	  | j                   dd|i|}|j                  r-t        |j                        dkD  r|j                  D ]  }|  |j                  r>|j                  j
                  r(|j                  d|j                  j
                  i       nd}|syy# t        $ r}|d}~ww xY ww)a&  
        The list_namespaces operation accepts all of the same arguments as list_namespaces_paginated, and returns a generator that yields
        each namespace. It automatically handles pagination tokens on your behalf.

        Args:
            limit (Optional[int]): The maximum number of namespaces to fetch in each network call. If unspecified, the server will use a default value. [optional]

        Returns:
            Returns a generator that yields each namespace. It automatically handles pagination tokens on your behalf so you can
            easily iterate over all results. The ``list_namespaces`` method accepts all of the same arguments as list_namespaces_paginated

        Examples:

        .. code-block:: python

            >>> for namespace in index.list_namespaces():
            >>>     print(namespace.name)
            namespace1
            namespace2
            namespace3

        You can convert the generator into a list by wrapping the generator in a call to the built-in ``list`` function:

        .. code-block:: python

            namespaces = list(index.list_namespaces())

        You should be cautious with this approach because it will fetch all namespaces at once, which could be a large number
        of network calls and a lot of memory to hold the results.
        Fr   Nr   r   Tr_   )r   r   r   ro   r   r   rq   )rK   r   rx   r   r   r   rQ   s          rL   list_namespaceszGRPCIndex.list_namespacesL  s     @ 8$88OuOO !!c'*<*<&=&A!(!3!3 $I#O$ !!g&8&8&=&=173E3E3J3JKL   s.   B9B& BB9$B9&	B6/B11B66B9c                @    | D ci c]  \  }}|	|| c}}S c c}}w Nr_   )argsarg_namevals      rL   re   zGRPCIndex._parse_non_empty_args|  s"    37K-(C3?#KKKs   
)returnz'Type[VectorServiceStub]')FNNT)rR   zKlist[Vector] | list[GRPCVector] | list[VectorTuple] | list[VectorTypedDict]ru   boolrQ   
str | Nonerv   
int | Nonerw   r	  r  z#UpsertResponse | PineconeGrpcFuture)rR   zlist[GRPCVector]rQ   r
  rP   r  r  r"   )Ni  TT)r   r   rQ   r
  rv   rn   r   r	  rw   r	  r  r"   )r   r   rv   rn   r  zIterator[list[dict[str, Any]]])NNNNF)r   list[str] | Noner   bool | NonerQ   r
  r   FilterTypedDict | Noneru   r	  r  z#dict[str, Any] | PineconeGrpcFuture)NF)r   r  rQ   r
  ru   r  r  z"FetchResponse | PineconeGrpcFuture)NNNF)r   rC   rQ   r
  r   r  r   r
  ru   r  r  z,FetchByMetadataResponse | PineconeGrpcFuture)NNNNNNNN)r   list[float] | Noner   r
  rQ   r
  r   r  r   r  r   r  r   r  r   >SparseValues | GRPCSparseValues | SparseVectorTypedDict | Noner  z0tuple[ProtoQueryResponse, dict[str, str] | None])	NNNNNNNNF)r   r  r   r
  rQ   r
  r   r  r   r  r   r  r   r  r   r  ru   r  r  z$'QueryResponse' | PineconeGrpcFuture)NNNNN)r   zlist[float]r   z	list[str]r   z,Literal['cosine', 'euclidean', 'dotproduct']r   r  r   r  r   r  r   r  r   /GRPCSparseValues | SparseVectorTypedDict | Noner  r:   )NFNNNNNN)r   r
  ru   r	  r   r  r   zVectorMetadataTypedDict | NonerQ   r
  r   r  r   r  r   r  r  z#UpdateResponse | PineconeGrpcFuture)NNNN)
r   r
  r   r  r   r
  rQ   r
  r  r   )r  zIterator[list[str]]r  )r   r  r  DescribeIndexStatsResponse)r   strr   zdict[str, Any] | Noneru   r	  r  z)NamespaceDescription | PineconeGrpcFuture)rQ   r  r  r   )rQ   r  r  dict[str, Any])NN)r   r  r   r
  r  r   )r   r  )r  zList[tuple[str, Any]]r  r  )__name__
__module____qualname____doc__propertyrM   r   rm   r   staticmethodr   r   r   r   r   r   r   rq   r   rb   r   r   r   r   r   r   r  re   r_   rN   rL   rE   rE   [   s2   F! !   $!%"t[\t[ t[ 	t[
 t[ t[ 
-t[lR'R4>RISR	R !%#'"B[B[ B[ 	B[
 !B[ B[ 
B[H   !%"& $)-IVIV  IV 	IV
 'IV IV 
-IV\ !%!&	(U(U (U 	(U 
,(UZ !% '+!&JaJa Ja 	Ja
 %Ja Ja 
6Ja\ &* $ )-&*(,Z^-*"-* -* 	-*
 -* '-* $-* &-* X-* 
:-*b &* $ )-&*(,Z^!&h"h h 	h
 h 'h $h &h Xh h 
.h^ !)-&*(,KO,, , =	,
 , ', $, &, I, 
 ,` %)7; $KO)-#BVBV BV #	BV
 5BV BV IBV 'BV BV 
-BVL " '+ $7
7
 7
 %	7

 7
 
7
r%P 04.,.	#.@ QV>X>X!6>XJN>X	2>X >X@ X X. R R. GK88:D8	8 8B - -^ L LrN   rE   )]
__future__r   loggingtypingr   r   r   r   r   r	   r
   pinecone.utils.tqdmr   pinecone.utilsr   concurrent.futuresr   r   utilsr   r   r   r   r   r   r   r   r   r   r   vector_factory_grpcr   sparse_values_factoryr   $pinecone.core.openapi.db_data.modelsr   r  r   r   rr   r    r!   r"   r#   r$   (pinecone.db_control.models.list_responser%   r   r&   -pinecone.core.grpc.protos.db_data_2025_10_pb2r'   rF   r(   rG   ProtoQueryResponser)   r*   r+   r,   r-   r.   r/   r0   r1   rH   r2   r3   r4   r5   r6   r7   2pinecone.core.grpc.protos.db_data_2025_10_pb2_grpcr9   pinecone)pinecone.db_data.query_results_aggregatorr:   r;   baser<   rj   r=   r>   db_data.typesr@   rA   rB   rC   rD   __all__	getLoggerr  _loggerrE   r_   rN   rL   <module>r0     s    "  N N N % ) 3    3 6 
  d    ( Q ) d  &  '

H
% cL cLrN   