o
    ¾¿iÖ3  ã                   @   s$  d dl mZ d dlmZmZmZmZmZ d dlm	Z	 zd dlm
Z
 W n ey1   d dlm
Z
 Y nw d dlmZmZ d dlmZmZ e	G dd„ dƒƒZG d	d
„ d
eƒZe	G dd„ dƒƒZG dd„ dƒZG dd„ deƒZe	G dd„ dƒƒZe	G dd„ dƒƒZe	G dd„ deƒƒZe	G dd„ dƒƒZdS )é    )ÚEnum)ÚAnyÚDictÚListÚOptionalÚUnion)Úexperimental)ÚSelf)ÚLimitÚReducer)ÚFilterÚSortbyFieldc                	   @   sx   e Zd Z		ddedee dee ddfdd„Zdefdd	„Zdedd fd
d„Zdedd fdd„Zde	e fdd„Z
dS )ÚHybridSearchQueryNÚquery_stringÚscorerÚyield_score_asÚreturnc                 C   s   || _ || _|| _dS )aB  
        Create a new hybrid search query object.

        Args:
            query_string: The query string.
            scorer: Scoring algorithm for text search query.
                Allowed values are "TFIDF", "TFIDF.DOCNORM", "DISMAX", "DOCSCORE",
                "BM25", "BM25STD", "BM25STD.TANH", "HAMMING", etc.
                For more information about supported scoring algorithms, see
                https://redis.io/docs/latest/develop/ai/search-and-query/advanced-concepts/scoring/
            yield_score_as: The name of the field to yield the score as.
        N)Ú_query_stringÚ_scorerÚ_yield_score_as)Úselfr   r   r   © r   úV/home/ubuntu/.local/lib/python3.10/site-packages/redis/commands/search/hybrid_query.pyÚ__init__   s   
zHybridSearchQuery.__init__c                 C   ó   | j S )z-Return the query string of this query object.)r   ©r   r   r   r   r   '   ó   zHybridSearchQuery.query_stringc                 C   ó
   || _ | S )ab  
        Scoring algorithm for text search query.
        Allowed values are "TFIDF", "TFIDF.DOCNORM", "DISMAX", "DOCSCORE", "BM25",
        "BM25STD", "BM25STD.TANH", "HAMMING", etc.

        For more information about supported scoring algorithms,
        see https://redis.io/docs/latest/develop/ai/search-and-query/advanced-concepts/scoring/
        )r   )r   r   r   r   r   r   +   ó   	zHybridSearchQuery.scorerÚaliasc                 C   r   )z-
        Yield the score as a field.
        ©r   ©r   r   r   r   r   r   7   ó   z HybridSearchQuery.yield_score_asc                 C   s:   d| j g}| jr| d| jf¡ | jr| d| jf¡ |S )NÚSEARCHÚSCORERÚYIELD_SCORE_AS)r   r   Úextendr   ©r   Úargsr   r   r   Úget_args>   s   
zHybridSearchQuery.get_args)NN)Ú__name__Ú
__module__Ú__qualname__Ústrr   r   r   r   r   r   r)   r   r   r   r   r      s     üþýü
ûr   c                   @   ó   e Zd ZdZdZdS )ÚVectorSearchMethodsÚKNNÚRANGEN)r*   r+   r,   r0   r1   r   r   r   r   r/   G   ó    r/   c                   @   sÀ   e Zd Z				ddedeeef dee deeee	f  ded dee d	dfd
d„Z
d	efdd„Zd	eeef fdd„Zded	d fdd„Zddd„Zded	d fdd„Zd	ee fdd„ZdS )ÚHybridVsimQueryNÚvector_field_nameÚvector_dataÚvsim_search_methodÚvsim_search_method_paramsÚfilterr   r   r   c                 C   s>   || _ || _|r|r| j|fi |¤Ž nd| _|| _|| _dS )a5  
        Create a new hybrid vsim query object.

        Args:
            vector_field_name: Vector field name.

            vector_data: Vector data for the search.

            vsim_search_method: Search method that will be used for the vsim search.

            vsim_search_method_params: Search method parameters. Use the param names
                for keys and the values for the values.
                Example for KNN: {"K": 10, "EF_RUNTIME": 100}
                                    where K is mandatory and defines the number of results
                                    and EF_RUNTIME is optional and definesthe exploration factor.
                Example for RANGE: {"RADIUS": 10, "EPSILON": 0.1}
                                    where RADIUS is mandatory and defines the radius of the search
                                    and EPSILON is optional and defines the accuracy of the search.
            yield_score_as: The name of the field to yield the score as.

            filter: If defined, a filter will be applied on the vsim query results.
        N)Ú_vector_fieldÚ_vector_dataÚvsim_method_paramsÚ_vsim_method_paramsÚ_filterr   )r   r4   r5   r6   r7   r8   r   r   r   r   r   N   s   
