
    IZj                      d dl mZ d dlZd dlmZmZ d dlmZ d dlm	Z	 d dl
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 d dlZd dlZd dlZd dlmZ d dlZd dl m!Z! d d	l"m#Z# d d
l$m%Z% d dl&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 erZd dl9Z9d dl:Z:d dl;Z<ddl=m>Z? ddl=m@ZA ddl=mBZB ddl=mCZD ddl=mEZF ddl=mGZH ddlImJZJ ddlmKZK ddlLmMZM e9jN        dk    rd dlmOZO nd dl mOZO  ed d!"          ZPd^d'ZQ G d( d)ejR                  ZS G d* d+eTe          ZU G d, d-eTe          ZV G d. d/eTe          ZWejX        jY         G d0 d1e                      ZZejX        jY         G d2 d3eZ                      Z[ejX        jY         G d4 d5eZ                      Z\ejX        jY         G d6 d7eZ                      Z]ejX        jY         G d8 d9eZ                      Z^ejX        jY         G d: d;eZ                      Z_ G d< d=ejR                  Z` G d> d?ejR                  ZC G d@ dAe          Za G dB dCea          Zb G dD dEea          Zc G dF dGea          Zd G dH dIea          Ze G dJ dKef          Zg G dL dMeg          Zh G dN dOeh          Zi G dP dQeh          Zj G dR dS          Zk G dT dUehek          Zl G dV dWehek          Zm G dX dYeg          Zn G dZ d[ef          Zo G d\ d]eo          ZpdS )_    )annotationsN)ABCabstractmethod)ThreadPoolExecutor)	timedelta)Enum)
TYPE_CHECKINGAnyDictListLiteralOptionalTupleTypeTypeVarUnion)	Annotatedfts_query_to_json)LOOP)PYDANTIC_VERSION   )__version__)AsyncRecordBatchReader)pandas)Expr)Reranker)RRFReranker)check_reranker_result)flatten_columns)FTSQuery)HybridQuery)PyQueryRequest)Query)	TakeQuery)VectorQuery)VEC)
LanceModel)Table)      )SelfTr(   )boundvalr
   return?Union[List[float], List[List[float]], pa.Array, List[pa.Array]]c                   t          | t                    r+t          |           dk    rt          d          | d         }n&t          | t                    rt          d          | }t          |t
          j                  r| S t          |t                    r?t          |          dk    rt          d          t          |d         t                    r| S t          |t                    r| S d S )Nr   z%Vector query must be a non-empty listzBVector query must be a list of floats or a list of lists of floats)
isinstancelistlen
ValueErrorfloatpaArray)r/   samples     Y/Users/jameslopez/projects/MentorCore/.venv/lib/python3.11/site-packages/lancedb/query.pyensure_vector_queryr<   E   s     #t 	s88q==DEEEQc5!! 	T   &"(## 
&$ v;;!DEEEfQi'' 	J&%   
     c                  6    e Zd ZU ded<   dZded<   dZded<   dS )	ColumnOrderingstrcolumn_nameTbool	ascendingFnulls_firstN)__name__
__module____qualname____annotations__rC   rD    r=   r;   r?   r?   `   s@         IKr=   r?   c                  "    e Zd ZdZdZdZdZdZdS )FullTextQueryTypematchmatch_phraseboostmulti_matchbooleanN)rE   rF   rG   MATCHMATCH_PHRASEBOOSTMULTI_MATCHBOOLEANrI   r=   r;   rK   rK   f   s'        E!LEKGGGr=   rK   c                      e Zd ZdZdZdS )FullTextOperatorANDORN)rE   rF   rG   rX   rY   rI   r=   r;   rW   rW   n   s        
C	BBBr=   rW   c                      e Zd ZdZdZdZdS )OccurSHOULDMUSTMUST_NOTN)rE   rF   rG   r\   r]   r^   rI   r=   r;   r[   r[   s   s        FDHHHr=   r[   c                  >    e Zd Zedd            ZddZddZdd	Zd
S )FullTextQueryr0   rK   c                    dS )z
        Get the query type of the query.

        Returns
        -------
        str
            The type of the query.
        NrI   selfs    r;   
query_typezFullTextQuery.query_type{   s	     	r=   r@   c                     t          |           S )a  
        Convert the query to a JSON string.

        Returns
        -------
        str
            A JSON string representation of the query.

        Examples
        --------
        >>> from lancedb.query import MatchQuery
        >>> query = MatchQuery("puppy", "text", fuzziness=2)
        >>> query.to_json()
        '{"match":{"column":"text","terms":"puppy","boost":1.0,"fuzziness":2,"max_expansions":50,"operator":"Or","prefix_length":0}}'
        r   rb   s    r;   to_jsonzFullTextQuery.to_json   s      !&&&r=   other'FullTextQuery'c                T    t          t          j        | ft          j        |fg          S )a)  
        Combine two queries with a logical AND operation.

        Parameters
        ----------
        other : FullTextQuery
            The other query to combine with.

        Returns
        -------
        FullTextQuery
            A new query that combines both queries with AND.
        )BooleanQueryr[   r]   rc   rg   s     r;   __and__zFullTextQuery.__and__   s%     ej$/%*e1DEFFFr=   c                T    t          t          j        | ft          j        |fg          S )a'  
        Combine two queries with a logical OR operation.

        Parameters
        ----------
        other : FullTextQuery
            The other query to combine with.

        Returns
        -------
        FullTextQuery
            A new query that combines both queries with OR.
        )rj   r[   r\   rk   s     r;   __or__zFullTextQuery.__or__   s%     elD1EL%3HIJJJr=   Nr0   rK   r0   r@   )rg   rh   r0   rh   )rE   rF   rG   r   rd   rf   rl   rn   rI   r=   r;   r`   r`   y   sx        	 	 	 ^	' ' ' '$G G G G K K K K K Kr=   r`   c                      e Zd ZU dZded<   ded<    ej        dd          Zded	<    ej        d
d          Zded<    ej        dd          Z	ded<    ej        e
j        d          Zded<    ej        d
d          Zded<   ddZdS )
MatchQuerya  
    Match query for full-text search.

    Parameters
    ----------
    query : str
        The query string to match against.
    column : str
        The name of the column to match against.
    boost : float, default 1.0
        The boost factor for the query.
        The score of each matching document is multiplied by this value.
    fuzziness : int, optional
        The maximum edit distance for each term in the match query.
        Defaults to 0 (exact match).
        If None, fuzziness is applied automatically by the rules:
            - 0 for terms with length <= 2
            - 1 for terms with length <= 5
            - 2 for terms with length > 5
    max_expansions : int, optional
        The maximum number of terms to consider for fuzzy matching.
        Defaults to 50.
    operator : FullTextOperator, default OR
        The operator to use for combining the query results.
        Can be either `AND` or `OR`.
        If `AND`, all terms in the query must match.
        If `OR`, at least one term in the query must match.
    prefix_length : int, optional
        The number of beginning characters being unchanged for fuzzy matching.
        This is useful to achieve prefix matching.
    r@   querycolumng      ?Tkw_onlyr7   rN   r   int	fuzziness2   max_expansionsrW   operatorprefix_lengthr0   rK   c                    t           j        S N)rK   rQ   rb   s    r;   rd   zMatchQuery.query_type        &&r=   Nro   )rE   rF   rG   __doc__rH   pydanticFieldrN   rx   rz   rW   rY   r{   r|   rd   rI   r=   r;   rr   rr      s          @ JJJKKK!8>#t444E4444#X^At444I4444((.T:::N::::!/0@0CT!R!R!RHRRRR'4888M8888' ' ' ' ' 'r=   rr   c                  ^    e Zd ZU dZded<   ded<    ej        dd          Zded	<   ddZdS )PhraseQueryz
    Phrase query for full-text search.

    Parameters
    ----------
    query : str
        The query string to match against.
    column : str
        The name of the column to match against.
    r@   rs   rt   r   Tru   rw   slopr0   rK   c                    t           j        S r~   )rK   rR   rb   s    r;   rd   zPhraseQuery.query_type   s     --r=   Nro   )	rE   rF   rG   r   rH   r   r   r   rd   rI   r=   r;   r   r      sj         	 	 JJJKKKq$///D////. . . . . .r=   r   c                  ^    e Zd ZU dZded<   ded<    ej        dd          Zded	<   ddZdS )
BoostQuerya  
    Boost query for full-text search.

    Parameters
    ----------
    positive : dict
        The positive query object.
    negative : dict
        The negative query object.
    negative_boost : float, default 0.5
        The boost factor for the negative query.
    r`   positivenegativeg      ?Tru   r7   negative_boostr0   rK   c                    t           j        S r~   )rK   rS   rb   s    r;   rd   zBoostQuery.query_type  r   r=   Nro   )	rE   rF   rG   r   rH   r   r   r   rd   rI   r=   r;   r   r      sp           *HN3===N====' ' ' ' ' 'r=   r   c                      e Zd ZU dZded<   ded<    ej        dd          Zd	ed
<    ej        ej	        d          Z
ded<   ddZdS )MultiMatchQuerya  
    Multi-match query for full-text search.

    Parameters
    ----------
    query : str | list[Query]
        If a string, the query string to match against.
    columns : list[str]
        The list of columns to match against.
    boosts : list[float], optional
        The list of boost factors for each column. If not provided,
        all columns will have the same boost factor.
    operator : FullTextOperator, default OR
        The operator to use for combining the query results.
        Can be either `AND` or `OR`.
        It would be applied to all columns individually.
        For example, if the operator is `AND`,
        then the query "hello world" is equal to
        `match("hello AND world", column1) OR match("hello AND world", column2)`.
    r@   rs   z	list[str]columnsNTru   zOptional[list[float]]boostsrW   r{   r0   rK   c                    t           j        S r~   )rK   rT   rb   s    r;   rd   zMultiMatchQuery.query_type0  s     ,,r=   ro   )rE   rF   rG   r   rH   r   r   r   rW   rY   r{   rd   rI   r=   r;   r   r     s          * JJJ$2HN4$F$F$FFFFFF!/0@0CT!R!R!RHRRRR- - - - - -r=   r   c                  &    e Zd ZU dZded<   ddZdS )	rj   a)  
    Boolean query for full-text search.

    Parameters
    ----------
    queries : list[tuple(Occur, FullTextQuery)]
        The list of queries with their occurrence requirements.
        Each tuple contains an Occur value (MUST, SHOULD, or MUST_NOT)
        and a FullTextQuery to apply.
    z!list[tuple[Occur, FullTextQuery]]queriesr0   rK   c                    t           j        S r~   )rK   rU   rb   s    r;   rd   zBooleanQuery.query_typeC  s     ((r=   Nro   )rE   rF   rG   r   rH   rd   rI   r=   r;   rj   rj   4  sB         	 	 /...) ) ) ) ) )r=   rj   c                  ,    e Zd ZU dZdZded<   ded<   dS )FullTextSearchQueryaM  A LanceDB Full Text Search Query

    Attributes
    ----------
    columns: List[str]
        The columns to search

        If None, then the table should select the column automatically.
    query: str | FullTextQuery
        If a string, it is treated as a MatchQuery.
        If a FullTextQuery object, it is used directly.
    NzOptional[List[str]]r   zUnion[str, FullTextQuery]rs   )rE   rF   rG   r   r   rH   rI   r=   r;   r   r   G  s;           $(G''''$$$$$$r=   r   c                  r   e Zd ZU dZdZded<   dZded<   dZded<   dZd	ed
<   dZ	ded<   dZ
ded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZd	ed<   dZded<   dZd	ed<   dZded<   dZd	ed<   dZded<   ed)d#            Zej        d$k     r G d% d&          ZdS d'd(iZdS )*r$   a  A LanceDB Query

    Queries are constructed by the `Table.search` method.  This class is a
    python representation of the query.  Normally you will not need to interact
    with this class directly.  You can build up a query and execute it using
    collection methods such as `to_batches()`, `to_arrow()`, `to_pandas()`,
    etc.

    However, you can use the `to_query()` method to get the underlying query object.
    This can be useful for serializing a query or using it in a different context.

    Attributes
    ----------
    filter : Optional[str]
        sql filter to refine the query with
    limit : Optional[int]
        The limit on the number of results to return.  If this is a vector or FTS query,
        then this is required.  If this is a plain SQL query, then this is optional.
    offset: Optional[int]
        The offset to start fetching results from

        This is ignored for vector / FTS search (will be None).
    columns : Optional[Union[List[str], Dict[str, str]]]
        which columns to return in the results

        This can be a list of column names or a dictionary.  If it is a dictionary,
        then the keys are the column names and the values are sql expressions to
        use to calculate the result.

        If this is None then all columns are returned.  This can be expensive.
    with_row_id : Optional[bool]
        if True then include the row id in the results
    vector : Optional[Union[List[float], List[List[float]], pa.Array, List[pa.Array]]]
        the vector to search for, if this a vector search or hybrid search.  It will
        be None for full text search and plain SQL filtering.
    vector_column : Optional[str]
        the name of the vector column to use for vector search

        If this is None then a default vector column will be used.
    distance_type : Optional[str]
        the distance type to use for vector search

        This can be l2 (default), cosine and dot.  See [metric definitions][search] for
        more details.

        If this is not a vector search this will be None.
    postfilter : bool
        if True then apply the filter after vector / FTS search.  This is ignored for
        plain SQL filtering.
    nprobes : Optional[int]
        The number of IVF partitions to search.  If this is None then a default
        number of partitions will be used.

        - A higher number makes search more accurate but also slower.

        - See discussion in [Querying an ANN Index][querying-an-ann-index] for
          tuning advice.

        Will be None if this is not a vector search.
    refine_factor : Optional[int]
        Refine the results by reading extra elements and re-ranking them in memory.

        - A higher number makes search more accurate but also slower.

        - See discussion in [Querying an ANN Index][querying-an-ann-index] for
          tuning advice.

        Will be None if this is not a vector search.
    lower_bound : Optional[float]
        The lower bound for distance search

        Only results with a distance greater than or equal to this value
        will be returned.

        This will only be set on vector search.
    upper_bound : Optional[float]
        The upper bound for distance search

        Only results with a distance less than or equal to this value
        will be returned.

        This will only be set on vector search.
    ef : Optional[int]
        The size of the nearest neighbor list maintained during HNSW search

        This will only be set on vector search.
    full_text_query : Optional[Union[str, dict]]
        The full text search query

        This can be a string or a dictionary.  A dictionary will be used to search
        multiple columns.  The keys are the column names and the values are the
        search queries.

        This will only be set on FTS or hybrid queries.
    fast_search: Optional[bool]
        Skip a flat search of unindexed data. This will improve
        search performance but search results will not include unindexed data.

        The default is False
    NOptional[str]vector_columnziAnnotated[Optional[Union[List[float], List[List[float]], pa.Array, List[pa.Array]]], ensure_vector_query]vectorzOptional[Union[str, Expr]]filterOptional[bool]
postfilterzOptional[FullTextSearchQuery]full_text_queryOptional[int]limitdistance_typez7Optional[Union[List[str], Dict[str, Union[str, Expr]]]]r   minimum_nprobesmaximum_nprobesOptional[float]lower_boundupper_boundrefine_factorwith_row_idoffsetfast_searchefbypass_vector_indexOptional[List[ColumnOrdering]]order_byreqr#   r0   r,   c                0    |             }|j         |_         |j        |_        |j        |_        |j        |_        |j        |_        |j        |_        |j        |_	        |j
        |_        |j        |_        |j        |_        |j        |_        |j        |_        |j        |_        |j        |_        |j        |_        |j        |_        |j        |_        |j        d |j        D             |_        |j        t-          d |j                  |_        |S )Nc                &    g | ]}t          d i |S rI   )r?   .0os     r;   
<listcomp>z$Query.from_inner.<locals>.<listcomp>  s&    HHHan11q11HHHr=   )r   rs   )r   r   r   full_text_searchr   selectr   r   rt   r   query_vectorr   r   r   r   r   r   r   r   r   r   r   r   )clsr   rs   s      r;   
from_innerzQuery.from_inner  s   izz # 4
O!j'!/ # 3 # 3OO6!/$'$;!><#HH3<HHHEN+$7*% % %E! r=      c                      e Zd ZdZdS )Query.ConfigTN)rE   rF   rG   arbitrary_types_allowedrI   r=   r;   Configr   %  s        &*###r=   r   r   T)r   r#   r0   r,   )rE   rF   rG   r   r   rH   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   classmethodr   r   majorr   model_configrI   r=   r;   r$   r$   Y  s        c cL $(M'''' 	      *.F---- "&J%%%% 6:O9999  E $(M'''' HLGKKKK
 &*O)))) &*O)))) $(K'''' $(K'''' $(M'''' #'K&&&& !F     #'K&&&& B +/..../3H3333   [< !!	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 248r=   r$   c                     e Zd ZdZe	 	 	 dSdTd            Zed             Zed             ZdUdZ e	j
        dded          dVd            Z	 dWdddXd!ZedddYd#            Ze	 dWdddZd'            Zddd[d)Zddd\d-Zddd]d/Zd^d2Zd_d5Zd`d8Zdadbd=Zdcd?ZdddedCZdfdFZdgdGZdhdJZdidMZedjdP            ZedkdR            ZdS )lLanceQueryBuilderzAn abstract query builder. Subclasses are defined for vector search,
    full text search, hybrid, and plain SQL filtering.
    Ntable'Table'rs   :Optional[Union[np.ndarray, str, 'PIL.Image.Image', Tuple]]rd   r@   vector_column_nameordering_field_namer   fts_columnsOptional[Union[str, List[str]]]r   rB   r0   r,   c                   |!ddl }|                    dt          d           |dk    rt          ||||          S |t	          |          S t          |t                    r|nd}	|                     ||||          \  }}|dk    rt          ||||          S t          |t          t          f          rt          |||||          S t          |t                    r!t          j        |t          j        	          }nYt          |t          j                  r |                    t          j                  }nt!          d
