b؉bddlZddlZddlmZmZmZddlmZddlm Z ddl m Z ddl m Z mZmZdd lmZdd lmZdd lmZdd lmZd ZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*d Z+d!Z,d"Z-d#Z.d$Z/d%Z0d&Z1d'Z2d(Z3d)Z4d*Z5d+Z6d,Z7d-Z8d.Z9d/Z:d0Z;d1Zd4Z?d5Z@d6ZAGd7d8ZBGd9d:eBZCy);N)DictOptionalUnion)Pipeline) parse_to_dict) to_string)AggregateRequestAggregateResultCursor)Document)Query)Result)SuggestionParserNUMERICz FT.CREATEzFT.ALTERz FT.SEARCHzFT.ADDz FT.ADDHASHzFT.DROPz FT.EXPLAINz FT.EXPLAINCLIzFT.DELz FT.AGGREGATEz FT.PROFILEz FT.CURSORz FT.SPELLCHECKz FT.DICTADDz FT.DICTDELz FT.DICTDUMPzFT.GETzFT.MGETz FT.CONFIGz FT.TAGVALSz FT.ALIASADDzFT.ALIASUPDATEz FT.ALIASDELzFT.INFOz FT.SUGADDz FT.SUGDELz FT.SUGLENz FT.SUGGETz FT.SYNUPDATEz FT.SYNDUMP NOOFFSETSNOFIELDSNOHLNOFREQS MAXTEXTFIELDS TEMPORARY STOPWORDSSKIPINITIALSCAN WITHSCORESFUZZY WITHPAYLOADSc JeZdZdZd*dZ d+dZdZd,dZ d-dZ d.dZ d/d Z d0d Z d1d Z d Z d ZdZdeeeeeeeffdffdZdeeeeeefffdZ d2deeefdeeeeeefffdZ d2deeefdeeeeeefffdZdeeeffdZ d2deeefdeeeeeefffdZdZ d3deeeefdedeeeeeeefffdZ d4dZ!dZ"dZ#dZ$dZ%dZ&d Z'd!Z(d"Z)d#Z*d$Z+d%Z,d&Z- d5d'Z.d,d(Z/d)Z0y)6SearchCommandszSearch commands.c(|j||S)zT Create a new batch indexer from the client with a given chunk size ) chunk_size) BatchIndexer)selfr!s @/usr/lib/python3/dist-packages/redis/commands/search/commands.py batch_indexerzSearchCommands.batch_indexer@s  * ==Nc 6t|jg} || |jz } |r| jt|6t |t r&| jt| j||r| jt|r| jt|r| jt| r| jt| r| jt|Kt |tttfr0| t t#|gz } t#|dkDr| t|z } | jd | tt%j&d|Dz } |j,| S#t($r| |j+z } Y-wxYw)a Create the search index. The index must not already exist. ### Parameters: - **fields**: a list of TextField or NumericField objects - **no_term_offsets**: If true, we will not save term offsets in the index - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty - **max_text_fields**: If true, we will encode indexes as if there were more than 32 text fields which allows you to add additional fields (beyond 32). - **temporary**: Create a lightweight temporary index which will expire after the specified period of inactivity (in seconds). The internal idle timer is reset whenever the index is searched or added to. - **no_highlight**: If true, disabling highlighting support. Also implied by no_term_offsets. - **no_term_frequencies**: If true, we avoid saving the term frequencies in the index. - **skip_initial_scan**: If true, we do not scan and index. For more information see `FT.CREATE `_. rSCHEMAc3<K|]}|jywN redis_args.0fs r$ z.SearchCommands.create_index..*Ja1<<>*J) CREATE_CMD index_nameargsappendr isinstanceintrrrrrrlisttuplesetrlen itertoolschain TypeErrorr,execute_command) r#fieldsno_term_offsetsno_field_flags stopwords definitionmax_text_fields temporary no_highlightno_term_frequenciesskip_initial_scanr5s r$ create_indexzSearchCommands.create_indexFsSPDOO,  ! JOO #D  KK &  Z 3%? KK " KK "  KK "  KK   KK !  KK  KK (  Z D%;M%N YI/ /D9~!Y' H ( D*J6*JKL LD$t##T** ( F%%' 'D (s%E99FFct|jddg} |ttjd|Dz }|j|S#t $r||j z }Y-wxYw)a Alter the existing search index by adding new fields. The index must already exist. ### Parameters: - **fields**: a list of Field objects to add for the index For more information see `FT.ALTER `_. r(ADDc3<K|]}|jywr*r+r-s r$r0z2SearchCommands.alter_schema_add..r1r2) ALTER_CMDr4r9r=r>r?r,r@)r#rAr5s r$alter_schema_addzSearchCommands.alter_schema_addsr4??He< ( D*J6*JKL LD$t##T** ( F%%' 'D (s%A A)(A)cP|rdnd}|jt|j|S)ai Drop the index if it exists. Replaced `drop_index` in RediSearch 2.0. Default behavior was changed to not delete the indexed documents. ### Parameters: - **delete_documents**: If `True`, all documents will be deleted. For more information see `FT.DROPINDEX `_. KEEPDOCS)r@DROP_CMDr4)r#delete_documentskeep_strs r$ dropindexzSearchCommands.dropindexs&*2z##HdooxHHr&c  |s| rd}t|j||g} |r| jd|"| jd| j||r7| jd|r| jd| r| jd|r| d|gz } | jd| tt j | j z } ||j| S|j| S) zS Internal add_document used for both batch and single doc indexing TNOSAVEPAYLOADREPLACEPARTIALNOCREATELANGUAGEFIELDS)ADD_CMDr4r6r9r=r>itemsr@) r#doc_idconnnosavescorepayloadreplacepartiallanguage no_createrAr5s r$ _add_documentzSearchCommands._add_documents" iG&%8  KK !   KK " KK  KK " I& J'  Z* *D H Y__flln566  '4''. .#t##T**r&ct|j||g}|r|jd|r|d|gz }||j|S|j|S)zX Internal add_document_hash used for both batch and single doc indexing r[r^) ADDHASH_CMDr4r6r@)r#rbrcrerirgr5s r$_add_document_hashz!SearchCommands._add_document_hashscT__fe<  KK "  Z* *D  '4''. .#t##T**r&c :|j|fd|||||||d| S)a Add a single document to the index. ### Parameters - **doc_id**: the id of the saved document. - **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids. - **score**: the document ranking, between 0.0 and 1.0 - **payload**: optional inner-index payload we can save for fast i access in scoring functions - **replace**: if True, and the document already is in the index, we perform an update and reindex the document - **partial**: if True, the fields specified will be added to the existing document. This has the added benefit that any fields specified with `no_index` will not be reindexed again. Implies `replace` - **language**: Specify the language used for document tokenization. - **no_create**: if True, the document is only updated and reindexed if it already exists. If the document does not exist, an error will be returned. Implies `replace` - **fields** kwargs dictionary of the document fields to be saved and/or indexed. NOTE: Geo points shoule be encoded as strings of "lon,lat" N)rcrdrerfrgrhrirj)rk) r#rbrdrerfrgrhrirjrAs r$ add_documentzSearchCommands.add_documentsDP"t!!       r&c.|j|d|||S)a Add a hash document to the index. ### Parameters - **doc_id**: the document's id. This has to be an existing HASH key in Redis that will hold the fields the index needs. - **score**: the document ranking, between 0.0 and 1.0 - **replace**: if True, and the document already is in the index, we perform an update and reindex the document - **language**: Specify the language used for document tokenization. N)rcrerirg)rn)r#rbrerirgs r$add_document_hashz SearchCommands.add_document_hash#s'&& UXw'  r&ct|j|g}|r|jd||j|S|j|S)a Delete a document from index Returns 1 if the document was deleted, 0 if not ### Parameters - **delete_actual_document**: if set to True, RediSearch also delete the actual document if it is in the index DD)DEL_CMDr4r6r@)r#rbrcdelete_actual_documentr5s r$delete_documentzSearchCommands.delete_document4sO&1 ! KK   '4''. .#t##T**r&c|jj|}|jDcic]\}}t|t|}}}|} |d=t dd|i|Scc}}w#t$rYwxYw). Load a single document by id idclienthgetallrar KeyErrorrr#rzrAkvf2s r$ load_documentzSearchCommands.load_documentGs$$R(5;\\^ DTQilIaL( D D t (2(((E    sA$A** A65A6cF|jt|jg|S)z Returns the full contents of multiple documents. ### Parameters - **ids**: the ids of the saved documents. )r@MGET_CMDr4)r#idss r$getzSearchCommands.getVs"$t##HdooDDDr&c|jt|j}tt|}t t ||S) Get info an stats about the the current index, including the number of documents, memory consumption, etc For more information see `FT.INFO `_. r@INFO_CMDr4mapr dictzipr#resits r$infozSearchCommands.infobs7""8T__= C CBK  r& query_paramsc|gSg}t|dkDrh|jd|jt|dz|jD]'\}}|j||j|)|S)Nrparamsr)r<r6ra)r#rr5keyvalues r$get_params_argszSearchCommands.get_params_argsns~  I | q KK ! KKL)A- .*002 # U C  E" # r&c|jg}t|tr t|}t|tst dt |||j z }||j|z }||fS)NzBad query type )r4r7strr ValueErrortypeget_argsr)r#queryrr5s r$_mk_query_argszSearchCommands._mk_query_args|sq  eS !%LE%'tE{m<= =    $$\22U{r&rc6|j||\}}tj}|jtg|}t |t r|St ||j tj|z dz|j|jS) Search the index for a given query, and return a result of documents ### Parameters - **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries. See RediSearch's documentation on query format For more information see `FT.SEARCH `_. r@@duration has_payload with_scores rtimer@ SEARCH_CMDr7rr _no_content_with_payloads _with_scoresr#rrr5strs r$searchzSearchCommands.searchs ))%l)K e YY["d"":55 c8 $J !! !iikB&&0,,**   r&c\|j||\}}|jtg|S)zReturns the execution plan for a complex query. For more information see `FT.EXPLAIN `_. r)rr@ EXPLAIN_CMD)r#rrr5 query_texts r$explainzSearchCommands.explains6 ..u<.Pj#t##K7$77r&ctd)Nz#EXPLAINCLI will not be implemented.)NotImplementedError)r#rs r$ explain_clizSearchCommands.explain_clis!"GHHr&ct|tr9t|j}t|j g|j z}nCt|tr'd}td|j g|j z}n td|||j|z }|j|}|j|||S) Issue an aggregation query. ### Parameters **query**: This can be either an `AggregateRequest`, or a `Cursor` An `AggregateResult` object is returned. You can access the rows from its `rows` property, which will always yield the rows of the result. For more information see `FT.AGGREGATE `_. TREAD Bad query r7r bool_cursor AGGREGATE_CMDr4 build_argsr CURSOR_CMDrrr@_get_aggregate_resultr#rr has_cursorcmdraws r$ aggregatezSearchCommands.aggregates" e- .emm,J $//2U5E5E5GGC v &Jvt7%:J:J:LLC[%0 0 t##L11"d""C())#ujAAr&c|r1t|tr |d|_|}nt|d}|d}nd}t|tr|jr |d}|dd}nd}|dd}t |||S)Nr rr)r7r cidr _with_schemar )r#rrrcursorschemarowss r$rz$SearchCommands._get_aggregate_results %(F Aa&CF e- .53E3EVFqr7DFqr7DtVV44r&limitedctj}t|jdg}|r|jd|jdt |t rd|d<||j z }nHt |tr-d|d<||jz }||j|z }n td|j|}t |t r!|j|d||j}nJt|d|j tj|z d z|j |j" }|t%|d fS) a Performs a search or aggregate command and collects performance information. ### Parameters **query**: This can be either an `AggregateRequest`, `Query` or string. **limited**: If set to True, removes details of reader iterator. **query_params**: Define one or more value parameters. Each parameter has a name and a value. rRLIMITEDQUERY AGGREGATErSEARCHz5Must provide AggregateRequest object or Query object.rrrr )r PROFILE_CMDr4r6r7r rrrrrr@rrrrrrr)r#rrrrrrresults r$profilezSearchCommands.profiles7$YY[DOOR0  JJy ! 7 e- . CF 5##% %C u %CF 5>># #C 4'' 5 5CWX X"d""C( e- .//Au}}MFA%%%))+*f4!00!.. F}SV,,,r&ct|j|g}|r|jd|g|r|jdd|g|r|jdd|g|j|}i}|dk(r|S|D]X}t |t r|dk(rt |dk7r(|ds.|dds7|dD cgc] } | d| dd c} ||d<Z|Scc} w)  Issue a spellcheck query ### Parameters **query**: search query. **distance***: the maximal Levenshtein distance for spelling suggestions (default: 1, max: 4). **include**: specifies an inclusion custom dictionary. **exclude**: specifies an exclusion custom dictionary. For more information see `FT.SPELLCHECK `_. DISTANCETERMSINCLUDEEXCLUDErrr re suggestionSPELLCHECK_CMDr4extendr@r7r8r< r#rdistanceincludeexcluderr corrections _correction_items r$ spellcheckzSearchCommands.spellcheckst6  JJ H- .  JJG4 5  JJG4 5"d""C( !8  K+s+ q0@;1$q>q>!$$JUUV+@E%(%(;+K A '5 < +s-C cRt|g}|j||j|S)zAdds terms to a dictionary. ### Parameters - **name**: Dictionary name. - **terms**: List of items for adding to the dictionary. For more information see `FT.DICTADD `_. ) DICT_ADD_CMDrr@r#nametermsrs r$dict_addzSearchCommands.dict_addY-T" 5#t##S))r&cRt|g}|j||j|S)aDeletes terms from a dictionary. ### Parameters - **name**: Dictionary name. - **terms**: List of items for removing from the dictionary. For more information see `FT.DICTDEL `_. ) DICT_DEL_CMDrr@rs r$dict_delzSearchCommands.dict_delgrr&c0t|g}|j|S)zDumps all terms in the given dictionary. ### Parameters - **name**: Dictionary name. For more information see `FT.DICTDUMP `_. ) DICT_DUMP_CMDr@)r#rrs r$ dict_dumpzSearchCommands.dict_dumpus!d##t##S))r&c>td||g}|j|}|dk(S)Set runtime configuration option. ### Parameters - **option**: the name of the configuration option. - **value**: a value for the configuration option. For more information see `FT.CONFIG SET `_. SETOK CONFIG_CMDr@r#optionrrrs r$ config_setzSearchCommands.config_sets.5&%0"d""C(d{r&cbtd|g}i}|j|}|r|D] }|d||d<|S)Get runtime configuration option value. ### Parameters - **option**: the name of the configuration option. For more information see `FT.CONFIG GET `_. GETr rrr#rrrrkvss r$ config_getzSearchCommands.config_getsO5&)"d""C(  %!!fCF  % r&cD|jt|j|S)z Return a list of all possible tag values ### Parameters - **tagfield**: Tag field name For more information see `FT.TAGVALS `_. )r@ TAGVALS_CMDr4)r#tagfields r$tagvalszSearchCommands.tagvalss##K(KKr&cD|jt||jS)z Alias a search index - will fail if alias already exists ### Parameters - **alias**: Name of the alias to create For more information see `FT.ALIASADD `_. )r@ ALIAS_ADD_CMDr4r#aliass r$aliasaddzSearchCommands.aliasadds##M5$//JJr&cD|jt||jS)z Updates an alias - will fail if alias does not already exist ### Parameters - **alias**: Name of the alias to create For more information see `FT.ALIASUPDATE `_. )r@ALIAS_UPDATE_CMDr4rs r$ aliasupdatezSearchCommands.aliasupdates##$4eT__MMr&c.|jt|S)z Removes an alias to a search index ### Parameters - **alias**: Name of the alias to delete For more information see `FT.ALIASDEL `_. )r@ ALIAS_DEL_CMDrs r$aliasdelzSearchCommands.aliasdels##M599r&ch|jd}|D]}t||j|jg}|j dr|j d|j r,|j d|j |j |j||jdS)aJ Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string. If kwargs["increment"] is true and the terms are already in the server's dictionary, we increment their scores. For more information see `FT.SUGADD `_. F transaction incrementINCRrZ pipelineSUGADD_COMMANDstringrerr6rfr@executer#r suggestionskwargspipesugr5s r$sugaddzSearchCommands.sugadds}}}/ (C"CSYY?Dzz+& F#{{ I& CKK( D $ ' (||~b!!r&c.|jt|S)z Return the number of entries in the AutoCompleter index. For more information see `FT.SUGLEN `_. )r@SUGLEN_COMMAND)r#rs r$suglenzSearchCommands.suglens ##NC88r&c0|jt||S)z Delete a string from the AutoCompleter index. Returns 1 if the string was found and deleted, 0 otherwise. For more information see `FT.SUGDEL `_. )r@SUGDEL_COMMAND)r#rr s r$sugdelzSearchCommands.sugdels##NC@@r&ct||d|g}|r|jt|r|jt|r|jt|j |}g} |s| St |||} | D cgc]} | c} Scc} w)t Get a list of suggestions from the AutoCompleter, for a given prefix. Parameters: prefix : str The prefix we are searching. **Must be valid ascii or utf-8** fuzzy : bool If set to true, the prefix search is done in fuzzy mode. **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index. with_scores : bool If set to true, we also return the (refactored) score of each suggestion. This is normally not needed, and is NOT the original score inserted into the index. with_payloads : bool Return suggestion payloads num : int The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions. Returns: list: A list of Suggestion objects. If with_scores was False, the score of all suggestions is 1. For more information see `FT.SUGGET `_. MAXSUGGET_COMMANDr6rrrr@r r#rprefixfuzzynumr with_payloadsr5retresultsparserss r$suggetzSearchCommands.suggetsDVUC8  KK   KK #  KK %"d""D)N!+}cB!"a"""s7 Bct|j|g}|r|jdg|j||j|S)a Updates a synonym group. The command is used to create or update a synonym group with additional terms. Only documents which were indexed after the update will be affected. Parameters: groupid : Synonym group id. skipinitial : bool If set to true, we do not scan and index. terms : The terms. For more information see `FT.SYNUPDATE `_. r) SYNUPDATE_CMDr4rr@)r#groupid skipinitialrrs r$ synupdatezSearchCommands.synupdate-sF$doow7  JJ)* + 5#t##S))r&c|jt|j}tdt |dDcic]}||||dzc}Scc}w)a Dumps the contents of a synonym group. The command is used to dump the synonyms data structure. Returns a list of synonym terms and their synonym group ids. For more information see `FT.SYNDUMP `_. rrr )r@ SYNDUMP_CMDr4ranger<)r#ris r$syndumpzSearchCommands.syndumpEsL"";@,1!SXq,ABqAAE "BBBsA)d) FFNNFNFFF)F)NF?NFFNF)NrHNF)FrHNFFNF)rHNF)NFr*)FNNNNF FF)1__name__ __module__ __qualname____doc__r%rKrPrWrkrnrprrrwrrrrrrr8floatrrrrrrrrr rrrrrrrrrr rrrr'r*r-r<rArFr{r&r$rr=sf>!E+N+( I$(+VDI+.3 j "+& ) E ! !$sE#sE/,B'B"CT"IJ  $sE#sE/q>!$JUUV+@E%(%(;+K A ' +/"+s%A'C)C*A C7C CCcZKtd||g}|j|d{}|dk(S7 w)rrNrrrs r$rzAsyncSearchCommands.config_sets:5&%0(D((#..d{/s +) +c~Ktd|g}i}|j|d{}|r|D] }|d||d<|S7w)rrNr rrrs r$rzAsyncSearchCommands.config_gets[5&)(D((#..  %!!fCF  % /s =;=cK|jj|d{}|jDcic]\}}t|t|}}}|} |d=t dd|i|S7Lcc}}w#t$rY wxYww)ryNrzr{r|rs r$rz!AsyncSearchCommands.load_documents{{**2..5;\\^ DTQilIaL( D D t (2(((/ D    sDBA.BA0BA6!B0B6 B?BBBcK|jd}|D]}t||j|jg}|j dr|j d|j r,|j d|j |j |j||jd{dS7w)aI Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string. If kwargs["increment"] is true and the terms are already in the server's dictionary, we increment their scores. For more information see `FT.SUGADD `_. FrrrrZNrrr"s r$r'zAsyncSearchCommands.sugadds}}}/ (C"CSYY?Dzz+& F#{{ I& CKK( D $ ' (lln$b))$sB4C6B>7Cc,Kt||d|g}|r|jt|r|jt|r|jt|j |d{}g} |s| St |||} | D cgc]} | c} S7'cc} ww)r/r0Nr1r3s r$r<zAsyncSearchCommands.suggetsDVUC8  KK   KK #  KK %(D(($//N!+}cB!"a"" 0 #s$A#B%B &B B BBr*rIrJ)rLrMrNrrrrrr8rPrrrrrrr'r<r{r&r$rRrRRs !;? S%Z  3c3o 667 D;?BS%Z B3c3o 667B<-^ " )*0RW0#r&rR)Dr=rtypingrrr redis.clientrhelpersr_utilr aggregationr r r documentrrrrrrrrr3rOrr`rmrTrEXPLAINCLI_CMDrurrrrrrrGET_CMDrrr r rrrrr,r)r2r>rCrrrrrrrrrrrrrRr{r&r$rds ((!#BB(                     #         #   R CR Cjn#.n#r&