zHybridVsimQuery.__init__c                 C   r   )z2Return the vector field name of this query object.)r9   r   r   r   r   Úvector_fieldv   r   zHybridVsimQuery.vector_fieldc                 C   r   )z,Return the vector data of this query object.)r:   r   r   r   r   r5   z   r   zHybridVsimQuery.vector_dataÚmethodc                 K   sL   |j g}|r!| t| ¡ ƒd ¡ | ¡ D ]\}}| ||f¡ q|| _| S )aB  
        Add search method parameters to the query.

        Args:
            method: Vector search method name. Supported values are "KNN" or "RANGE".
            kwargs: Search method parameters. Use the param names for keys and the
                values for the values. Example: {"K": 10, "EF_RUNTIME": 100}.
        é   )ÚvalueÚappendÚlenÚitemsr&   r<   )r   r?   Úkwargsr;   ÚkeyrA   r   r   r   r;   ~   s   z"HybridVsimQuery.vsim_method_paramsÚfltÚHybridFilterc                 C   r   )z‚
        Add a filter to the query.

        Args:
            flt: A HybridFilter object, used on a corresponding field.
        ©r=   )r   rG   r   r   r   r8   ”   s   zHybridVsimQuery.filterr   c                 C   r   )z@
        Return the score as a field with name `alias`.
        r    r!   r   r   r   r   ž   r"   zHybridVsimQuery.yield_score_asc                 C   sN   d| j | jg}| jr| | j¡ | jr| | jj¡ | jr%| d| jf¡ |S )NÚVSIMr%   )r9   r:   r<   r&   r=   r(   r   r'   r   r   r   r)   ¥   s   zHybridVsimQuery.get_args)NNNN)rG   rH   r   r3   )r*   r+   r,   r-   r   Úbytesr   r/   r   r   r   r>   r5   r;   r8   r   r   r)   r   r   r   r   r3   L   s<    ùþ
ýüûúù
ø(þ
ü

r3   c                   @   s4   e Zd Zdededdfdd„Zdee fdd„ZdS )	ÚHybridQueryÚsearch_queryÚvector_similarity_queryr   Nc                 C   ó   || _ || _dS )zô
        Create a new hybrid query object.

        Args:
            search_query: HybridSearchQuery object containing the text query.
            vector_similarity_query: HybridVsimQuery object containing the vector similarity query.
        N)Ú_search_queryÚ_vector_similarity_query)r   rM   rN   r   r   r   r   ²   s   
zHybridQuery.__init__c                 C   s(   g }|  | j ¡ ¡ |  | j ¡ ¡ |S )N)r&   rP   r)   rQ   r'   r   r   r   r)   Á   s   zHybridQuery.get_args)	r*   r+   r,   r   r3   r   r   r-   r)   r   r   r   r   rL   ±   s    þý
ürL   c                   @   r.   )ÚCombinationMethodsÚRRFÚLINEARN)r*   r+   r,   rS   rT   r   r   r   r   rR   È   r2   rR   c                   @   s8   e Zd Zdeddfdd„Zdeeeef  fdd„Z	dS )ÚCombineResultsMethodr?   r   Nc                 K   rO   )aý  
        Create a new combine results method object.

        Args:
            method: The combine method to use - RRF or LINEAR.
            kwargs: Additional combine parameters.
                    For RRF, the following parameters are supported(at least one should be provided):
                                WINDOW: Limits fusion scopeLimits fusion scope.
                                CONSTANT: Controls decay of rank influence.
                                YIELD_SCORE_AS: The name of the field to yield the calculated score as.
                    For LINEAR, supported parameters (at least one should be provided):
                                ALPHA: The weight of the first query.
                                BETA: The weight of the second query.
                                YIELD_SCORE_AS: The name of the field to yield the calculated score as.

                    The additional parameters are not validated and are passed as is to the server.
                    The supported format is to provide the parameter names and values like the following:
                        CombineResultsMethod(CombinationMethods.RRF, WINDOW=3, CONSTANT=0.5)
                        CombineResultsMethod(CombinationMethods.LINEAR, ALPHA=0.5, BETA=0.5)
        N)Ú_methodÚ_kwargs)r   r?   rE   r   r   r   r   Ï   s   
zCombineResultsMethod.__init__c                 C   sP   d| j jg}| jr&| t| j ¡ ƒd ¡ | j ¡ D ]\}}| ||f¡ q|S )NÚCOMBINEr@   )rV   rA   rW   rB   rC   rD   r&   )r   r(   rF   rA   r   r   r   r)   ç   s   zCombineResultsMethod.get_args)
r*   r+   r,   rR   r   r   r   r-   Úintr)   r   r   r   r   rU   Í   s    rU   c                   @   sœ   e Zd Zddd„Zdedefdd„Zdee dedefd	d
„Z	defdd„Z
dddefdd„Zdddefdd„Zdededefdd„Zdee fdd„ZdS )ÚHybridPostProcessingConfigr   Nc                 C   s(   g | _ g | _g | _g | _d| _d| _dS )zK
        Create a new hybrid post processing configuration object.
        N)Ú_load_statementsÚ_apply_statementsÚ_groupby_statementsÚ_sortby_fieldsr=   Ú_limitr   r   r   r   r   ò   s   