t#          |                     t%          ||||	|          S )a  
        Create a query builder based on the given query and query type.

        Parameters
        ----------
        table: Table
            The table to query.
        query: Optional[Union[np.ndarray, str, "PIL.Image.Image", Tuple]]
            The query to use. If None, an empty query builder is returned
            which performs simple SQL filtering.
        query_type: str
            The type of query to perform. One of "vector", "fts", "hybrid", or "auto".
            If "auto", the query type is inferred based on the query.
        vector_column_name: str
            The name of the vector column to use for vector search.
        ordering_field_name: Optional[str]
            .. deprecated:: 0.27.0
                Use ``order_by()`` method instead.
        fts_columns: Optional[Union[str, List[str]]]
            The columns to search in for full text search.
        fast_search: bool
            Skip flat search of unindexed data.
        Nr   zBordering_field_name is deprecated, use .order_by() method instead.r   )
stacklevelhybridr   )r   r   r   )dtypezUnsupported query type: )warningswarnDeprecationWarningLanceHybridQueryBuilderLanceEmptyQueryBuilderr3   r@   _resolve_queryr`   LanceFtsQueryBuilderr4   nparrayfloat32ndarrayastype	TypeErrortypeLanceVectorQueryBuilder)
r   r   rs   rd   r   r   r   r   r   	str_querys
             r;   createzLanceQueryBuilder.create0  s   D *OOOMMT"     !!*u0k    =)%000 (s33=EE	  ..5*&8
 
z !!*u0k    ec=122 	'$7''    eT"" 	FHU"*555EErz** 	FLL,,EEDtE{{DDEEE&5,i
 
 	
r=   c                   |dk    r?t          |t          t          f          st          dt	          |                     ||fS |dk    r|                     |||          }||fS |dk    rit          |t          t          j        f          r|dfS |j	        
                    |          }|$|j                            |          d         }|dfS |dfS t          d|           )Nftsz/'fts' query must be a string or FullTextQuery: r   autor   z8Invalid query_type, must be 'vector', 'fts', or 'auto': )r3   r@   r`   r   r   _query_to_vectorr4   r   r   embedding_functionsgetfunction#compute_query_embeddings_with_retryr6   )r   r   rs   rd   r   confs         r;   r   z LanceQueryBuilder._resolve_query  s    ec=%9:: Sd5kkSS   *$$8##((7IJJE*$$6!!%$
!344 (h&0445GHH# MMMeTTUVWE (?* %<'W:WW  r=   c                    t          |t          t          j        f          r|S |j                            |          }| |j                            |          d         S d| }t          |          )Nr   zNo embedding function for )	r3   r4   r   r   r   r   r   r   r6   )r   r   rs   r   r   msgs         r;   r   z"LanceQueryBuilder._query_to_vector  sr    edBJ/00 	L(,,-?@@=DDUKKANNC/ACCCS//!r=   c                    || _         d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _	        d | _
        d | _        d S r~   )_table_limit_offset_columns_where_postfilter_with_row_id_vector_text_ef_bypass_vector_index	_order_by)rc   r   s     r;   __init__zLanceQueryBuilder.__init__  s]     
$(!r=   z0.3.1z0.4.0zUse to_pandas() instead)deprecated_in
removed_incurrent_versiondetails'pd.DataFrame'c                *    |                                  S )ae  
        *Deprecated alias for `to_pandas()`. Please use `to_pandas()` instead.*

        Execute the query and return the results as a pandas DataFrame.
        In addition to the selected columns, LanceDB also returns a vector
        and also the "_distance" column which is the distance between the query
        vector and the returned vector.
        )	to_pandasrb   s    r;   to_dfzLanceQueryBuilder.to_df  s     ~~r=   timeoutflattenOptional[Union[int, bool]]r  Optional[timedelta]c               d    t          |                     |          |          } |j        di |S )aT  
        Execute the query and return the results as a pandas DataFrame.
        In addition to the selected columns, LanceDB also returns a vector
        and also the "_distance" column which is the distance between the query
        vector and the returned vector.

        Parameters
        ----------
        flatten: Optional[Union[int, bool]]
            If flatten is True, flatten all nested columns.
            If flatten is an integer, flatten the nested columns up to the
            specified depth.
            If unspecified, do not flatten the nested columns.
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If None, wait indefinitely.
        **kwargs
            Forwarded to pyarrow.Table.to_pandas after query execution and
            optional flattening.
        r  rI   r    to_arrowr  )rc   r  r  kwargstbls        r;   r  zLanceQueryBuilder.to_pandas  s9    6 dmmGm<<gFFs}&&v&&&r=   pa.Tablec                   t           )(  
        Execute the query and return the results as an
        [Apache Arrow Table](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table).

        In addition to the selected columns, LanceDB also returns a vector
        and also the "_distance" column which is the distance between the query
        vector and the returned vectors.

        Parameters
        ----------
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If None, wait indefinitely.
        NotImplementedErrorrc   r  s     r;   r  zLanceQueryBuilder.to_arrow  s
      "!r=   
batch_sizer   pa.RecordBatchReaderc                  t           )a  
        Execute the query and return the results as a pyarrow
        [RecordBatchReader](https://arrow.apache.org/docs/python/generated/pyarrow.RecordBatchReader.html)

        Parameters
        ----------
        batch_size: int
            The maximum number of selected records in a RecordBatch object.
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If None, wait indefinitely.
        r  rc   r  r  s      r;   
to_batcheszLanceQueryBuilder.to_batches  s
    ( "!r=   
List[dict]c               R    |                      |                                          S )a  
        Execute the query and return the results as a list of dictionaries.

        Each list entry is a dictionary with the selected column names as keys,
        or all table columns if `select` is not called. The vector and the "_distance"
        fields are returned whether or not they're explicitly selected.

        Parameters
        ----------
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If None, wait indefinitely.
        r  r  	to_pylistr  s     r;   to_listzLanceQueryBuilder.to_list  s$     }}W}--77999r=   modeltype[T]list[T]c               l    fd|                      |                                          D             S )al  Return the table as a list of pydantic models.

        Parameters
        ----------
        model: Type[LanceModel]
            The pydantic model to use.
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If None, wait indefinitely.

        Returns
        -------
        List[LanceModel]
        c                     g | ]
} d i |S r   rI   r   rowr  s     r;   r   z1LanceQueryBuilder.to_pydantic.<locals>.<listcomp>4  s%    SSSSSSr=   r  r  rc   r  r  s    ` r;   to_pydanticzLanceQueryBuilder.to_pydantic#  s:    " TSSSg(F(F(P(P(R(RSSSSr=   'pl.DataFrame'c               R    ddl } |j        |                     |                    S )a  
        Execute the query and return the results as a Polars DataFrame.
        In addition to the selected columns, LanceDB also returns a vector
        and also the "_distance" column which is the distance between the query
        vector and the returned vector.

        Parameters
        ----------
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If None, wait indefinitely.
        r   Nr  polars
from_arrowr  rc   r  pls      r;   	to_polarszLanceQueryBuilder.to_polars6  s0     	r}T]]7];;<<<r=   r   Union[int, None]c                |    ||dk    r,t          | t                    rt          d          d| _        n|| _        | S )a  Set the maximum number of results to return.

        Parameters
        ----------
        limit: int
            The maximum number of results to return.
            The default query limit is 10 results.
            For ANN/KNN queries, you must specify a limit.
            For plain searches, all records are returned if limit not set.
            *WARNING* if you have a large dataset, setting
            the limit to a large number, e.g. the table size,
            can potentially result in reading a
            large amount of data into memory and cause
            out of memory issues.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        Nr   z%Limit is required for ANN/KNN queries)r3   r   r6   r   rc   r   s     r;   r   zLanceQueryBuilder.limitG  sH    * =EQJJ$ 788 # !HIII"DKr=   r   rw   c                4    ||dk    rd| _         n|| _         | S )zSet the offset for the results.

        Parameters
        ----------
        offset: int
            The offset to start fetching results from.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        Nr   )r   rc   r   s     r;   r   zLanceQueryBuilder.offsete  s&     >Vq[[DLL!DLr=   r   -Union[list[str], dict[str, Union[str, Expr]]]c                    t          |t                    st          |t                    r|| _        nt	          d          | S )a  Set the columns to return.

        Parameters
        ----------
        columns: list of str, or dict of str to str or Expr
            List of column names to be fetched.
            Or a dictionary of column names to SQL expressions or
            :class:`~lancedb.expr.Expr` objects.
            All columns are fetched if None or unspecified.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        z&columns must be a list or a dictionary)r3   r4   dictr   r6   rc   r   s     r;   r   zLanceQueryBuilder.selectx  sF      gt$$ 	G
7D(A(A 	G#DMMEFFFr=   TwhereUnion[str, Expr]	prefilterc                $    || _         | | _        | S )a  Set the where clause.

        Parameters
        ----------
        where: str or :class:`~lancedb.expr.Expr`
            The filter condition.  Can be a SQL string or a type-safe
            :class:`~lancedb.expr.Expr` built with :func:`~lancedb.expr.col`
            and :func:`~lancedb.expr.lit`.
        prefilter: bool, default True
            If True, apply the filter before vector search, otherwise the
            filter is applied on the result of vector search.
            This feature is **EXPERIMENTAL** and may be removed and modified
            without warning in the future.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        r   r   rc   r8  r:  s      r;   r8  zLanceQueryBuilder.where  s    ( (=r=   r   c                    || _         | S )a  Set whether to return row ids.

        Parameters
        ----------
        with_row_id: bool
            If True, return _rowid column in the results.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        )r   )rc   r   s     r;   r   zLanceQueryBuilder.with_row_id  s     (r=   Fverboser   c                ^    | j                             |                                 |          S )  Return the execution plan for this query.

        Examples
        --------
        >>> import lancedb
        >>> db = lancedb.connect("./.lancedb")
        >>> table = db.create_table("my_table", [{"vector": [99.0, 99]}])
        >>> query = [100, 100]
        >>> plan = table.search(query).explain_plan(True)
        >>> print(plan) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
        ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance]
          GlobalLimitExec: skip=0, fetch=10
            FilterExec: _distance@2 IS NOT NULL
              SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
                KNNVectorDistance: metric=l2
                  LanceRead: uri=..., projection=[vector], ...

        Parameters
        ----------
        verbose : bool, default False
            Use a verbose output format.

        Returns
        -------
        plan : str
        r?  )r   _explain_planto_query_objectrc   r?  s     r;   explain_planzLanceQueryBuilder.explain_plan  s+    6 {(()=)=)?)?(QQQr=   orderingr   c                    || _         | S )a_  
        Set the ordering for the results.

        Parameters
        ----------
        ordering: Optional[List[ColumnOrdering]]
            The ordering to use for the results.  If None, then the default ordering
            will be used.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        )r   rc   rG  s     r;   r   zLanceQueryBuilder.order_by  s     "r=   c                Z    | j                             |                                           S )aG  
        Run the query and return its execution plan with runtime metrics.

        This returns detailed metrics for each step, such as elapsed time,
        rows processed, bytes read, and I/O stats. It is useful for debugging
        and performance tuning.

        Examples
        --------
        >>> import lancedb
        >>> db = lancedb.connect("./.lancedb")
        >>> table = db.create_table("my_table", [{"vector": [99.0, 99]}])
        >>> query = [100, 100]
        >>> plan = table.search(query).analyze_plan()
        >>> print(plan)  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
        AnalyzeExec verbose=true, elapsed=..., metrics=...
          TracedExec, elapsed=..., metrics=...
            ProjectionExec: elapsed=..., expr=[...],
            metrics=[output_rows=..., elapsed_compute=..., output_bytes=...]
              GlobalLimitExec: elapsed=..., skip=0, fetch=10,
              metrics=[output_rows=..., elapsed_compute=..., output_bytes=...]
                FilterExec: elapsed=..., _distance@2 IS NOT NULL, metrics=[...]
                  SortExec: elapsed=..., TopK(fetch=10), expr=[...],
                  preserve_partitioning=[...],
                  metrics=[output_rows=..., elapsed_compute=...,
                  output_bytes=..., row_replacements=...]
                    KNNVectorDistance: elapsed=..., metric=l2,
                    metrics=[output_rows=..., elapsed_compute=...,
                    output_bytes=..., output_batches=...]
                      LanceRead: elapsed=..., uri=..., projection=[vector],
                      num_fragments=..., range_before=None, range_after=None,
                      row_id=true, row_addr=false,
                      full_filter=--, refine_filter=--,
                      metrics=[output_rows=..., elapsed_compute=..., output_bytes=...,
                      fragments_scanned=..., ranges_scanned=1, rows_scanned=1,
                      bytes_read=..., iops=..., requests=..., task_wait_time=...]

        Returns
        -------
        plan : str
            The physical query execution plan with runtime metrics.
        )r   _analyze_planrD  rb   s    r;   analyze_planzLanceQueryBuilder.analyze_plan  s'    V {(()=)=)?)?@@@r=   r   Union[np.ndarray, list]c                    t           )zSet the vector to search for.

        Parameters
        ----------
        vector: np.ndarray or list
            The vector to search for.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        r  rc   r   s     r;   r   zLanceQueryBuilder.vector  s
     "!r=   textstr | FullTextQueryc                    t           )aF  Set the text to search for.

        Parameters
        ----------
        text: str | FullTextQuery
            If a string, it is treated as a MatchQuery.
            If a FullTextQuery object, it is used directly.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        r  rc   rP  s     r;   rP  zLanceQueryBuilder.text!  
     "!r=   rerankerr   c                    t           )zRerank the results using the specified reranker.

        Parameters
        ----------
        reranker: Reranker
            The reranker to use.

        Returns
        -------

        The LanceQueryBuilder object.
        r  rc   rU  s     r;   rerankzLanceQueryBuilder.rerank1  rT  r=   r$   c                    t           )zReturn a serializable representation of the query

        Returns
        -------
        Query
            The serializable representation of the query
        r  rb   s    r;   rD  z!LanceQueryBuilder.to_query_objectA  s
     "!r=   NNN)r   r   rs   r   rd   r@   r   r@   r   r   r   r   r   rB   r0   r,   )r   r   )r0   r   r~   r  r  r  r  r0   r   r  r  r0   r  r  r   r  r  r0   r  r  r  r0   r  )r  r  r  r  r0   r   r  r  r0   r'  )r   r/  r0   r,   r   rw   r0   r,   )r   r4  r0   r,   T)r8  r9  r:  rB   r0   r,   )r   rB   r0   r,   Fr?  r   r0   r@   rG  r   r0   r,   rp   )r   rM  r0   r,   )rP  rQ  r0   r,   )rU  r   r0   r,   r0   r$   ) rE   rF   rG   r   r   r   r   r   r   deprecation
deprecatedr   r  r  r   r  r  r  r&  r.  r   r   r   r8  r   rF  r   rL  r   rP  rX  rD  rI   r=   r;   r   r   +  s          .27; T
 T
 T
 T
 [T
l   [6 " " ["    [#)	  	  	  	  	  /3' (,	' ' ' ' ' '< 9= " " " " " ^""  %)"
 (," " " " " ^"* 9= : : : : : :" AET T T T T T& ;? = = = = = ="   <   &   ,    0    R R R R R:   $+A +A +A +AZ" " " "" " " "  " " " ^" " " " ^" " "r=   r   c                       e Zd ZdZ	 	 d;d< fdZd=dZd>dZd?dZd@dZdAdZ		 d;dBdZ
dCd!ZdDd#ZdEd%Zdd&dFd*ZdGd,Z	 dHdd&dId0Z	 dHdJd4Z	 dHdKd8ZdLd9ZdLd:Z xZS )Mr   a|  
    Examples
    --------
    >>> import lancedb
    >>> data = [{"vector": [1.1, 1.2], "b": 2},
    ...         {"vector": [0.5, 1.3], "b": 4},
    ...         {"vector": [0.4, 0.4], "b": 6},
    ...         {"vector": [0.4, 0.4], "b": 10}]
    >>> db = lancedb.connect("./.lancedb")
    >>> table = db.create_table("my_table", data=data)
    >>> (table.search([0.4, 0.4])
    ...       .distance_type("cosine")
    ...       .where("b < 10")
    ...       .select(["b", "vector"])
    ...       .limit(2)
    ...       .to_pandas())
       b      vector  _distance
    0  6  [0.4, 0.4]   0.000000
    1  2  [1.1, 1.2]   0.000944
    Nr   r   rs   *Union[np.ndarray, list, 'PIL.Image.Image']r   r@   r   r   r   rB   c                    t                                          |           || _        d | _        d | _        d | _        d | _        d | _        d | _        || _	        d | _
        d | _        || _        || _        d S r~   )superr   _query_distance_type_minimum_nprobes_maximum_nprobes_lower_bound_upper_bound_refine_factor_vector_columnr   	_reranker
_str_query_fast_search)rc   r   rs   r   r   r   	__class__s         r;   r   z LanceVectorQueryBuilder.__init__c  s     	" $ $  "+#'r=   metricLiteral['l2', 'cosine', 'dot']r0   c                ,    |                      |          S a  Set the distance metric to use.

        This is an alias for distance_type() and may be deprecated in the future.
        Please use distance_type() instead.

        Parameters
        ----------
        metric: "l2" or "cosine" or "dot"
            The distance metric to use. By default "l2" is used.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceQueryBuilder object.
        r   rc   rx  s     r;   rx  zLanceVectorQueryBuilder.metricy        !!&)))r=   r   'LanceVectorQueryBuilder'c                8    |                                 | _        | S a  Set the distance metric to use.

        When performing a vector search we try and find the "nearest" vectors according
        to some kind of distance metric. This parameter controls which distance metric
        to use.

        Note: if there is a vector index then the distance type used MUST match the
        distance type used to train the vector index. If this is not done then the
        results will be invalid.

        Parameters
        ----------
        distance_type: "l2" or "cosine" or "dot"
            The distance metric to use. By default "l2" is used.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceQueryBuilder object.
        lowerrm  rc   r   s     r;   r   z%LanceVectorQueryBuilder.distance_type      . ,1133r=   nprobesrw   c                "    || _         || _        | S )a  Set the number of probes to use.

        Higher values will yield better recall (more likely to find vectors if
        they exist) at the expense of latency.

        See discussion in [Querying an ANN Index][querying-an-ann-index] for
        tuning advice.

        This method sets both the minimum and maximum number of probes to the same
        value. See `minimum_nprobes` and `maximum_nprobes` for more fine-grained
        control.

        Parameters
        ----------
        nprobes: int
            The number of probes to use.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceQueryBuilder object.
        rn  ro  rc   r  s     r;   r  zLanceVectorQueryBuilder.nprobes  s    . !( 'r=   r   c                    || _         | S )zSet the minimum number of probes to use.

        See `nprobes` for more details.

        These partitions will be searched on every vector query and will increase recall
        at the expense of latency.
        rn  rc   r   s     r;   r   z'LanceVectorQueryBuilder.minimum_nprobes  s     !0r=   r   c                    || _         | S a  Set the maximum number of probes to use.

        See `nprobes` for more details.

        If this value is greater than `minimum_nprobes` then the excess partitions
        will be searched only if we have not found enough results.

        This can be useful when there is a narrow filter to allow these queries to
        spend more time searching and avoid potential false negatives.

        If this value is 0 then no limit will be applied and all partitions could be
        searched if needed to satisfy the limit.
        ro  rc   r   s     r;   r   z'LanceVectorQueryBuilder.maximum_nprobes  s     !0r=   r   r   r   c                "    || _         || _        | S )a  Set the distance range to use.

        Only rows with distances within range [lower_bound, upper_bound)
        will be returned.

        Parameters
        ----------
        lower_bound: Optional[float]
            The lower bound of the distance range.
        upper_bound: Optional[float]
            The upper bound of the distance range.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceQueryBuilder object.
        rp  rq  rc   r   r   s      r;   distance_rangez&LanceVectorQueryBuilder.distance_range  s    ( ('r=   r   c                    || _         | S )a  Set the number of candidates to consider during search.

        Higher values will yield better recall (more likely to find vectors if
        they exist) at the expense of latency.

        This only applies to the HNSW-related index.
        The default value is 1.5 * limit.

        Parameters
        ----------
        ef: int
            The number of candidates to consider during search.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceQueryBuilder object.
        r   rc   r   s     r;   r   zLanceVectorQueryBuilder.ef  s    & r=   r   c                    || _         | S )a)  Set the refine factor to use, increasing the number of vectors sampled.

        As an example, a refine factor of 2 will sample 2x as many vectors as
        requested, re-ranks them, and returns the top half most relevant results.

        See discussion in [Querying an ANN Index][querying-an-ann-index] for
        tuning advice.

        Parameters
        ----------
        refine_factor: int
            The refine factor to use.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceQueryBuilder object.
        rr  rc   r   s     r;   r   z%LanceVectorQueryBuilder.refine_factor
  s    & ,r=   	pa.Schemac                Z    | j                             |                                           S b
        Return the output schema for the query

        This does not execute the query.
        r   _output_schemarD  rb   s    r;   output_schemaz%LanceVectorQueryBuilder.output_schema   &     {))$*>*>*@*@AAAr=   r  r  r  r  c               R    |                      |                                          S )r  r  r  read_allr  s     r;   r  z LanceVectorQueryBuilder.to_arrow(  s$     w//88:::r=   r$   c                   t          | j        t                    r| j        n| j                                        }t          |d         t          j                  rd |D             }t          di d|d| j        d| j        d| j	        d| j
        d| j        d	| j        d
| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        S )zU
        Build a Query object

        This can be used to serialize a query
        r   c                6    g | ]}|                                 S rI   tolistr   vs     r;   r   z;LanceVectorQueryBuilder.to_query_object.<locals>.<listcomp>A       111Qahhjj111r=   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rI   )r3   rl  r4   r  r   r   r$   r   r   r   rm  r   rn  ro  rp  rq  rr  rs  r   r   rv  r   r   r   rO  s     r;   rD  z'LanceVectorQueryBuilder.to_query_object9  s|    !+4; = =W4;CUCUCWCWfQi,, 	211&111F 
 
 
6
;;
 ''
 ++	

 --
 MM
 !11
 !11
 ))
 ))
 --
 --
 ))
 <<
 ))
  xx!
" !% 9 9#
$ ^^%
 	
r=   r  r   r  c              6   t          | j        t                    r| j        n| j                                        }t          |d         t          j                  rd |D             }|                                 }| j                            |||          }| j	        z|
                                }| j	                            | j        |          }t          |           t          j                            |j        |                                          }|S )a  
        Execute the query and return the result as a RecordBatchReader object.

        Parameters
        ----------
        batch_size: int
            The maximum number of selected records in a RecordBatch object.
        timeout: timedelta, default None
            The maximum time to wait for the query to complete.
            If None, wait indefinitely.

        Returns
        -------
        pa.RecordBatchReader
        r   c                6    g | ]}|                                 S rI   r  r  s     r;   r   z6LanceVectorQueryBuilder.to_batches.<locals>.<listcomp>o  r  r=   r  r  )r3   rl  r4   r  r   r   rD  r   _execute_queryrt  r  rerank_vectorru  r   r8   RecordBatchReaderfrom_batchesschemar  )rc   r  r  r   rs   
result_setrs_tables          r;   r  z"LanceVectorQueryBuilder.to_batchesW  s   , !+4; = =W4;CUCUCWCWfQi,, 	211&111F$$&&[//j' 0 
 

 >%!**,,H55doxPPJ!*----::!:#8#8#:#: J r=   r8  r9  r:  c                (    || _         || | _        | S )aH  Set the where clause.

        Parameters
        ----------
        where: str or :class:`~lancedb.expr.Expr`
            The filter condition.  Can be a SQL string or a type-safe
            :class:`~lancedb.expr.Expr` built with :func:`~lancedb.expr.col`
            and :func:`~lancedb.expr.lit`.
        prefilter: bool, default True
            If True, apply the filter before vector search, otherwise the
            filter is applied on the result of vector search.

        Returns
        -------
        LanceQueryBuilder
            The LanceQueryBuilder object.
        r<  r=  s      r;   r8  zLanceVectorQueryBuilder.where  s     (  #,}Dr=   rU  r   query_stringc                    || _         | j        |t          d          |$t          |t                    st          d          ||n| j        | _        |j        dk    r|                     d           | S )a  Rerank the results using the specified reranker.

        Parameters
        ----------
        reranker: Reranker
            The reranker to use.

        query_string: Optional[str]
            The query to use for reranking. This needs to be specified explicitly here
            as the query used for vector search may already be vectorized and the
            reranker requires a string query.
            This is only required if the query used for vector search is not a string.
            Note: This doesn't yet support the case where the query is multimodal or a
            list of vectors.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceQueryBuilder object.
        Nz
                The query used for vector search is not a string.
                In this case, the reranker query needs to be specified explicitly.
                z0Reranking currently only supports string queriesallT)rt  ru  r6   r3   r@   scorer   rc   rU  r  s      r;   rX  zLanceVectorQueryBuilder.rerank  s    . "?"|';   #J|S,I,I#OPPP*6*B,,>U""T"""r=   c                    d| _         | S )a<  
        If this is called then any vector index is skipped

        An exhaustive (flat) search will be performed.  The query vector will
        be compared to every vector in the table.  At high scales this can be
        expensive.  However, this is often still useful.  For example, skipping
        the vector index can give you ground truth results which you can use to
        calculate your recall to select an appropriate value for nprobes.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceVectorQueryBuilder object.
        Tr   rb   s    r;   r   z+LanceVectorQueryBuilder.bypass_vector_index       %)!r=   c                    d| _         | S )a	  
        Skip a flat search of unindexed data. This will improve
        search performance but search results will not include unindexed data.

        Returns
        -------
        LanceVectorQueryBuilder
            The LanceVectorQueryBuilder object.
        Trv  rb   s    r;   r   z#LanceVectorQueryBuilder.fast_search       !r=   NN)
r   r   rs   ri  r   r@   r   r   r   rB   )rx  ry  r0   r   )r   ry  r0   r  )r  rw   r0   r   )r   rw   r0   r   )r   rw   r0   r   )r   r   r   r   r0   r   )r   rw   r0   r   )r   rw   r0   r   r0   r  r\  re  r~   r]  )r8  r9  r:  rB   r0   r   )rU  r   r  r   r0   r   )r0   r   )rE   rF   rG   r   r   rx  r   r  r   r   r  r   r   r  r  rD  r  r8  rX  r   r   __classcell__rw  s   @r;   r   r   M  s        4 $( ( ( ( ( ( ( (,* * * *$   4   6	 	 	 	   $ SW    0   ,   ,B B B B :> ; ; ; ; ; ;"
 
 
 
B %)&
 (,& & & & & &R :>    4 AE$ $ $ $ $L   $       r=   r   c                  p     e Zd ZdZ	 	 	 d"d# fdZd$d%dZd&dZd'dZd(dZddd)dZ		 d*d+dZ
d,d!Z xZS )-r   z+A builder for full text search for LanceDB.Nr   r   rs   rQ  r   r   r   r   r   rB   c                    t                                          |           || _        d| _        |}d | _        || _        t          |t                    r|g}|| _        d S )NF)	rk  r   rl  _phrase_queryrt  rv  r3   r@   _fts_columns)rc   r   rs   r   r   r   _rw  s          r;   r   zLanceFtsQueryBuilder.__init__  si     	"  'k3'' 	(&-K'r=   Tphrase_queryr0   c                    || _         | S )a[  Set whether to use phrase query.

        Parameters
        ----------
        phrase_query: bool, default True
            If True, then the query will be wrapped in quotes and
            double quotes replaced by single quotes.

        Returns
        -------
        LanceFtsQueryBuilder
            The LanceFtsQueryBuilder object.
        r  rc   r  s     r;   r  z!LanceFtsQueryBuilder.phrase_query       *r=   c                    d| _         | S )a  
        Skip a flat search of unindexed data. This will improve
        search performance but search results will not include unindexed data.

        Returns
        -------
        LanceFtsQueryBuilder
            The LanceFtsQueryBuilder object.
        Tr  rb   s    r;   r   z LanceFtsQueryBuilder.fast_search  r  r=   r$   c                    t          | j        | j        | j        | j        | j        t          | j        | j                  | j	        | j
        | j        	  	        S )Nrs   r   )	r   r   r   r   r   r   r   r   r   )r$   r   r   r   r   r   r   rl  r  r   rv  r   rb   s    r;   rD  z$LanceFtsQueryBuilder.to_query_object  sb    M;+')/k4+<   <)^
 
 
 	
r=   r  c                Z    | j                             |                                           S r  r  rb   s    r;   r  z"LanceFtsQueryBuilder.output_schema"  r  r=   r  r  r  r  c               P   | j                                          | j        }| j        rt	          |t
                    r6|                    d          r|                    d          sd| d| _        n9t	          |t                    r$t	          |t                    st          d          |                                 }| j                             ||          }|                                }| j        /| j                            | j        |          }t!          |           |S )N"z*Please use PhraseQuery for phrase queries.r  )r   _ensure_no_legacy_fts_indexrl  r  r3   r@   
startswithendswithr`   r   r   rD  r  r  rt  
rerank_ftsr   )rc   r  rs   resultss       r;   r  zLanceFtsQueryBuilder.to_arrow*  s    //111 	N%%% N'',, /ENN34G4G /".e,,,DKE=11 N*{; ; N   LMMM$$&&+,,UG,DD""$$>%n//WEEG!'***r=   r  r   c                    t          d          )Nzto_batches on an FTS queryr  r  s      r;   r  zLanceFtsQueryBuilder.to_batches>  s     "">???r=   rU  r   c                T    || _         |j        dk    r|                     d           | S )a  Rerank the results using the specified reranker.

        Parameters
        ----------
        reranker: Reranker
            The reranker to use.

        Returns
        -------
        LanceFtsQueryBuilder
            The LanceQueryBuilder object.
        r  T)rt  r  r   rW  s     r;   rX  zLanceFtsQueryBuilder.rerankC  s1     ">U""T"""r=   rZ  )