z#HybridPostProcessingConfig.__init__Úfieldsc                 G   s6   |rd  |¡}| d¡}| j dt|ƒg|¢R ¡ | S )z=
        Add load statement parameters to the query.
        ú ÚLOAD)ÚjoinÚsplitr[   r&   rC   )r   r`   Ú
fields_strÚfields_listr   r   r   Úloadý   s
   

zHybridPostProcessingConfig.loadÚreducersc                 G   s„   t |tƒr|gn|}dtt|ƒƒg|¢}|D ]#}| d|jtt|jƒƒf¡ | |j¡ |jdur9| d|jf¡ q| j |¡ | S )al  
        Specify by which fields to group the aggregation.

        Args:
            fields: Fields to group by. This can either be a single string or a list
                of strings. In both cases, the field should be specified as `@field`.
            reducers: One or more reducers. Reducers may be found in the
                `aggregation` module.
        ÚGROUPBYÚREDUCENÚAS)Ú
isinstancer-   rC   r&   ÚNAMEr(   Ú_aliasr]   )r   r`   rh   ÚretÚreducerr   r   r   Úgroup_by  s   
€z#HybridPostProcessingConfig.group_byc                 K   sN   g }|  ¡ D ]\}}d|g}|dur| d|f¡ | |¡ q| j |¡ | S )aO  
        Specify one or more projection expressions to add to each result.

        Args:
            kwexpr: One or more key-value pairs for a projection. The key is
                the alias for the projection, and the value is the projection
                expression itself, for example `apply(square_root="sqrt(@foo)")`.
        ÚAPPLYNrk   )rD   r&   r\   )r   ÚkwexprÚ
apply_argsr   Úexprro   r   r   r   Úapply  s   	z HybridPostProcessingConfig.applyÚsortbyr   c                 G   s   g |¢| _ | S )z5
        Add sortby parameters to the query.
        )r^   )r   rw   r   r   r   Úsort_by2  s   
z"HybridPostProcessingConfig.sort_byr8   rH   c                 C   r   )zí
        Add a numeric or string filter to the query.

        Currently, only one of each filter is supported by the engine.

        Args:
            filter: A NumericFilter or GeoFilter object, used on a corresponding field.
        rI   )r   r8   r   r   r   r8   9  r   z!HybridPostProcessingConfig.filterÚoffsetÚnumc                 C   s   t ||ƒ| _| S )z4
        Add limit parameters to the query.
        )r
   r_   )r   ry   rz   r   r   r   ÚlimitE  s   z HybridPostProcessingConfig.limitc                 C   s¢   g }| j r| | j ¡ | jr| | j¡ | jr| | j¡ | jr:g }| jD ]}| |j¡ q%| dt|ƒg|¢R ¡ | jrD| | jj¡ | jrO| | j 	¡ ¡ |S )NÚSORTBY)
r[   r&   r]   r\   r^   r(   rC   r=   r_   Ú
build_args)r   r(   Úsortby_argsÚfr   r   r   r}   L  s"   
z%HybridPostProcessingConfig.build_args)r   N)r*   r+   r,   r   r-   r	   rg   r   r   rq   rv   rx   r8   rY   r{   r}   r   r   r   r   rZ   ð   s    

rZ   c                   @   s   e Zd Zdeddfdd„ZdS )rH   Ú
conditionsr   Nc                 C   s   |g}t j| dg|¢R Ž  dS )zn
        Create a new hybrid filter object.

        Args:
            conditions: Filter conditions.
        ÚFILTERN)r   r   )r   r€   r(   r   r   r   r   c  s   
zHybridFilter.__init__)r*   r+   r,   r-   r   r   r   r   r   rH   a  s    þýrH   c                   @   s,   e Zd Zd
dededdfdd„Zdd	„ ZdS )ÚHybridCursorQueryr   ÚcountÚmax_idler   Nc                 C   rO   )zÆ
        Create a new hybrid cursor query object.

        Args:
            count: Number of results to return per cursor iteration.
            max_idle: Maximum idle time for the cursor.
        N)rƒ   r„   )r   rƒ   r„   r   r   r   r   s  s   
zHybridCursorQuery.__init__c                 C   s:   dg}| j r|dt| j ƒg7 }| jr|dt| jƒg7 }|S )NÚ
WITHCURSORÚCOUNTÚMAXIDLE)rƒ   r-   r„   r'   r   r   r   r}   ~  s   zHybridCursorQuery.build_args)r   r   )r*   r+   r,   rY   r   r}   r   r   r   r   r‚   q  s    r‚   N)Úenumr   Útypingr   r   r   r   r   Úredis.utilsr   r	   ÚImportErrorÚtyping_extensionsÚ!redis.commands.search.aggregationr
   r   Úredis.commands.search.queryr   r   r   r/   r3   rL   rR   rU   rZ   rH   r‚   r   r   r   r   Ú<module>   s2    ÿ7d"p