r   r   rs   rQ  r   r   r   r   r   rB   ra  )r  rB   r0   r   )r0   r   re  r  r\  r  r  r   r  r  )rU  r   r0   r   )rE   rF   rG   r   r   r  r   rD  r  r  r  rX  r  r  s   @r;   r   r     s       55 .27; ( ( ( ( ( ( ((    "   
 
 
 
B B B B :>      * SW@ @ @ @ @
       r=   r   c                  @    e Zd ZddddZdd	ZddZ	 dddZddZdS )r   Nr  r  r  r0   r  c               R    |                      |                                          S )Nr  r  r  s     r;   r  zLanceEmptyQueryBuilder.to_arrowW  s"    w//88:::r=   r$   c                h    t          | j        | j        | j        | j        | j        | j                  S )N)r   r   r   r   r   r   )r$   r   r   r   r   r   r   rb   s    r;   rD  z&LanceEmptyQueryBuilder.to_query_objectZ  s8    M;+)<^
 
 
 	
r=   r  c                ^    |                                  }| j                            |          S r~   )rD  r   r  )rc   rs   s     r;   r  z$LanceEmptyQueryBuilder.output_schemad  s)    $$&&{))%000r=   r  r   r  c               d    |                                  }| j                            |||          S )Nr  )rD  r   r  )rc   r  r  rs   s       r;   r  z!LanceEmptyQueryBuilder.to_batchesh  s3     $$&&{))%JPW)XXXr=   rU  r   c                     t          d          )a  Rerank the results using the specified reranker.

        Parameters
        ----------
        reranker: Reranker
            The reranker to use.

        Returns
        -------
        LanceEmptyQueryBuilder
            The LanceQueryBuilder object.
        zReranking is not yet supported.r  rW  s     r;   rX  zLanceEmptyQueryBuilder.rerankn  s     ""CDDDr=   r\  re  r  r  r]  )rU  r   r0   r   )rE   rF   rG   r  rD  r  r  rX  rI   r=   r;   r   r   V  s        9= ; ; ; ; ; ;
 
 
 
1 1 1 1
 SWY Y Y Y YE E E E E Er=   r   c                  <    e Zd ZdZ	 	 	 dRdS fdZdTdZdUdVdZdWdZdddXdZe	dYd             Z
	 dTdZd#Ze	d[d\d(            Ze	d]d^d,            Z e            d-fd_d1Zd`d3Zdad5Zdbd7Z	 dTdcd;Zddd=Zded@ZdfdCZdgdEZdhdHZdidKZdjdLZd]dkdOZdP ZdQ Z xZS )lr     
    A query builder that performs hybrid vector and full text search.
    Results are combined and reranked based on the specified reranker.
    By default, the results are reranked using the RRFReranker, which
    uses reciprocal rank fusion score for reranking.

    To make the vector and fts results comparable, the scores are normalized.
    Instead of normalizing scores, the `normalize` parameter can be set to "rank"
    in the `rerank` method to convert the scores to ranks and then normalize them.
    Nr   r   rs   #Optional[Union[str, FullTextQuery]]r   r   r   r   c                    t                                          |           || _        || _        || _        d | _        d | _        d | _        d | _        d | _	        d | _
        d | _        d | _        d | _        d S r~   )rk  r   rl  rs  r  _normrt  rn  ro  rr  rm  r  rp  rq  )rc   r   rs   r   r   rw  s        r;   r   z LanceHybridQueryBuilder.__init__  s     	+'
 $ $""!  r=   c                ,   |||t          d          ||n|}t          |t          t          t          j        f          st          d          |p|}|t          d          t          |t          t          f          st          d          ||fS )NzYou can either provide a string query in search() method or set `vector()` and `text()` explicitly for hybrid search.But not both.z0Vector query must be either a string or a vectorz.Text query must be provided for hybrid search.z,Text query must be a string or FullTextQuery)r6   r3   r@   r4   r   r   r`   )rc   rs   r   rP  vector_query
text_querys         r;   _validate_queryz'LanceHybridQueryBuilder._validate_query  s    &"48H    "(!3vv,dBJ(?@@ 	QOPPP]U
MNNN*sM&:;; 	MKLLLZ''r=   r  rB   r0   c                    || _         | S )aa  Set whether to use phrase query.

        Parameters
        ----------
        phrase_query: bool, default True
            If True, then the query will be wrapped in quotes and
            double quotes replaced by single quotes.

        Returns
        -------
        LanceHybridQueryBuilder
            The LanceHybridQueryBuilder object.
        r  r  s     r;   r  z$LanceHybridQueryBuilder.phrase_query  r  r=   r$   c                     t          d          )Nz3to_query_object not yet supported on a hybrid queryr  rb   s    r;   rD  z'LanceHybridQueryBuilder.to_query_object  s    !"WXXXr=   r  r  r  r  c          	     
   |                                   t                      5 }|                    | j                            d          j        |          }|                    | j                            d          j        |          }|                                }|                                }d d d            n# 1 swxY w Y   |                     ||| j	        | j        j
        | j        | j        | j                  S )NTr  fts_resultsvector_resultsnorm	fts_queryrU  r   with_row_ids)_create_query_buildersr   submit
_fts_queryr   r  _vector_queryresult_combine_hybrid_resultsr  rl  rt  r   r   )rc   r  executor
fts_futurevector_futurer  r  s          r;   r  z LanceHybridQueryBuilder.to_arrow  s;   ##%%%!! 	4X!++D11:G )  J %OO"..t44=w ,  M %++--K*1133N	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 ++#)o,^+* , 
 
 	
s   BC  CCr  r  r  r@   r  r   rw   r  c                   |dk    r6t                               |d          }t                               | d          } |j        dk    r| j        dk    rt          j        |j        | j        g          t          j        fdj        D                       }|                    dt          j	        g t          j
                                        }|sd|j        v r|                    dg          }|S d }d }	d }
d }|j        dk    r|j                            d          }|                    |          }|                    d          }
|                    ||                    |          t                               |                    }| j        dk    r| j                            d          }|                     |          }	|                     d          }|                     ||                     |          t                               |	                    } |                    |||           }t'          |           d|j        v re|ct)          j        |d         |
d	
          }t)          j        ||          }|j                            d          }|                    |d|          }d|j        v re|	ct)          j        |d         |d	
          }t)          j        |	|          }	|j                            d          }|                    |d|	          }|                    |          }|s|                    dg          }|S )Nrank	_distance_scorer   c           	     n    i | ]1}|t          j        g                     |          j                   2S )r   )r8   r   fieldr   )r   colcombined_schemas     r;   
<dictcomp>zCLanceHybridQueryBuilder._combine_hybrid_results.<locals>.<dictcomp>  sK        "?+@+@+E+E+JKKK  r=   _relevance_scorer  _rowidT)
skip_nulls)length)r   _ranknum_rowsr8   unify_schemasr  r   namesappend_columnr   r   column_namesdropindexrt   
set_columnr  _normalize_scoresrerank_hybridr   pcindex_intakeslice)r  r  r  r  rU  r   r  emptyoriginal_distancesoriginal_scoresoriginal_distance_row_idsoriginal_score_row_ids
distance_iscore_ir  indicesr  s                   @r;   r  z/LanceHybridQueryBuilder._combine_hybrid_results  s    6>>4::>;WWN177XNNK "a''K,@A,E,E .&(:; O H   .4   E ''"BHRbjll$C$C$C E   /H0B$B$B

H:..L!$(!!% "Q&&'4::;GGJ!/!6!6z!B!B(6(=(=h(G(G%+66$$Z00'99:LMM N !##!.44X>>G)0099O%0%7%7%A%A"%00!!'**'99/JJ K ((NKPPg&&&'...3E3Qk!#<  G "$);W!E!E -33K@@J(([BTUUGw+++0Kk!#9d  G !gow??O*00::G(((OLLG--u--- 	/llH:..Gr=   r  r   c                    t          d          )Nz.to_batches not yet supported on a hybrid queryr  r  s      r;   r  z"LanceHybridQueryBuilder.to_batches9  s     ""RSSSr=   Tr  rt   rC   c           	        t          |           dk    r| S |                     |                                          }t          j        |          }|s|d d d         }t          j        |          }t          j        t          |                    dz   ||<   | j                            |          }| 	                    ||t          j        |t          j                                        } | S )Nr   r   r  )r5   rt   to_numpyr   argsort
empty_likearanger  r  r  r8   r   r   )r  rt   rC   scoressort_indicesranks
_score_idxs          r;   r  zLanceHybridQueryBuilder._rank>  s    w<<1N''0022z&)) 	.'"-Ll++ iF44q8l)//77
$$RZ\\ B B B
 
 r=   Fr,  pa.Arrayc                :   t          |           dk    r| S t          j        |                                           \  }}t          j        ||          }t          j        |t          j        d                                                    s)t          j	        t          j        | |          |          } nNt          j        |t          j        d                                                    st          j        | |          } |rt          j        d|           } | S )Nr   g        r   )
r5   r  min_maxvaluessubtractequalr8   scalaras_pydivide)r,  invertminmaxrngs        r;   r  z)LanceHybridQueryBuilder._normalize_scoresP  s    v;;!M:f%%,,..Sk#s##xRYs^^,,2244 	.Yr{6377==FF#ry~~..4466 	.[--F 	,[F++Fr=   r  rU  r   	normalizec                    |dvrt          d          |r$t          |t                    st          d          || _        || _        |j        dk    r|                     d           | S )a  
        Rerank the hybrid search results using the specified reranker. The reranker
        must be an instance of Reranker class.

        Parameters
        ----------
        reranker: Reranker, default RRFReranker()
            The reranker to use. Must be an instance of Reranker class.
        normalize: str, default "score"
            The method to normalize the scores. Can be "rank" or "score". If "rank",
            the scores are converted to ranks and then normalized. If "score", the
            scores are normalized directly.
        Returns
        -------
        LanceHybridQueryBuilder
            The LanceHybridQueryBuilder object.
        r  r  $normalize must be 'rank' or 'score'./reranker must be an instance of Reranker class.r  T)r6   r3   r   r  rt  r  r   rc   rU  r=  s      r;   rX  zLanceHybridQueryBuilder.rerankc  s}    , ---CDDD 	PJx:: 	PNOOO
!>U""T"""r=   r  c                "    || _         || _        | S )a  
        Set the number of probes to use for vector search.

        Higher values will yield better recall (more likely to find vectors if
        they exist) at the expense of latency.

        Parameters
        ----------
        nprobes: int
            The number of probes to use.

        Returns
        -------
        LanceHybridQueryBuilder
            The LanceHybridQueryBuilder object.
        r  r  s     r;   r  zLanceHybridQueryBuilder.nprobes  s    " !( 'r=   r   c                    || _         | S )zZSet the minimum number of probes to use.

        See `nprobes` for more details.
        r  r  s     r;   r   z'LanceHybridQueryBuilder.minimum_nprobes      
 !0r=   r   c                    || _         | S )zZSet the maximum number of probes to use.

        See `nprobes` for more details.
        r  r  s     r;   r   z'LanceHybridQueryBuilder.maximum_nprobes  rE  r=   r   r   r   c                "    || _         || _        | S )a  
        Set the distance range to use.

        Only rows with distances within range [lower_bound, upper_bound)
        will be returned.

        Parameters
        ----------
        lower_bound: Optional[float]
            The lower bound of the distance range.
        upper_bound: Optional[float]
            The upper bound of the distance range.

        Returns
        -------
        LanceHybridQueryBuilder
            The LanceHybridQueryBuilder object.
        r  r  s      r;   r  z&LanceHybridQueryBuilder.distance_range  s    * ('r=   r   c                    || _         | S )a  
        Set the number of candidates to consider during search.

        Higher values will yield better recall (more likely to find vectors if
        they exist) at the expense of latency.

        This only applies to the HNSW-related index.
        The default value is 1.5 * limit.

        Parameters
        ----------
        ef: int
            The number of candidates to consider during search.

        Returns
        -------
        LanceHybridQueryBuilder
            The LanceHybridQueryBuilder object.
        r  r  s     r;   r   zLanceHybridQueryBuilder.ef  s    ( r=   rx  ry  c                ,    |                      |          S r{  r|  r}  s     r;   rx  zLanceHybridQueryBuilder.metric  r~  r=   r   'LanceHybridQueryBuilder'c                8    |                                 | _        | S r  r  r  s     r;   r   z%LanceHybridQueryBuilder.distance_type  r  r=   r   c                    || _         | S )aL  
        Refine the vector search results by reading extra elements and
        re-ranking them in memory.

        Parameters
        ----------
        refine_factor: int
            The refine factor to use.

        Returns
        -------
        LanceHybridQueryBuilder
            The LanceHybridQueryBuilder object.
        r  r  s     r;   r   z%LanceHybridQueryBuilder.refine_factor  s     ,r=   r   rM  c                    || _         | S r~   )r   rO  s     r;   r   zLanceHybridQueryBuilder.vector  s    r=   rP  rQ  c                    || _         | S r~   )r   rS  s     r;   rP  zLanceHybridQueryBuilder.text  s    
r=   c                    d| _         | S )a<  
        If this is called then any vector index is skipped

        An exhaustive (flat) search will be performed.  The query vector will
        be compared to every vector in the table.  At high scales this can be
        expensive.  However, this is often still useful.  For example, skipping
        the vector index can give you ground truth results which you can use to
        calculate your recall to select an appropriate value for nprobes.

        Returns
        -------
        LanceHybridQueryBuilder
            The LanceHybridQueryBuilder object.
        Tr  rb   s    r;   r   z+LanceHybridQueryBuilder.bypass_vector_index   r  r=   r?  r   c                   |                                   | j        rt          | j                  nd}| j                            | j                                        |          }| j                            | j                                        |          }d                    d |	                                D                       }d                    d |	                                D                       }| d| d| S )rA  zNo rerankerrB  
c              3      K   | ]	}d |z   V  
dS z  NrI   r   lines     r;   	<genexpr>z7LanceHybridQueryBuilder.explain_plan.<locals>.<genexpr>W  &      #U#UDD4K#U#U#U#U#U#Ur=   c              3      K   | ]	}d |z   V  
dS rS  rI   rT  s     r;   rV  z7LanceHybridQueryBuilder.explain_plan.<locals>.<genexpr>X  &       O O O O O O O Or=   
  )
r  rt  r@   r   rC  r  rD  r  join
splitlines)rc   r?  reranker_labelvector_planfts_planindented_vectorindented_ftss          r;   rF  z$LanceHybridQueryBuilder.explain_plan2  s   6 	##%%%04QT^,,,Mk//..00' 0 
 
 ;,,O++--w - 
 
 ))#U#UK<R<R<T<T#U#U#UUUyy O O9L9L9N9N O O OOO IIoII<IIIr=   c                   |                                   dg}|                    | j                            | j                                                             |                    d           |                    | j                            | j                                                             d                    |          S )pExecute the query and display with runtime metrics.

        Returns
        -------
        plan : str
        zVector Search Plan:zFTS Search Plan:rQ  )r  appendr   rK  r  rD  r  r[  rc   r  s     r;   rL  z$LanceHybridQueryBuilder.analyze_plan[  s     	##%%%()t{001C1S1S1U1UVVWWW)***t{001P1P1R1RSSTTTyy!!!r=   c                   |                      | j        | j        | j                  \  }}t	          | j        || j                  | _        |                     | j        || j	                  }t          | j        || j	                  | _        | j        r>| j                            | j                   | j                            | j                   | j        r>| j                            | j                   | j                            | j                   | j        rL| j                            | j        | j                    | j                            | j        | j                    | j        r4| j                            d           | j                            d           | j        r| j                            d           | j        r| j                            | j                   | j        r| j                            | j                   | j        | j                            | j                   | j        r| j                            | j                   | j        r| j                             | j                   | j!        r| j        "                                 | j#        s| j$        r&| j        %                    | j#        | j$                   | j&        tO                      | _&        dS dS )z7Set up and configure the vector and FTS query builders.r   TN)r   r   )(r  rl  r   r   r   r   r  r  r   rs  r   r  r   r   r   r   r   r8  r   r   r   r  r  rm  rx  rn  r   ro  r   rr  r   r   r   r   r   rp  rq  r  rt  r   )rc   r  r  s      r;   r  z.LanceHybridQueryBuilder._create_query_buildersj  s   "&"6"6Ktz#
 #
i /K0A
 
 
 ,,Kt':
 
 5Kt':
 

 ; 	/$$T[111O!!$+...= 	2%%dm444O""4=111; 	E$$T[d6F2FGGGO!!$+43C/CDDD 	.**4000O''--- 	/O((... 	;%%d&9:::  	F..t/DEEE ,..t/DEEE 	B,,T-@AAA8 	,!!$(+++$ 	522444 	 1 	-- -4;L .    >!(]]DNNN "!r=   rZ  )r   r   rs   r  r   r   r   r   r  r~   )r  rB   r0   r   re  r\  )r  r  r  r  r  r@   r  r@   r   rw   r  rB   r0   r  r  ra  )r  r  rt   r@   rC   rB   rb  )r,  r0  r0   r0  )rU  r   r=  r@   r0   r   )r  rw   r0   r   )r   rw   r0   r   )r   rw   r0   r   )r   r   r   r   r0   r   )r   rw   r0   r   )rx  ry  r0   r   )r   ry  r0   rJ  )r   rw   r0   r   )r   rM  r0   r   )rP  rQ  r0   r   )r0   r   rc  )rE   rF   rG   r   r   r  r  rD  r  staticmethodr  r  r  r  r   rX  r  r   r   r  r   rx  r   r   r   rP  r   rF  rL  r  r  r  s   @r;   r   r   ~  s       	 	 6:'+7;! ! ! ! ! ! !*( ( ( ((    "Y Y Y Y :> 
 
 
 
 
 
, Y Y Y \Yx SWT T T T T
     \"     \( )[]]          D   *       SW    2   .* * * *$   4   $         $'J 'J 'J 'J 'JR" " "0+ 0+ 0+ 0+ 0+ 0+ 0+r=   r   c                      e Zd ZdZd+dZd,dZd-dZd.dZdddd/dZd0dZ	d1d2dZ
d1d3dZ	 	 d4d5dZ	 d1d6d Zdd!d7d%Zd8d9d)Zd* ZdS ):AsyncQueryBasezL
    Base class for all async queries (take, scan, vector, fts, hybrid)
    inner3Union[LanceQuery, LanceVectorQuery, LanceTakeQuery]c                    || _         dS )z
        Construct an AsyncQueryBase

        This method is not intended to be called directly.  Instead, use the
        [AsyncTable.query][lancedb.table.AsyncTable.query] method to create a query.
        N_innerrc   rj  s     r;   r   zAsyncQueryBase.__init__  s     r=   r0   r$   c                d    t                               | j                                                  S )z
        Convert the query into a query object

        This is currently experimental but can be useful as the query object is pure
        python and more easily serializable.
        )r$   r   rn  to_query_requestrb   s    r;   rD  zAsyncQueryBase.to_query_object  s&      < < > >???r=   r    Union[List[str], dict[str, str]]r,   c                2   t          |t                    r5t          d |D                       r| j                            |           nKt          |t
                    r&t          d |D                       rt          d |                                D                       rAddlm	 fd|
                                D             }| j                            |           nt          d |                                D                       r:| j                            t          |
                                                     nJt          dt          d	 |
                                D                       z             t          d
          | S )`  
        Return only the specified columns.

        By default a query will return all columns from the table.  However, this can
        have a very significant impact on latency.  LanceDb stores data in a columnar
        fashion.  This
        means we can finely tune our I/O to select exactly the columns we need.

        As a best practice you should always limit queries to the columns that you need.
        If you pass in a list of column names then only those columns will be
        returned.

        You can also use this method to create new "dynamic" columns based on your
        existing columns. For example, you may not care about "a" or "b" but instead
        simply want "a + b".  This is often seen in the SELECT clause of an SQL query
        (e.g. `SELECT a+b FROM my_table`).

        To create dynamic columns you can pass in a dict[str, str].  A column will be
        returned for each entry in the map.  The key provides the name of the column.
        The value is an SQL string used to specify how the column is calculated.

        For example, an SQL query might state `SELECT a + b AS combined, c`.  The
        equivalent input to this method would be `{"combined": "a + b", "c": "c"}`.

        Columns will always be returned in the order given, even if that order is
        different than the order used when adding the data.
        c              3  @   K   | ]}t          |t                    V  d S r~   r3   r@   )r   cs     r;   rV  z(AsyncQueryBase.select.<locals>.<genexpr>  s,      ,Q,QAZ3-?-?,Q,Q,Q,Q,Q,Qr=   c              3  @   K   | ]}t          |t                    V  d S r~   rv  )r   ks     r;   rV  z(AsyncQueryBase.select.<locals>.<genexpr>  s,      .S.Saz!S/A/A.S.S.S.S.S.Sr=   c              3  @   K   | ]}t          |t                    V  d S r~   )r3   r   r  s     r;   rV  z(AsyncQueryBase.select.<locals>.<genexpr>  s,      AA1:a&&AAAAAAr=   r   )_coercec                :    g | ]\  }}| |          j         fS rI   rm  )r   ry  r  r{  s      r;   r   z)AsyncQueryBase.select.<locals>.<listcomp>  s-    LLLDAq!WWQZZ./LLLr=   c              3  @   K   | ]}t          |t                    V  d S r~   rv  r  s     r;   rV  z(AsyncQueryBase.select.<locals>.<genexpr>  s,      BBAZ3''BBBBBBr=   z%dict values must be str or Expr, got c                4    i | ]\  }}|t          |          S rI   r  )r   ry  r  s      r;   r	  z)AsyncQueryBase.select.<locals>.<dictcomp>  s$    BBB$!Q1d1ggBBBr=   z0columns must be a list of column names or a dict)r3   r4   r  rn  select_columnsr6  anyr3  exprr{  itemsselect_exprr   r   r@   )rc   r   pairsr{  s      @r;   r   zAsyncQueryBase.select  s   8 gt$$ 	P,Q,Q,Q,Q,Q)Q)Q 	PK&&w////&& 	P3.S.S7.S.S.S+S+S 	PAA0@0@AAAAA ))))))LLLLGMMOOLLL''....BB1A1ABBBBB ""4#8#89999;BB'--//BBBCCD  
 NOOOr=   c                8    | j                                          | S z;
        Include the _rowid column in the results.
        rn  r   rb   s    r;   r   zAsyncQueryBase.with_row_id       	!!!r=   Nmax_batch_lengthr  r  r   r  r  r   c               d   K   t          | j                            ||           d{V           S )  
        Execute the query and return the results as an Apache Arrow RecordBatchReader.

        Parameters
        ----------

        max_batch_length: Optional[int]
            The maximum number of selected records in a single RecordBatch object.
            If not specified, a default batch length is used.
            It is possible for batches to be smaller than the provided length if the
            underlying data is stored in smaller chunks.
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If not specified, no timeout is applied. If the query does not
            complete within the specified time, an error will be raised.
        r  N)r   rn  execute)rc   r  r  s      r;   r  zAsyncQueryBase.to_batches  sW      , &+%%!17 &        
 
 	
r=   r  c                D   K   | j                                          d{V S )r  N)rn  r  rb   s    r;   r  zAsyncQueryBase.output_schema	  s.       [..000000000r=   r  c                   K   |                      |           d{V }t          j                            |                                 d{V |j                  S )G  
        Execute the query and collect the results into an Apache Arrow Table.

        This method will collect all results into memory before returning.  If
        you expect a large number of results, you may want to use
        [to_batches][lancedb.query.AsyncQueryBase.to_batches]

        Parameters
        ----------
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If not specified, no timeout is applied. If the query does not
            complete within the specified time, an error will be raised.
        r  N)r  )r  r8   r)   r  r  r  )rc   r  
batch_iters      r;   r  zAsyncQueryBase.to_arrow	  sr        ??7?;;;;;;;;
x$$%%''''''''
0A % 
 
 	
r=   r  c                b   K   |                      |           d{V                                 S )e  
        Execute the query and return the results as a list of dictionaries.

        Each list entry is a dictionary with the selected column names as keys,
        or all table columns if `select` is not called. The vector and the "_distance"
        fields are returned whether or not they're explicitly selected.

        Parameters
        ----------
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If not specified, no timeout is applied. If the query does not
            complete within the specified time, an error will be raised.
        r  Nr  r  s     r;   r  zAsyncQueryBase.to_list#	  s:       mmGm44444444??AAAr=   r  r  r   c                p   K    t          |                     |           d{V |          j        di |S )  
        Execute the query and collect the results into a pandas DataFrame.

        This method will collect all results into memory before returning.  If you
        expect a large number of results, you may want to use
        [to_batches][lancedb.query.AsyncQueryBase.to_batches] and convert each batch to
        pandas separately.

        Examples
        --------

        >>> import asyncio
        >>> from lancedb import connect_async
        >>> async def doctest_example():
        ...     conn = await connect_async("./.lancedb")
        ...     table = await conn.create_table("my_table", data=[{"a": 1, "b": 2}])
        ...     async for batch in await table.query().to_batches():
        ...         batch_df = batch.to_pandas()
        >>> asyncio.run(doctest_example())

        Parameters
        ----------
        flatten: Optional[Union[int, bool]]
            If flatten is True, flatten all nested columns.
            If flatten is an integer, flatten the nested columns up to the
            specified depth.
            If unspecified, do not flatten the nested columns.
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If not specified, no timeout is applied. If the query does not
            complete within the specified time, an error will be raised.
        **kwargs
            Forwarded to pyarrow.Table.to_pandas after query execution and
            optional flattening.
        r  NrI   r
  rc   r  r  r  s       r;   r  zAsyncQueryBase.to_pandas4	  sX      R$---"@"@@@@@@@'JJ
   	r=   r'  c                b   K   ddl } |j        |                     |           d{V           S )a  
        Execute the query and collect the results into a Polars DataFrame.

        This method will collect all results into memory before returning.  If you
        expect a large number of results, you may want to use
        [to_batches][lancedb.query.AsyncQueryBase.to_batches] and convert each batch to
        polars separately.

        Parameters
        ----------
        timeout: Optional[timedelta]
            The maximum time to wait for the query to complete.
            If not specified, no timeout is applied. If the query does not
            complete within the specified time, an error will be raised.

        Examples
        --------

        >>> import asyncio
        >>> import polars as pl
        >>> from lancedb import connect_async
        >>> async def doctest_example():
        ...     conn = await connect_async("./.lancedb")
        ...     table = await conn.create_table("my_table", data=[{"a": 1, "b": 2}])
        ...     async for batch in await table.query().to_batches():
        ...         batch_df = pl.from_arrow(batch)
        >>> asyncio.run(doctest_example())
        r   Nr  r)  r,  s      r;   r.  zAsyncQueryBase.to_polarsa	  sG      @ 	r}4===#A#AAAAAAABBBr=   r  r  Type[LanceModel]List[LanceModel]c               |   K   fd|                      |           d{V                                 D             S )av  
        Convert results to a list of pydantic models.

        Parameters
        ----------
        model : Type[LanceModel]
            The pydantic model to use.
        timeout : timedelta, optional
            The maximum time to wait for the query to complete.
            If None, wait indefinitely.

        Returns
        -------
        list[LanceModel]
        c                     g | ]
} d i |S r   rI   r#  s     r;   r   z.AsyncQueryBase.to_pydantic.<locals>.<listcomp>	  s2     
 
 
 EELLCLL
 
 
r=   r  Nr  r%  s    ` r;   r&  zAsyncQueryBase.to_pydantic	  s^      $
 
 
 
+/===+I+I%I%I%I%I%I%I$T$T$V$V
 
 
 	
r=   Fr?  r   c                F   K   | j                             |           d{V S )t  Return the execution plan for this query.

        Examples
        --------
        >>> import asyncio
        >>> from lancedb import connect_async
        >>> async def doctest_example():
        ...     conn = await connect_async("./.lancedb")
        ...     table = await conn.create_table("my_table", [{"vector": [99.0, 99.0]}])
        ...     plan = await table.query().nearest_to([1.0, 2.0]).explain_plan(True)
        ...     print(plan)
        >>> asyncio.run(doctest_example()) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
        ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance]
          GlobalLimitExec: skip=0, fetch=10
            FilterExec: _distance@2 IS NOT NULL
              SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
                KNNVectorDistance: metric=l2
                  LanceRead: uri=..., projection=[vector], ...
        <BLANKLINE>

        Parameters
        ----------
        verbose : bool, default False
            Use a verbose output format.

        Returns
        -------
        plan : str
        N)rn  rF  rE  s     r;   rF  zAsyncQueryBase.explain_plan	  s0      < [--g666666666r=   c                D   K   | j                                          d{V S )rc  N)rn  rL  rb   s    r;   rL  zAsyncQueryBase.analyze_plan	  s.       [--/////////r=   )rj  rk  re  r   rr  r0   r,   r0   r,   r  r   r  r  r0   r   r  r~   r\  r^  r  r[  r_  )r  r  r  r  r0   r  rb  r?  r   )rE   rF   rG   r   r   rD  r   r   r  r  r  r  r  r.  r&  rF  rL  rI   r=   r;   ri  ri    sx           @ @ @ @. . . .`    +/'+	
 
 
 
 
 
81 1 1 1
 
 
 
 
(B B B B B& /3'++ + + + +^ (,"C "C "C "C "CJ JN
 
 
 
 
 
,7 7 7 7 7@0 0 0 0 0r=   ri  c                  T     e Zd ZdZd fdZdd	ZddZddZddZddZ	ddZ
 xZS )AsyncStandardQueryzJ
    Base class for "standard" async queries (all but take currently)
    rj  #Union[LanceQuery, LanceVectorQuery]c                J    t                                          |           dS )z
        Construct an AsyncStandardQuery

        This method is not intended to be called directly.  Instead, use the
        [AsyncTable.query][lancedb.table.AsyncTable.query] method to create a query.
        Nrk  r   rc   rj  rw  s     r;   r   zAsyncStandardQuery.__init__	  s#     	r=   	predicater9  r0   r,   c                    t          |t                    r | j                            |j                   n| j                            |           | S )a  
        Only return rows matching the given predicate

        The predicate can be a SQL string or a type-safe
        :class:`~lancedb.expr.Expr` built with :func:`~lancedb.expr.col`
        and :func:`~lancedb.expr.lit`.

        Examples
        --------

        >>> predicate = "x > 10"
        >>> predicate = "y > 0 AND y < 100"
        >>> predicate = "x > 5 OR y = 'test'"

        Filtering performance can often be improved by creating a scalar index
        on the filter column(s).
        )r3   r   rn  
where_exprr8  )rc   r  s     r;   r8  zAsyncStandardQuery.where	  sM    $ i&& 	)K""9#34444Ki(((r=   r   rw   c                :    | j                             |           | S )z
        Set the maximum number of results to return.

        By default, a plain search has no limit.  If this method is not
        called then every valid row from the table will be returned.
        )rn  r   r1  s     r;   r   zAsyncStandardQuery.limit	  s     	%   r=   r   c                :    | j                             |           | S )z
        Set the offset for the results.

        Parameters
        ----------
        offset: int
            The offset to start fetching results from.
        )rn  r   r3  s     r;   r   zAsyncStandardQuery.offset	  s     	6"""r=   rG  r   c                    || j                             d           n$| j                             d |D                        | S )z
        Set the ordering for the results.

        Parameters
        ----------
        ordering: Optional[List[ColumnOrdering]]
            The ordering to use for the results.  If None, then the default ordering
            will be used.
        Nc                ~    g | ]:}t          |d           r|                                n|                                ;S )
model_dump)hasattrr  r6  r   s     r;   r   z/AsyncStandardQuery.order_by.<locals>.<listcomp>
  sK        '.a&>&>LALLNNNAFFHH  r=   )rn  r   rI  s     r;   r   zAsyncStandardQuery.order_by
  s`     K  &&&&K   %     r=   c                8    | j                                          | S )a,  
        Skip searching un-indexed data.

        This can make queries faster, but will miss any data that has not been
        indexed.

        !!! tip
            You can add new data into an existing index by calling
            [AsyncTable.optimize][lancedb.table.AsyncTable.optimize].
        )rn  r   rb   s    r;   r   zAsyncStandardQuery.fast_search
  s     	!!!r=   c                8    | j                                          | S )ax  
        If this is called then filtering will happen after the search instead of
        before.
        By default filtering will be performed before the search.  This is how
        filtering is typically understood to work.  This prefilter step does add some
        additional latency.  Creating a scalar index on the filter column(s) can
        often improve this latency.  However, sometimes a filter is too complex or
        scalar indices cannot be applied to the column.  In these cases postfiltering
        can be used instead of prefiltering to improve latency.
        Post filtering applies the filter to the results of the search.  This
        means we only run the filter on a much smaller set of data.  However, it can
        cause the query to return fewer than `limit` results (or even no results) if
        none of the nearest results match the filter.
        Post filtering happens during the "refine stage" (described in more detail in
        @see {@link VectorQuery#refineFactor}).  This means that setting a higher refine
        factor can often help restore some of the results lost by post filtering.
        )rn  r   rb   s    r;   r   zAsyncStandardQuery.postfilter$
  s    $ 	   r=   )rj  r  )r  r9  r0   r,   )r   rw   r0   r,   r`  rd  r  )rE   rF   rG   r   r   r8  r   r   r   r   r   r  r  s   @r;   r  r  	  s                       0   
 
 
 
   *          r=   r  c                  L     e Zd Zd fdZedd            ZddZ	 dddZ xZS )
AsyncQueryrj  
LanceQueryc                X    t                                          |           || _        dS )z
        Construct an AsyncQuery

        This method is not intended to be called directly.  Instead, use the
        [AsyncTable.query][lancedb.table.AsyncTable.query] method to create a query.
        N)rk  r   rn  r  s     r;   r   zAsyncQuery.__init__;
  s(     	r=   vecUnion[VEC, Tuple]c                   t          |t                    rt          j        |          S t          |t          j                  rt          j        |          S t          |t          j                  r|S t          |t          j                  r|                                S t          |t                    rt          j        |          S t          j        |          S r~   )
r3   r4   r8   r   r   r   r9   ChunkedArraycombine_chunkstuple)rc   r  s     r;   _query_vec_to_arrayzAsyncQuery._query_vec_to_arrayE
  s    c4   	!8C== c2:&& 	!8C== c28$$ 	Jc2?++ 	(%%'''c5!! 	!8C==  x}}r=   r   Union[VEC, Tuple, List[VEC]]r0   AsyncVectorQueryc                >   |t          d          t          |t          t          j        t
          j        f          rt          |          dk    rt          |d         t          t          j        t
          j        f          r]d |D             }| j        	                    |d                   }|dd         D ]}|
                    |           t          |          S t          | j        	                    t                              |                              S )aC
  
        Find the nearest vectors to the given query vector.

        This converts the query from a plain query to a vector query.

        This method will attempt to convert the input to the query vector
        expected by the embedding model.  If the input cannot be converted
        then an error will be thrown.

        By default, there is no embedding model, and the input should be
        something that can be converted to a pyarrow array of floats.  This
        includes lists, numpy arrays, and tuples.

        If there is only one vector column (a column whose data type is a
        fixed size list of floats) then the column does not need to be specified.
        If there is more than one vector column you must use
        [AsyncVectorQuery.column][lancedb.query.AsyncVectorQuery.column] to specify
        which column you would like to compare with.

        If no index has been created on the vector column then a vector query
        will perform a distance comparison between the query vector and every
        vector in the database and then sort the results.  This is sometimes
        called a "flat search"

        For small databases, with tens of thousands of vectors or less, this can
        be reasonably fast.  In larger databases you should create a vector index
        on the column.  If there is a vector index then an "approximate" nearest
        neighbor search (frequently called an ANN search) will be performed.  This
        search is much faster, but the results will be approximate.

        The query can be further parameterized using the returned builder.  There
        are various ANN search parameters that will let you fine tune your recall
        accuracy vs search latency.

        Vector searches always have a [limit][].  If `limit` has not been called then
        a default `limit` of 10 will be used.

        Typically, a single vector is passed in as the query. However, you can also
        pass in multiple vectors. When multiple vectors are passed in, if the vector
        column is with multivector type, then the vectors will be treated as a single
        query. Or the vectors will be treated as multiple queries, this can be useful
        if you want to find the nearest vectors to multiple query vectors.
        This is not expected to be faster than making multiple queries concurrently;
        it is just a convenience method. If multiple vectors are passed in then
        an additional column `query_index` will be added to the results. This column
        will contain the index of the query vector that the result is nearest to.
        Nquery_vector can not be Noner   c                B    g | ]}t                               |          S rI   r  r  r  s     r;   r   z)AsyncQuery.nearest_to.<locals>.<listcomp>
  &    UUU1Z;;A>>UUUr=   r   )r6   r3   r4   r   r   r8   r9   r5   rn  
nearest_toadd_query_vectorr  r  r  rc   r   query_vectorsnew_selfr  s        r;   r  zAsyncQuery.nearest_toV
  s   f ;<<< |dBJ%ABB	L!!A%%<?T2:rx,HII & VUUUUM{--mA.>??H"122& - -))!,,,,#H---#&&z'E'El'S'STT  r=   Nrs   rQ  r   Union[str, List[str], None]AsyncFTSQueryc                
   t          |t                    r|g}|g }t          |t                    r*t          | j                            ||d                    S t          | j                            d|i                    S )a  
        Find the documents that are most relevant to the given text query.

        This method will perform a full text search on the table and return
        the most relevant documents.  The relevance is determined by BM25.

        The columns to search must be with native FTS index
        (Tantivy-based can't work with this method).

        By default, all indexed columns are searched,
        now only one column can be searched at a time.

        Parameters
        ----------
        query: str
            The text query to search for.
        columns: str or list of str, default None
            The columns to search in. If None, all indexed columns are searched.
            For now only one column can be searched at a time.
        Nr  rs   )r3   r@   r  rn  nearest_to_textrc   rs   r   s      r;   r  zAsyncQuery.nearest_to_text
  s    . gs## 	 iG?GeS!! 	 ++e,P,PQQ   T[88'59IJJKKKr=   )rj  r  )r  r  )r   r  r0   r  r~   )rs   rQ  r   r  r0   r  )	rE   rF   rG   r   r   r  r  r  r  r  s   @r;   r  r  :
  s                 [ D D D DN RV!L !L !L !L !L !L !L !L !Lr=   r  c                  d     e Zd ZdZd fdZddZ e            fdd
ZddZdddd fdZ	 xZ
S )r  z)A query for full text search for LanceDB.rj  LanceFTSQueryc                f    t                                          |           || _        d | _        d S r~   )rk  r   rn  rt  r  s     r;   r   zAsyncFTSQuery.__init__
  s-    r=   r0   r@   c                4    | j                                         S r~   )rn  	get_queryrb   s    r;   r  zAsyncFTSQuery.get_query
  s    {$$&&&r=   rU  r   c                `    |r$t          |t                    st          d          || _        | S )NrA  )r3   r   r6   rt  rW  s     r;   rX  zAsyncFTSQuery.rerank
  s:      	PJx:: 	PNOOO!r=   r   r  AsyncHybridQueryc                   |t          d          t          |t                    rt          |          dk    rt          |d         t          t
          f          s]d |D             }| j                            |d                   }|dd         D ]}|                    |           t          |          S t          | j                            t                              |                              S )a
  
        In addition doing text search on the LanceDB Table, also
        find the nearest vectors to the given query vector.

        This converts the query from a FTS Query to a Hybrid query. Results
        from the vector search will be combined with results from the FTS query.

        This method will attempt to convert the input to the query vector
        expected by the embedding model.  If the input cannot be converted
        then an error will be thrown.

        By default, there is no embedding model, and the input should be
        something that can be converted to a pyarrow array of floats.  This
        includes lists, numpy arrays, and tuples.

        If there is only one vector column (a column whose data type is a
        fixed size list of floats) then the column does not need to be specified.
        If there is more than one vector column you must use
        [AsyncVectorQuery.column][lancedb.query.AsyncVectorQuery.column] to specify
        which column you would like to compare with.

        If no index has been created on the vector column then a vector query
        will perform a distance comparison between the query vector and every
        vector in the database and then sort the results.  This is sometimes
        called a "flat search"

        For small databases, with tens of thousands of vectors or less, this can
        be reasonably fast.  In larger databases you should create a vector index
        on the column.  If there is a vector index then an "approximate" nearest
        neighbor search (frequently called an ANN search) will be performed.  This
        search is much faster, but the results will be approximate.

        The query can be further parameterized using the returned builder.  There
        are various ANN search parameters that will let you fine tune your recall
        accuracy vs search latency.

        Hybrid searches always have a [limit][].  If `limit` has not been called then
        a default `limit` of 10 will be used.

        Typically, a single vector is passed in as the query. However, you can also
        pass in multiple vectors.  This can be useful if you want to find the nearest
        vectors to multiple query vectors. This is not expected to be faster than
        making multiple queries concurrently; it is just a convenience method.
        If multiple vectors are passed in then an additional column `query_index`
        will be added to the results.  This column will contain the index of the
        query vector that the result is nearest to.
        Nr  r   c                B    g | ]}t                               |          S rI   r  r  s     r;   r   z,AsyncFTSQuery.nearest_to.<locals>.<listcomp>  r  r=   r   )r6   r3   r4   r5   r7   rw   rn  r  r  r  r  r  r  s        r;   r  zAsyncFTSQuery.nearest_to
  s    f ;<<< |T**	L!!A%%|A== & VUUUUM{--mA.>??H"122& - -))!,,,,#H---#&&z'E'El'S'STT  r=   Nr  r  r   r  r  r   c               \  K   t                                          |           d {V }t          j                            |                                 d {V |j                  }| j        r-| j                            | 	                                |          }t          ||          S Nr  r  )rk  r  r8   r)   r  r  r  rt  r  r  r   rc   r  r  readerr  rw  s        r;   r  zAsyncFTSQuery.to_batches  s       ww))')::::::::(''foo.?.?(?(?(?(?(?(?OO> 	Kn//0@0@'JJG%g@PQQQQr=   )rj  r  rp   )rU  r   r0   r  )r   r  r0   r  r  )rE   rF   rG   r   r   r  r   rX  r  r  r  r  s   @r;   r  r  
  s        33     
' ' ' '
 )[]]	 	 	 	 	D D D DR +/'+	
R 
R 
R 
R 
R 
R 
R 
R 
R 
R 
R 
Rr=   r  c                  Z    e Zd ZddZddZdd
ZddZ	 dddZddZd dZ	d!dZ
d"dZdS )#AsyncVectorQueryBasert   r@   r0   r,   c                :    | j                             |           | S )aZ  
        Set the vector column to query

        This controls which column is compared to the query vector supplied in
        the call to [AsyncQuery.nearest_to][lancedb.query.AsyncQuery.nearest_to].

        This parameter must be specified if the table has more than one column
        whose data type is a fixed-size-list of floats.
        )rn  rt   )rc   rt   s     r;   rt   zAsyncVectorQueryBase.column*  s     	6"""r=   r  rw   c                :    | j                             |           | S )a  
        Set the number of partitions to search (probe)

        This argument is only used when the vector column has an IVF-based index.
        If there is no index then this value is ignored.

        The IVF stage of IVF PQ divides the input into partitions (clusters) of
        related values.

        The partition whose centroids are closest to the query vector will be
        exhaustiely searched to find matches.  This parameter controls how many
        partitions should be searched.

        Increasing this value will increase the recall of your query but will
        also increase the latency of your query.  The default value is 20.  This
        default is good for many cases but the best value to use will depend on
        your data and the recall that you need to achieve.

        For best results we recommend tuning this parameter with a benchmark against
        your actual data to find the smallest possible value that will still give
        you the desired recall.
        )rn  r  r  s     r;   r  zAsyncVectorQueryBase.nprobes7  s    . 	G$$$r=   r   c                :    | j                             |           | S )zSet the minimum number of probes to use.

        See `nprobes` for more details.

        These partitions will be searched on every indexed vector query and will
        increase recall at the expense of latency.
        )rn  r   r  s     r;   r   z$AsyncVectorQueryBase.minimum_nprobesQ  s     	##O444r=   r   c                :    | j                             |           | S r  )rn  r   r  s     r;   r   z$AsyncVectorQueryBase.maximum_nprobes\  s     	##O444r=   Nr   r   r   c                <    | j                             ||           | S )a  Set the distance range to use.

        Only rows with distances within range [lower_bound, upper_bound)
        will be returned.

        Parameters
        ----------
        lower_bound: Optional[float]
            The lower bound of the distance range.
        upper_bound: Optional[float]
            The upper bound of the distance range.

        Returns
        -------
        AsyncVectorQuery
            The AsyncVectorQuery object.
        )rn  r  r  s      r;   r  z#AsyncVectorQueryBase.distance_rangem  s!    ( 	"";<<<r=   r   c                :    | j                             |           | S )a  
        Set the number of candidates to consider during search

        This argument is only used when the vector column has an HNSW index.
        If there is no index then this value is ignored.

        Increasing this value will increase the recall of your query but will also
        increase the latency of your query.  The default value is 1.5 * limit.  This
        default is good for many cases but the best value to use will depend on your
        data and the recall that you need to achieve.
        )rn  r   r  s     r;   r   zAsyncVectorQueryBase.ef  s     	rr=   r   c                :    | j                             |           | S )a  
        A multiplier to control how many additional rows are taken during the refine
        step

        This argument is only used when the vector column has an IVF PQ index.
        If there is no index then this value is ignored.

        An IVF PQ index stores compressed (quantized) values.  They query vector is
        compared against these values and, since they are compressed, the comparison is
        inaccurate.

        This parameter can be used to refine the results.  It can improve both improve
        recall and correct the ordering of the nearest results.

        To refine results LanceDb will first perform an ANN search to find the nearest
        `limit` * `refine_factor` results.  In other words, if `refine_factor` is 3 and
        `limit` is the default (10) then the first 30 results will be selected.  LanceDb
        then fetches the full, uncompressed, values for these 30 results.  The results
        are then reordered by the true distance and only the nearest 10 are kept.

        Note: there is a difference between calling this method with a value of 1 and
        never calling this method at all.  Calling this method with any value will have
        an impact on your search latency.  When you call this method with a
        `refine_factor` of 1 then LanceDb still needs to fetch the full, uncompressed,
        values so that it can potentially reorder the results.

        Note: if this method is NOT called then the distances returned in the _distance
        column will be approximate distances based on the comparison of the quantized
        query vector and the quantized result vectors.  This can be considerably
        different than the true distance between the query vector and the actual
        uncompressed vector.
        )rn  r   r  s     r;   r   z"AsyncVectorQueryBase.refine_factor  s     B 	!!-000r=   r   c                :    | j                             |           | S )aO  
        Set the distance metric to use

        When performing a vector search we try and find the "nearest" vectors according
        to some kind of distance metric.  This parameter controls which distance metric
        to use.  See @see {@link IvfPqOptions.distanceType} for more details on the
        different distance metrics available.

        Note: if there is a vector index then the distance type used MUST match the
        distance type used to train the vector index.  If this is not done then the
        results will be invalid.

        By default "l2" is used.
        )rn  r   r  s     r;   r   z"AsyncVectorQueryBase.distance_type  s     	!!-000r=   c                8    | j                                          | S )a  
        If this is called then any vector index is skipped

        An exhaustive (flat) search will be performed.  The query vector will
        be compared to every vector in the table.  At high scales this can be
        expensive.  However, this is often still useful.  For example, skipping
        the vector index can give you ground truth results which you can use to
        calculate your recall to select an appropriate value for nprobes.
        )rn  r   rb   s    r;   r   z(AsyncVectorQueryBase.bypass_vector_index  s     	'')))r=   )rt   r@   r0   r,   )r  rw   r0   r,   )r   rw   r0   r,   )r   rw   r0   r,   r  )r   r   r   r   r0   r,   )r   rw   r0   r,   )r   rw   r0   r,   )r   r@   r0   r,   r  )rE   rF   rG   rt   r  r   r   r  r   r   r   r   rI   r=   r;   r  r  )  s              4	 	 	 	   $ SW    .   " " " "H   $     r=   r  c                  ^     e Zd Zd fdZ e            dfddZ	 dddZdddd fdZ xZS )r  rj  LanceVectorQueryc                t    t                                          |           || _        d| _        d| _        dS )a  
        Construct an AsyncVectorQuery

        This method is not intended to be called directly.  Instead, create
        a query first with [AsyncTable.query][lancedb.table.AsyncTable.query] and then
        use [AsyncQuery.nearest_to][lancedb.query.AsyncQuery.nearest_to]] to convert to
        a vector query.  Or you can use
        [AsyncTable.vector_search][lancedb.table.AsyncTable.vector_search]
        N)rk  r   rn  rt  _query_stringr  s     r;   r   zAsyncVectorQuery.__init__  s9     	!r=   NrU  r   r  r   r0   r  c                    |r$t          |t                    st          d          || _        | j        s|st          d          || _        | S )NrA  z4query_string must be provided to rerank the results.)r3   r   r6   rt  r  r  s      r;   rX  zAsyncVectorQuery.rerank  se      	PJx:: 	PNOOO!! 	U, 	USTTT)r=   rs   rQ  r   r  c                
   t          |t                    r|g}|g }t          |t                    r*t          | j                            ||d                    S t          | j                            d|i                    S )a  
        Find the documents that are most relevant to the given text query,
        in addition to vector search.

        This converts the vector query into a hybrid query.

        This search will perform a full text search on the table and return
        the most relevant documents, combined with the vector query results.
        The text relevance is determined by BM25.

        The columns to search must be with native FTS index
        (Tantivy-based can't work with this method).

        By default, all indexed columns are searched,
        now only one column can be searched at a time.

        Parameters
        ----------
        query: str
            The text query to search for.
        columns: str or list of str, default None
            The columns to search in. If None, all indexed columns are searched.
            For now only one column can be searched at a time.
        Nr  rs   )r3   r@   r  rn  r  r  s      r;   r  z AsyncVectorQuery.nearest_to_text  s    6 gs## 	 iG?GeS!! 	#++e,P,PQQ     ; ;We<L M MNNNr=   r  r  r   r  r  r   c               B  K   t                                          |           d {V }t          j                            |                                 d {V |j                  }| j        r | j                            | j	        |          }t          ||          S r  )rk  r  r8   r)   r  r  r  rt  r  r  r   r  s        r;   r  zAsyncVectorQuery.to_batches  s       ww))')::::::::(''foo.?.?(?(?(?(?(?(?OO> 	Pn2243EwOOG%g@PQQQQr=   )rj  r  )rU  r   r  r   r0   r  r~   )rs   rQ  r   r  r0   r  r  )	rE   rF   rG   r   r   rX  r  r  r  r  s   @r;   r  r    s        " " " " " "  $/;==PT      RV%O %O %O %O %OT +/'+	
R 
R 
R 
R 
R 
R 
R 
R 
R 
R 
R 
Rr=   r  c                  b     e Zd ZdZd fdZ e            dfddZdddddZdddZd Z	 xZ
S )r  r  rj  LanceHybridQueryc                    t                                          |           || _        d| _        t	                      | _        d S )Nr  )rk  r   rn  r  r   rt  r  s     r;   r   zAsyncHybridQuery.__init__6  s8    
$r=   r  rU  r   r=  r@   r0   c                    |dvrt          d          |r$t          |t                    st          d          || _        || _        | S )a  
        Rerank the hybrid search results using the specified reranker. The reranker
        must be an instance of Reranker class.

        Parameters
        ----------
        reranker: Reranker, default RRFReranker()
            The reranker to use. Must be an instance of Reranker class.
        normalize: str, default "score"
            The method to normalize the scores. Can be "rank" or "score". If "rank",
            the scores are converted to ranks and then normalized. If "score", the
            scores are normalized directly.
        Returns
        -------
        AsyncHybridQuery
            The AsyncHybridQuery object.
        r?  r@  rA  )r6   r3   r   r  rt  rB  s      r;   rX  zAsyncHybridQuery.rerank<  s\    ( ---CDDD 	PJx:: 	PNOOO
!r=   Nr  r  r   r  r  r   c          	     v  K   t          | j                                                  }t          | j                                                  }| j                                        }|                                 |                                 t          j        |	                    |          |	                    |                     d {V \  }}t                              ||| j        |                                | j        | j                                        |          }t!          ||          S )Nr  r  r  )r  rn  to_fts_queryr  to_vector_queryget_with_row_idr   asynciogatherr  r   r  r  r  rt  	get_limitr   )	rc   r  r  r  	vec_queryr  r  r  r  s	            r;   r  zAsyncHybridQuery.to_batchesZ  s9      "$+":":"<"<==	$T[%@%@%B%BCC	 {2244,3Nw//w//-
 -
 '
 '
 '
 '
 '
 '
#^
 )@@#)))++^+''))% A 
 
 &f?OPPPPr=   Fr?  r   c                  K   | j                                                             |           d{V }| j                                                             |           d{V }d                    d |                                D                       }d                    d |                                D                       }| j         d| d| S )ac  Return the execution plan for this query.

        The output includes both the vector and FTS search plans.

        Examples
        --------
        >>> import asyncio
        >>> from lancedb import connect_async
        >>> from lancedb.index import FTS
        >>> async def doctest_example():
        ...     conn = await connect_async("./.lancedb")
        ...     table = await conn.create_table("my_table", [{"vector": [99.0, 99.0], "text": "hello world"}])
        ...     await table.create_index("text", config=FTS(with_position=False))
        ...     plan = await table.query().nearest_to([1.0, 2.0]).nearest_to_text("hello").explain_plan(True)
        ...     print(plan)
        >>> asyncio.run(doctest_example()) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
        RRFReranker(K=60)
            ProjectionExec: expr=[vector@0 as vector, text@3 as text, _distance@2 as _distance]
              Take: columns="vector, _rowid, _distance, (text)"
                CoalesceBatchesExec: target_batch_size=1024
                  GlobalLimitExec: skip=0, fetch=10
                    FilterExec: _distance@2 IS NOT NULL
                      SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
                        KNNVectorDistance: metric=l2
                          LanceRead: uri=..., projection=[vector], ...
            ProjectionExec: expr=[vector@2 as vector, text@3 as text, _score@1 as _score]
              Take: columns="_rowid, _score, (vector), (text)"
                CoalesceBatchesExec: target_batch_size=1024
                  GlobalLimitExec: skip=0, fetch=10
                    MatchQuery: column=text, query=hello

        Parameters
        ----------
        verbose : bool, default False
            Use a verbose output format.

        Returns
        -------
        plan : str
        NrQ  c              3      K   | ]	}d |z   V  
dS rS  rI   rT  s     r;   rV  z0AsyncHybridQuery.explain_plan.<locals>.<genexpr>  rW  r=   c              3      K   | ]	}d |z   V  
dS rS  rI   rT  s     r;   rV  z0AsyncHybridQuery.explain_plan.<locals>.<genexpr>  rY  r=   rZ  )rn  r  rF  r  r[  r\  rt  )rc   r?  r^  r_  r`  ra  s         r;   rF  zAsyncHybridQuery.explain_planz  s      T !K7799FFwOOOOOOOO1133@@IIIIIIII))#U#UK<R<R<T<T#U#U#UUUyy O O9L9L9N9N O O OOO.IIoII<IIIr=   c                p  K   dg}|                     | j                                                                         d{V            |                     d           |                     | j                                                                         d{V            d                    |          S )u  
        Execute the query and return the physical execution plan with runtime metrics.

        This runs both the vector and FTS (full-text search) queries and returns
        detailed metrics for each step of execution—such as rows processed,
        elapsed time, I/O stats, and more. It’s useful for debugging and
        performance analysis.

        Returns
        -------
        plan : str
        zVector Search Query:NzFTS Search Query:rQ  )rd  rn  r  rL  r  r[  re  s     r;   rL  zAsyncHybridQuery.analyze_plan  s       **T[88::GGIIIIIIIIJJJ*+++T[5577DDFFFFFFFFGGGyy!!!r=   )rj  r  )rU  r   r=  r@   r0   r  r  rb  r  )rE   rF   rG   r   r   r   rX  r  rF  rL  r  r  s   @r;   r  r  *  s        	 	' ' ' ' ' ' $/;==7    B +/'+	Q Q Q Q Q Q@/J /J /J /J /Jb" " " " " " "r=   r  c                  $     e Zd ZdZd fdZ xZS )AsyncTakeQuery@
    Builder for parameterizing and executing take queries.
    rj  LanceTakeQueryc                J    t                                          |           d S r~   r  r  s     r;   r   zAsyncTakeQuery.__init__  !    r=   )rj  r  rE   rF   rG   r   r   r  r  s   @r;   r  r    G                            r=   r  c                      e Zd ZdZd&dZd'dZd(dZd)dZd*dZdddd+dZ	d,d-dZ
d,d.dZ	 	 d/d0dZ	 d,d1d Zd2d3d$Zd% ZdS )4BaseQueryBuilderzC
    Wraps AsyncQueryBase and provides a synchronous interface
    rj  ri  c                    || _         d S r~   rm  ro  s     r;   r   zBaseQueryBuilder.__init__  s    r=   r0   r$   c                4    | j                                         S r~   )rn  rD  rb   s    r;   rD  z BaseQueryBuilder.to_query_object  s    {**,,,r=   r   rr  r,   c                :    | j                             |           | S )rt  )rn  r   r7  s     r;   r   zBaseQueryBuilder.select  s    8 	7###r=   c                8    | j                                          | S r  r  rb   s    r;   r   zBaseQueryBuilder.with_row_id  r  r=   r  c                X    t          j        | j                                                  S r  )r   runrn  r  rb   s    r;   r  zBaseQueryBuilder.output_schema  s"     x1133444r=   Nr  r  r   r  r  r  c                   t          j        | j                            ||                    fd}t          j                            j         |                      S )r  r  c               3     K   	 	 t          j                                                   V  )# t          $ r Y d S w xY wr~   )r   r  	__anext__StopAsyncIteration)async_readers   r;   	iter_syncz.BaseQueryBuilder.to_batches.<locals>.iter_sync  sZ      =(<#9#9#;#;<<<<<=%   s   */ 
==)r   r  rn  r  r8   r  r  r  )rc   r  r  r  r  s       @r;   r  zBaseQueryBuilder.to_batches  sl    , xK""4Dg"VV
 
	 	 	 	 	 #001DiikkRRRr=   r  c                Z    t          j        | j                            |                    S )r  )r   r  rn  r  r  s     r;   r  zBaseQueryBuilder.to_arrow%  s$     x,,W55666r=   r  c                Z    t          j        | j                            |                    S )r  )r   r  rn  r  r  s     r;   r  zBaseQueryBuilder.to_list6  s$     x++G44555r=   r  r  r   c                N    t          j         | j        j        ||fi |          S )r  )r   r  rn  r  r  s       r;   r  zBaseQueryBuilder.to_pandasG  s/    R x--gwII&IIJJJr=   r'  c                Z    t          j        | j                            |                    S )r  )r   r  rn  r.  r  s     r;   r.  zBaseQueryBuilder.to_polarsr  s%    @ x--g66777r=   Fr?  r   c                Z    t          j        | j                            |                    S )r  )r   r  rn  rF  rE  s     r;   rF  zBaseQueryBuilder.explain_plan  s$    < x0099:::r=   c                X    t          j        | j                                                  S )rc  )r   r  rn  rL  rb   s    r;   rL  zBaseQueryBuilder.analyze_plan  s"     x0022333r=   )rj  ri  re  r  r  r  )r  r   r  r  r0   r  r~   r\  r^  r  r[  r_  rb  r  )rE   rF   rG   r   r   rD  r   r   r  r  r  r  r  r.  rF  rL  rI   r=   r;   r
  r
    sP           - - - -   >   5 5 5 5 +/'+	!S !S !S !S !S !SF7 7 7 7 7"6 6 6 6 6& /3'+)K )K )K )K )KZ (, 8  8  8  8  8D; ; ; ; ;@4 4 4 4 4r=   r
  c                  $     e Zd ZdZd fdZ xZS )LanceTakeQueryBuilderr  rj  r  c                J    t                                          |           d S r~   r  r  s     r;   r   zLanceTakeQueryBuilder.__init__  r  r=   )rj  r  r  r  s   @r;   r  r    r  r=   r  )r/   r
   r0   r1   )q
__future__r   r  abcr   r   concurrent.futuresr   datetimer   enumr   typingr	   r
   r   r   r   r   r   r   r   r   rf  numpyr   pyarrowr8   pyarrow.computecomputer  r   typing_extensionsr   lancedb._lancedbr   lancedb.background_loopr   lancedb.pydanticr    r   arrowr   dependenciesr   pdr  r   rerankers.baser   rerankers.rrfr   rerankers.utilr   utilr    sysPILr*  r-  _lancedbr!   r  r"   r  r#   r$   r  r%   r  r&   r  commonr'   r(   r   r)   version_infor,   r-   r<   	BaseModelr?   r@   rK   rW   r[   dataclasses	dataclassr`   rr   r   r   r   rj   r   r   r   r   r   r   objectri  r  r  r  r  r  r  r  r
  r  rI   r=   r;   <module>r?     s   # " " " " "  # # # # # # # # 1 1 1 1 1 1                                                       ' ' ' ' ' ' . . . . . . ( ( ( ( ( ( - - - - - -       ) ) ) ) ) ) & & & & & &       $ $ $ $ $ $ & & & & & & 1 1 1 1 1 1 ! ! ! ! ! ! +JJJJJJ333333999999((((((------555555999999$$$$$$
7""******GC|$$$   6    X'       T       sD   
    C    
=K =K =K =K =KC =K =K  =K@ 
*' *' *' *' *' *' *'  *'Z 
. . . . .- . .  .( 
' ' ' ' ' ' '  ', 
- - - - -m - -  -> 
) ) ) ) )= ) )  )$% % % % %(, % % %$O9 O9 O9 O9 O9H O9 O9 O9d_" _" _" _" _" _" _" _"DN N N N N/ N N Nbu u u u u, u u up%E %E %E %E %E. %E %E %EP\+ \+ \+ \+ \+/ \+ \+ \+~e0 e0 e0 e0 e0V e0 e0 e0P	r r r r r r r rjCL CL CL CL CL# CL CL CLLfR fR fR fR fR& fR fR fRRk k k k k k k k\PR PR PR PR PR)+? PR PR PRfS" S" S" S" S")+? S" S" S"l         ^      r4 r4 r4 r4 r4v r4 r4 r4j         ,          r=   