
    =wgУ                        d dl m Z  d dlmZ d dlmZ d dlmZmZmZ  G d de      Z	 G d de      Z
 G d	 d
e	      Z G d de
      Z G d de      Z G d de
      Z G d de
      Z G d de	      Z G d de      Z G d de      Z G d de	      Z G d de	      Z G d de	      Z G d d e	      Z G d! d"e	      Z G d# d$e      Z G d% d&e      Z G d' d(e      Z G d) d*e      Z G d+ d,e      Z G d- d.e      Zd1d0Zy/)2    )array)defaultdict)string_type)	iteritemsizipxrangec                   (    e Zd ZdZdZd ZddZd Zy)	FacetTypezABase class for "facets", aspects that can be sorted/faceted.
    Nc                     t         )zReturns a :class:`Categorizer` corresponding to this facet.

        :param global_searcher: A parent searcher. You can use this searcher if
            you need global document ID references.
        NotImplementedErrorselfglobal_searchers     E/var/www/horilla/myenv/lib/python3.12/site-packages/whoosh/sorting.pycategorizerzFacetType.categorizer+   
     "!    c                 n    | j                   }||}|
t               S t        |      t        u r |       S |S N)maptypeOrderedListtype)r   defaultts      r   mapzFacetType.map4   s9    LL9A9= !W_3JHr   c                      y)Nfacet r   s    r   default_namezFacetType.default_name@   s    r   r   )__name__
__module____qualname____doc__r   r   r   r!   r   r   r   r
   r
   %   s     G"
r   r
   c                   0    e Zd ZdZdZdZd Zd Zd Zd Z	y)Categorizera  Base class for categorizer objects which compute a key value for a
    document based on certain criteria, for use in sorting/faceting.

    Categorizers are created by FacetType objects through the
    :meth:`FacetType.categorizer` method. The
    :class:`whoosh.searching.Searcher` object passed to the ``categorizer``
    method may be a composite searcher (that is, wrapping a multi-reader), but
    categorizers are always run **per-segment**, with segment-relative document
    numbers.

    The collector will call a categorizer's ``set_searcher`` method as it
    searches each segment to let the cateogorizer set up whatever segment-
    specific data it needs.

    ``Collector.allow_overlap`` should be ``True`` if the caller can use the
    ``keys_for`` method instead of ``key_for`` to group documents into
    potentially overlapping groups. The default is ``False``.

    If a categorizer subclass can categorize the document using only the
    document number, it should set ``Collector.needs_current`` to ``False``
    (this is the default) and NOT USE the given matcher in the ``key_for`` or
    ``keys_for`` methods, since in that case ``segment_docnum`` is not
    guaranteed to be consistent with the given matcher. If a categorizer
    subclass needs to access information on the matcher, it should set
    ``needs_current`` to ``True``. This will prevent the caller from using
    optimizations that might leave the matcher in an inconsistent state.
    Fc                      y)a[  Called by the collector when the collector moves to a new segment.
        The ``segment_searcher`` will be atomic. The ``docoffset`` is the
        offset of the segment's document numbers relative to the entire index.
        You can use the offset to get absolute index docnums by adding the
        offset to segment-relative docnums.
        Nr   r   segment_searcher	docoffsets      r   set_searcherzCategorizer.set_searcherd   s     	r   c                     t        | d      r| j                  |      S t        | d      r| j                  |      S t        | j                        )a  Returns a key for the current match.

        :param matcher: a :class:`whoosh.matching.Matcher` object. If
            ``self.needs_current`` is ``False``, DO NOT use this object,
            since it may be inconsistent. Use the given ``segment_docnum``
            instead.
        :param segment_docnum: the segment-relative document number of the
            current match.
        
key_for_idkey_for_matcher)hasattrr.   r/   r   	__class__r   matchersegment_docnums      r   key_forzCategorizer.key_forn   sH     4&??>22T,-''00!$..11r   c                 f    t        | d      r| j                  |      S t        | j                        )a  Yields a series of keys for the current match.

        This method will be called instead of ``key_for`` if
        ``self.allow_overlap`` is ``True``.

        :param matcher: a :class:`whoosh.matching.Matcher` object. If
            ``self.needs_current`` is ``False``, DO NOT use this object,
            since it may be inconsistent. Use the given ``segment_docnum``
            instead.
        :param segment_docnum: the segment-relative document number of the
            current match.
        keys_for_id)r0   r7   r   r1   r2   s      r   keys_forzCategorizer.keys_for   s.     4'##N33!$..11r   c                     |S )a  Returns a representation of the key to be used as a dictionary key
        in faceting. For example, the sorting key for date fields is a large
        integer; this method translates it into a ``datetime`` object to make
        the groupings clearer.
        r   r   keys     r   key_to_namezCategorizer.key_to_name   s	     
r   N)
r"   r#   r$   r%   allow_overlapneeds_currentr,   r5   r8   r<   r   r   r   r'   r'   D   s'    8 MM2&2(r   r'   c                   (    e Zd ZdZ	 	 ddZd Zd Zy)
FieldFaceta  Sorts/facets by the contents of a field.

    For example, to sort by the contents of the "path" field in reverse order,
    and facet by the contents of the "tag" field::

        paths = FieldFacet("path", reverse=True)
        tags = FieldFacet("tag")
        results = searcher.search(myquery, sortedby=paths, groupedby=tags)

    This facet returns different categorizers based on the field type.
    Nc                 <    || _         || _        || _        || _        y)aG  
        :param fieldname: the name of the field to sort/facet on.
        :param reverse: if True, when sorting, reverse the sort order of this
            facet.
        :param allow_overlap: if True, when grouping, allow documents to appear
            in multiple groups when they have multiple terms in the field.
        N)	fieldnamereverser=   r   )r   rB   rC   r=   r   s        r   __init__zFieldFacet.__init__   s!     #*r   c                     | j                   S r   rB   r    s    r   r!   zFieldFacet.default_name       ~~r   c                 n   | j                   }|j                  |   }| j                  rt        ||      S |j	                         j                  |      rK|j                  }|j                  s| j                  st        ||| j                        }|S t        ||      }|S t        ||| j                        }|S r   )rB   schemar=   OverlappingCategorizerreader
has_columncolumn_type
reversiblerC   ColumnCategorizerReversedColumnCategorizerPostingCategorizer)r   r   rB   fieldobjcoltypecs         r   r   zFieldFacet.categorizer   s     NN	")))4 )/9EE!!#..y9**G!!%oy$,,O 	 .oyI  #?I#'<<1Ar   )FFN)r"   r#   r$   r%   rD   r!   r   r   r   r   r@   r@      s     
 @Er   r@   c                   ,    e Zd ZddZd Zd Zd Zd Zy)rO   c                     || _         |j                  | j                      | _        | j                  j                  | _        || _        d | _        y r   )
_fieldnamerI   	_fieldobjrM   _column_type_reverse_creader)r   r   rB   rC   s       r   rD   zColumnCategorizer.__init__   sA    #(//@ NN66 r   c                     | j                   j                  d| j                  d| j                  d| j                  dS )N(, z
, reverse=))r1   r"   rX   rW   rZ   r    s    r   __repr__zColumnCategorizer.__repr__   s-    +/>>+B+B+/>>4??+/==: 	:r   c                 ~    |j                         }|j                  | j                  | j                  d      | _        y )NF)rC   	translate)rK   column_readerrW   rZ   r[   )r   r*   r+   rs       r   r,   zColumnCategorizer.set_searcher   s5    ##%0427 ( 9r   c                 8    | j                   j                  |      S r   )r[   sort_keyr2   s      r   r5   zColumnCategorizer.key_for   s    }}%%n55r   c                 8    | j                   j                  |      S r   )rX   from_column_valuer:   s     r   r<   zColumnCategorizer.key_to_name   s    ~~//44r   NF)r"   r#   r$   rD   r`   r,   r5   r<   r   r   r   rO   rO      s    :
965r   rO   c                   "    e Zd ZdZd Zd Zd Zy)rP   z^Categorizer that reverses column values for columns that aren't
    naturally reversible.
    c                     t         j                  | ||       |j                         }|j                         | _        |j                  |d      }t        t        |            | _        y NF)rb   )	rO   rD   rK   doc_count_all	_doccountrc   sortedset_values)r   r   rB   rK   global_creaders        r   rD   z"ReversedColumnCategorizer.__init__   sX    ""4)D '')--/--i5-Ic.12r   c                 `    | j                   |   }| j                  j                  |      }d|z
  S Nr   )r[   rq   index)r   r3   r4   valueorders        r   r5   z!ReversedColumnCategorizer.key_for  s.    n-""5)5yr   c                 R    | j                   d|z
     }t        j                  | |      S rt   )rq   rO   r<   r:   s     r   r<   z%ReversedColumnCategorizer.key_to_name	  s'    ll1s7# ,,T377r   N)r"   r#   r$   r%   rD   r5   r<   r   r   r   rP   rP      s    38r   rP   c                   (    e Zd ZdZd Zd Zd Zd Zy)rJ   Tc                 :   || _         |j                  |   | _        |j                  |   }|j                         }t	        |j
                        | _        |j                  |      xr |j                  j                         | _
        d | _        d | _        d | _        y r   )rW   rI   rX   rK   boolvector_use_vectorsrL   rM   stores_lists_use_column_segment_searcherr[   _lists)r   r   rB   fieldrK   s        r   rD   zOverlappingCategorizer.__init__  s    #(//	:&&y1 '') ."--i8 A % 1 1 > > @ 	 "&r   c                    | j                   }|| _        |j                         }| j                  ry | j                  r|j                  |d      | _        y |j                         }|j                  |   }|j                  }t        |      D cg c]  }g  c}| _        |j                  ||      D ]O  }	 ||	      }
|j                  ||	      }|j                         D ]   }| j                  |   j                  |
       " Q y c c}w rl   )rW   r   rK   r}   r   rc   r[   rm   rI   
from_bytesr   r   sortable_termspostingsall_idsappend)r   r*   r+   rB   rK   dcr   r   _btexttextr   docids                r   r,   z#OverlappingCategorizer.set_searcher!  s    OO	!1!((*"00e0LDM "//1B$++I6E))J'-bz2!22DK--fi@ 4!%(!??9e<%--/ 4EKK&--d344 3s   	Dc                    | j                   r@	 | j                  j                  || j                        }t	        |j                               S | j                  r| j                  |   S | j                  |   xs d gS # t        $ r g cY S w xY wr   )
r}   r   r|   rW   listr   KeyErrorr   r[   r   )r   r3   r   vs       r   r8   zOverlappingCategorizer.keys_for8  s    **11%IAIIK(( =='';;u%/$/  	s   >A< <B
	B
c                 "   | j                   r7	 | j                  j                  || j                        }|j	                         S | j                  r| j                  j                  |      S | j                  |   }|r|d   S y # t
        $ r Y y w xY wrt   )
r}   r   r|   rW   idr   r   r[   rf   r   )r   r3   r   r   lss        r   r5   zOverlappingCategorizer.key_forD  s    **11%Ittv ==))%00U#B!u  s   5B 	BBN)r"   r#   r$   r=   rD   r,   r8   r5   r   r   r   rJ   rJ     s    M4.
0r   rJ   c                   (    e Zd ZdZd Zd Zd Zd Zy)rQ   aa  
    Categorizer for fields that don't store column values. This is very
    inefficient. Instead of relying on this categorizer you should plan for
    which fields you'll want to sort on and set ``sortable=True`` in their
    field type.

    This object builds an array caching the order of all documents according to
    the field, then uses the cached order as a numeric key. This is useful when
    a field cache is not available, and also for reversed fields (since field
    cache keys for non- numeric fields are arbitrary data, it's not possible to
    "negate" them to reverse the sort order).
    c                    || _         ||j                  v r|j                  |   \  | _        | _        y |j	                         }|j                         }|j                  |   | _        | j                  j                  }g | _        t        d|dz   g|z        | _        | j                  j                  ||      }t        |      D ]\  \  }}	| j                  j                   ||	             |j                  ||	      }
|
j                         D ]  }|| j                  |<    ^ | j                  | j                  f|j                  |<   y )Ni   )rC   _field_cachesvaluesr   rK   rm   rI   rX   r   r   	enumerater   r   r   )r   r   rB   rC   rK   r   r   btextsr   r   r   r   s               r   rD   zPostingCategorizer.__init__c  s(   555&5&C&CI&N#DK %++-F%%'B,33I>DN22JDKsR!VHrM2DJ^^2269EF%f- *5"":e#45!??9e<%--/ *E()DJJu%*	* 9=TZZ7PO)))4r   c                      || _         || _        y r   )	_searcherr+   r)   s      r   r,   zPostingCategorizer.set_searcher}  s    )"r   c                     | j                   |z   }| j                  |   }| j                  rt        | j                        |z
  }|S r   )r+   r   rC   lenr   )r   r3   r4   global_docnumr   s        r   r5   zPostingCategorizer.key_for  s=    7JJ}%<<DKK 1$Ar   c                     |t        | j                        k\  ry | j                  rt        | j                        |z
  }| j                  |   S r   )r   r   rC   )r   r   s     r   r<   zPostingCategorizer.key_to_name  s>    DKK  <<DKK 1$A{{1~r   N)r"   r#   r$   r%   rD   r,   r5   r<   r   r   r   rQ   rQ   U  s    Q4#r   rQ   c                   8    e Zd ZdZ	 	 ddZd Z G d de      Zy)
QueryFacetz>Sorts/facets based on the results of a series of queries.
    Nc                 <    || _         || _        || _        || _        y)z
        :param querydict: a dictionary mapping keys to
            :class:`whoosh.query.Query` objects.
        :param other: the key to use for documents that don't match any of the
            queries.
        N)	querydictotherr   r=   )r   r   r   r=   r   s        r   rD   zQueryFacet.__init__  s!     #
*r   c                 d    | j                  | j                  | j                  | j                        S r   )QueryCategorizerr   r   r=   r   s     r   r   zQueryFacet.categorizer  s%    $$T^^TZZASASTTr   c                   &    e Zd ZddZd Zd Zd Zy)QueryFacet.QueryCategorizerc                 .    || _         || _        || _        y r   )r   r   r=   r   r   r   r=   s       r   rD   z$QueryFacet.QueryCategorizer.__init__  s    &DNDJ!.Dr   c                     i | _         | j                  j                         D ]1  \  }}t        |j	                  |            }|s#|| j                   |<   3 || _        y r   )docsetsr   itemsrp   docsoffset)r   r*   r   qnameqdocsets         r   r,   z(QueryFacet.QueryCategorizer.set_searcher  sW    DL NN002 1qQVV$456*0DLL'1 !DKr   c                 f    | j                   D ]  }|| j                   |   v s|c S  | j                  S r   )r   r   )r   r3   r   r   s       r   r5   z#QueryFacet.QueryCategorizer.key_for  s7     !DLL// L! ::r   c              #   p   K   d}| j                   D ]  }|| j                   |   v s| d} |sd  y y w)NFT)r   )r   r3   r   foundr   s        r   r8   z$QueryFacet.QueryCategorizer.keys_for  sH     E !DLL//K E! 
 s   #66Nri   )r"   r#   r$   rD   r,   r5   r8   r   r   r   r   r     s    	/
	!		r   r   )NFN)r"   r#   r$   r%   rD   r   r'   r   r   r   r   r   r     s'     =B+U; r   r   c                   :    e Zd ZdZ	 	 d	dZd Zd Zd Zd Zd Z	y)

RangeFacetaz  Sorts/facets based on numeric ranges. For textual ranges, use
    :class:`QueryFacet`.

    For example, to facet the "price" field into $100 buckets, up to $1000::

        prices = RangeFacet("price", 0, 1000, 100)
        results = searcher.search(myquery, groupedby=prices)

    The ranges/buckets are always **inclusive** at the start and **exclusive**
    at the end.
    Nc                 x    || _         || _        || _        || _        || _        || _        | j                          y)a  
        :param fieldname: the numeric field to sort/facet on.
        :param start: the start of the entire range.
        :param end: the end of the entire range.
        :param gap: the size of each "bucket" in the range. This can be a
            sequence of sizes. For example, ``gap=[1,5,10]`` will use 1 as the
            size of the first bucket, 5 as the size of the second bucket, and
            10 as the size of all subsequent buckets.
        :param hardend: if True, the end of the last bucket is clamped to the
            value of ``end``. If False (the default), the last bucket is always
            ``gap`` sized, even if that means the end of the last bucket is
            after ``end``.
        N)rB   startendgaphardendr   _queries)r   rB   r   r   r   r   r   s          r   rD   zRangeFacet.__init__  s7      #
r   c                     | j                   S r   rF   r    s    r   r!   zRangeFacet.default_name  rG   r   c                 &    ddl m} |j                  S Nr   )query)whooshr   NumericRanger   r   s     r   
_rangetypezRangeFacet._rangetype  s     !!!r   c                 
    ||fS r   r   )r   startvalendvals      r   _range_namezRangeFacet._range_name  s    &!!r   c                 L   | j                   st        d| j                   z        t        | j                   t        t        f      r| j                   }d}n| j                   g}d}| j                         }i | _        | j                  }|| j                  k  r||   }|dk\  r|dz  }|t        |      k(  rd}||z   }| j                  rt        | j                  |      }| j                  ||      } || j                  ||d      }|| j                  |<   |}|| j                  k  ry y )NzNo gap secified (%r)r   r   T)endexcl)r   	Exception
isinstancer   tupler   r   r   r   r   r   minr   rB   )	r   gapsgapindex	rangetypecstartthisgapcend	rangenamer   s	            r   r   zRangeFacet._queries  s   xx2TXX=>>dhhu.88DHHH:DHOO%	txx8nG1}As4y(!HG#D||488T*((6I$..&$EA()DNN9%F txxr   c                 J    t        | j                        j                  |      S r   )r   r   r   r   s     r   r   zRangeFacet.categorizer  s    $..)55oFFr   )FN)
r"   r#   r$   r%   rD   r!   r   r   r   r   r   r   r   r   r     s/    
 <A0"
"<Gr   r   c                       e Zd ZdZd Zy)DateRangeFacetaU  Sorts/facets based on date ranges. This is the same as RangeFacet
    except you are expected to use ``daterange`` objects as the start and end
    of the range, and ``timedelta`` or ``relativedelta`` objects as the gap(s),
    and it generates :class:`~whoosh.query.DateRange` queries instead of
    :class:`~whoosh.query.TermRange` queries.

    For example, to facet a "birthday" range into 5 year buckets::

        from datetime import datetime
        from whoosh.support.relativedelta import relativedelta

        startdate = datetime(1920, 0, 0)
        enddate = datetime.now()
        gap = relativedelta(years=5)
        bdays = DateRangeFacet("birthday", startdate, enddate, gap)
        results = searcher.search(myquery, groupedby=bdays)

    The ranges/buckets are always **inclusive** at the start and **exclusive**
    at the end.
    c                 &    ddl m} |j                  S r   )r   r   	DateRanger   s     r   r   zDateRangeFacet._rangetype-  s     r   N)r"   r#   r$   r%   r   r   r   r   r   r     s    *r   r   c                   ,    e Zd ZdZd Z G d de      Zy)
ScoreFaceta  Uses a document's score as a sorting criterion.

    For example, to sort by the ``tag`` field, and then within that by relative
    score::

        tag_score = MultiFacet(["tag", ScoreFacet()])
        results = searcher.search(myquery, sortedby=tag_score)
    c                 $    | j                  |      S r   )ScoreCategorizerr   s     r   r   zScoreFacet.categorizer=  s    $$_55r   c                   "    e Zd ZdZd Zd Zd Zy)ScoreFacet.ScoreCategorizerTc                 z    |j                   }|j                  | _        |j                  r|j                  | _        y y r   )	weighting	use_finalfinal)r   r   ws      r   rD   z$ScoreFacet.ScoreCategorizer.__init__C  s/    ))A[[DN{{WW
 r   c                     || _         y r   r*   )r   r*   r   s      r   r,   z(ScoreFacet.ScoreCategorizer.set_searcherI  
    $4D!r   c                 ~    |j                         }| j                  r| j                  | j                  ||      }d|z
  S rt   )scorer   r   r*   )r   r3   r   r   s       r   r5   z#ScoreFacet.ScoreCategorizer.key_forL  s6    MMOE~~

4#8#8%Gu9r   N)r"   r#   r$   r>   rD   r,   r5   r   r   r   r   r   @  s    	%	5	r   r   N)r"   r#   r$   r%   r   r'   r   r   r   r   r   r   3  s    6; r   r   c                   4    e Zd ZdZddZd Z G d de      Zy)FunctionFaceta  This facet type is low-level. In most cases you should use
    :class:`TranslateFacet` instead.

    This facet type ets you pass an arbitrary function that will compute the
    key. This may be easier than subclassing FacetType and Categorizer to set up
    the desired behavior.

    The function is called with the arguments ``(searcher, docid)``, where the
    ``searcher`` may be a composite searcher, and the ``docid`` is an absolute
    index document number (not segment-relative).

    For example, to use the number of words in the document's "content" field
    as the sorting/faceting key::

        fn = lambda s, docid: s.doc_field_length(docid, "content")
        lengths = FunctionFacet(fn)
    Nc                      || _         || _        y r   )fnr   )r   r   r   s      r   rD   zFunctionFacet.__init__g  s    r   c                 :    | j                  || j                        S r   )FunctionCategorizerr   r   s     r   r   zFunctionFacet.categorizerk  s    ''AAr   c                       e Zd Zd Zd Zd Zy)!FunctionFacet.FunctionCategorizerc                      || _         || _        y r   )r   r   )r   r   r   s      r   rD   z*FunctionFacet.FunctionCategorizer.__init__o  s    #2D DGr   c                     || _         y r   )r   r)   s      r   r,   z.FunctionFacet.FunctionCategorizer.set_searchers  s	    #DKr   c                 T    | j                  | j                  || j                  z         S r   )r   r   r   r   r3   r   s      r   r5   z)FunctionFacet.FunctionCategorizer.key_forv  s"    774//1DEEr   Nr"   r#   r$   rD   r,   r5   r   r   r   r   r   n  s    		$	Fr   r   r   )r"   r#   r$   r%   rD   r   r'   r   r   r   r   r   r   T  s     $B	Fk 	Fr   r   c                   2    e Zd ZdZd Zd Z G d de      Zy)TranslateFaceta  Lets you specify a function to compute the key based on a key generated
    by a wrapped facet.

    This is useful if you want to use a custom ordering of a sortable field. For
    example, if you want to use an implementation of the Unicode Collation
    Algorithm (UCA) to sort a field using the rules from a particular language::

        from pyuca import Collator

        # The Collator object has a sort_key() method which takes a unicode
        # string and returns a sort key
        c = Collator("allkeys.txt")

        # Make a facet object for the field you want to sort on
        facet = sorting.FieldFacet("name")
        # Wrap the facet in a TranslateFacet with the translation function
        # (the Collator object's sort_key method)
        facet = sorting.TranslateFacet(c.sort_key, facet)

        # Use the facet to sort the search results
        results = searcher.search(myquery, sortedby=facet)

    You can pass multiple facets to the
    c                 .    || _         || _        d| _        y)a  
        :param fn: The function to apply. For each matching document, this
            function will be called with the values of the given facets as
            arguments.
        :param facets: One or more :class:`FacetType` objects. These facets are
            used to compute facet value(s) for a matching document, and then the
            value(s) is/are passed to the function.
        N)r   facetsr   )r   r   r   s      r   rD   zTranslateFacet.__init__  s     r   c                     | j                   D cg c]  }|j                  |       }}| j                  | j                  |      S c c}w r   )r   r   TranslateCategorizerr   )r   r   r   catterss       r   r   zTranslateFacet.categorizer  sA    CG;;O%5$$_5OO((':: Ps   Ac                       e Zd Zd Zd Zd Zy)#TranslateFacet.TranslateCategorizerc                      || _         || _        y r   )r   r  )r   r   r  s      r   rD   z,TranslateFacet.TranslateCategorizer.__init__  s    DG"DLr   c                 J    | j                   D ]  }|j                  ||        y r   r  r,   r   r*   r+   catters       r   r,   z0TranslateFacet.TranslateCategorizer.set_searcher  (    ,, A##$4i@Ar   c                 |    | j                   D cg c]  }|j                  ||       }} | j                  | S c c}w r   )r  r5   r   )r   r3   r4   r
  keyss        r   r5   z+TranslateFacet.TranslateCategorizer.key_for  sC    "&,,0 NN7N; 0D 0477D>!0s   9Nr   r   r   r   r  r    s    	#	A	"r   r  N)r"   r#   r$   r%   rD   r   r'   r  r   r   r   r   r   z  s    2;"{ "r   r   c                   >    e Zd ZdZ	 	 ddZd Zd Z G d de      Zy)	StoredFieldFaceta  Lets you sort/group using the value in an unindexed, stored field (e.g.
    :class:`whoosh.fields.STORED`). This is usually slower than using an indexed
    field.

    For fields where the stored value is a space-separated list of keywords,
    (e.g. ``"tag1 tag2 tag3"``), you can use the ``allow_overlap`` keyword
    argument to allow overlapped faceting on the result of calling the
    ``split()`` method on the field value (or calling a custom split function
    if one is supplied).
    Nc                 <    || _         || _        || _        || _        y)af  
        :param fieldname: the name of the stored field.
        :param allow_overlap: if True, when grouping, allow documents to appear
            in multiple groups when they have multiple terms in the field. The
            categorizer uses ``string.split()`` or the custom ``split_fn`` to
            convert the stored value into a list of facet values.
        :param split_fn: a custom function to split a stored field value into
            multiple facet values when ``allow_overlap`` is True. If not
            supplied, the categorizer simply calls the value's ``split()``
            method.
        N)rB   r=   split_fnr   )r   rB   r=   r  r   s        r   rD   zStoredFieldFacet.__init__  s!     #* r   c                     | j                   S r   rF   r    s    r   r!   zStoredFieldFacet.default_name  rG   r   c                 d    | j                  | j                  | j                  | j                        S r   )StoredFieldCategorizerrB   r=   r  r   s     r   r   zStoredFieldFacet.categorizer  s*    **4>>4;M;M+/==: 	:r   c                   $    e Zd Zd Zd Zd Zd Zy)'StoredFieldFacet.StoredFieldCategorizerc                 .    || _         || _        || _        y r   )rB   r=   r  )r   rB   r=   r  s       r   rD   z0StoredFieldFacet.StoredFieldCategorizer.__init__  s    &DN!.D$DMr   c                     || _         y r   r   r)   s      r   r,   z4StoredFieldFacet.StoredFieldCategorizer.set_searcher  r   r   c                     | j                   j                  |      }|j                  | j                        }| j                  r| j	                  |      S |j                         S r   )r*   stored_fieldsgetrB   r  split)r   r3   r   drv   s        r   r8   z0StoredFieldFacet.StoredFieldCategorizer.keys_for  sL    %%33E:AEE$..)E}}}}U++{{}$r   c                 n    | j                   j                  |      }|j                  | j                        S r   )r*   r  r  rB   )r   r3   r   r  s       r   r5   z/StoredFieldFacet.StoredFieldCategorizer.key_for  s+    %%33E:A55((r   N)r"   r#   r$   rD   r,   r8   r5   r   r   r   r  r    s    	%
	5	%	)r   r  )FNN)	r"   r#   r$   r%   rD   r!   r   r'   r  r   r   r   r  r    s,    	 AE&:) )r   r  c                   l    e Zd ZdZddZd Zed        Zd ZddZ	ddZ
d	 Zd
 Zd Z G d de      Zy)
MultiFacetaF  Sorts/facets by the combination of multiple "sub-facets".

    For example, to sort by the value of the "tag" field, and then (for
    documents where the tag is the same) by the value of the "path" field::

        facet = MultiFacet(FieldFacet("tag"), FieldFacet("path")
        results = searcher.search(myquery, sortedby=facet)

    As a shortcut, you can use strings to refer to field names, and they will
    be assumed to be field names and turned into FieldFacet objects::

        facet = MultiFacet("tag", "path")

    You can also use the ``add_*`` methods to add criteria to the multifacet::

        facet = MultiFacet()
        facet.add_field("tag")
        facet.add_field("path", reverse=True)
        facet.add_query({"a-m": TermRange("name", "a", "m"),
                         "n-z": TermRange("name", "n", "z")})
    Nc                 T    g | _         |r|D ]  }| j                  |        || _        y r   )r   _addr   )r   r   r   items       r   rD   zMultiFacet.__init__  s-      		$ r   c                 h    | j                   j                  d| j                  d| j                  dS )Nr]   r^   r_   )r1   r"   r   r   r    s    r   r`   zMultiFacet.__repr__  s'    #~~66#{{#||- 	-r   c                      |        }t        |t              r|j                  |       |S t        |t        t        f      st        |d      r|D ]  }|j                  |        |S |j                  |       |S )N__iter__)r   r   r"  r   r   r0   )clssortedbymultir#  s       r   from_sortedbyzMultiFacet.from_sortedby  su    h,JJx   D%=1:.  !

4 !  JJx r   c                     t        |t              r| j                  |       y t        |t              r| j	                  |       y t        d|      )Nz!Don't know what to do with facet )r   r
   	add_facetr   	add_fieldr   )r   r#  s     r   r"  zMultiFacet._add   s<    dI&NN4 k*NN4 TKLLr   c                 R    | j                   j                  t        ||             | S )N)rC   )r   r   r@   )r   rB   rC   s      r   r-  zMultiFacet.add_field(  s     :iABr   c                 T    | j                   j                  t        |||             | S )N)r   r=   )r   r   r   r   s       r   	add_queryzMultiFacet.add_query,  s)    :iu4AC 	Dr   c                 L    | j                   j                  t                      | S r   )r   r   r   r    s    r   	add_scorezMultiFacet.add_score1  s    :<(r   c                 x    t        |t              st        |d      | j                  j	                  |       | S )Nz5 is not a facet object, perhaps you meant add_field())r   r
   	TypeErrorr   r   )r   r   s     r   r,  zMultiFacet.add_facet5  s8    %+-25 6 65!r   c                    | j                   st        d      t        | j                         dk(  r | j                   d   j                  |      }|S | j	                  | j                   D cg c]  }|j                  |       c}      }|S c c}w )Nz	No facetsr   r   )r   r   r   r   MultiCategorizer)r   r   r
  r   s       r   r   zMultiFacet.categorizer<  s    {{K(("[[^//@F  **9=,F05 -2,=,=o,N ,F GF,Fs   )B
c                   4    e Zd Zd Zed        Zd Zd Zd Zy)MultiFacet.MultiCategorizerc                     || _         y r   )r  )r   r  s     r   rD   z$MultiFacet.MultiCategorizer.__init__G  s	    "DLr   c                 :    t        d | j                  D              S )Nc              3   4   K   | ]  }|j                     y wr   )r>   ).0rT   s     r   	<genexpr>z<MultiFacet.MultiCategorizer.needs_current.<locals>.<genexpr>L  s     =1q=s   )anyr  r    s    r   r>   z)MultiFacet.MultiCategorizer.needs_currentJ  s    ====r   c                 J    | j                   D ]  }|j                  ||        y r   r  r	  s       r   r,   z(MultiFacet.MultiCategorizer.set_searcherN  r  r   c                 D    t        fd| j                  D              S )Nc              3   B   K   | ]  }|j                          y wr   )r5   )r<  r
  r   r3   s     r   r=  z6MultiFacet.MultiCategorizer.key_for.<locals>.<genexpr>S  s$      5#  7 5s   )r   r  r   s    ``r   r5   z#MultiFacet.MultiCategorizer.key_forR  s!     5'+||5 5 5r   c                 N    t        d t        | j                  |      D              S )Nc              3   D   K   | ]  \  }}|j                  |        y wr   )r<   )r<  r
  keyparts      r   r=  z:MultiFacet.MultiCategorizer.key_to_name.<locals>.<genexpr>W  s'      5,VW  ++G4 5s    )r   r   r  r:   s     r   r<   z'MultiFacet.MultiCategorizer.key_to_nameV  s'     5 s35 5 5r   N)	r"   r#   r$   rD   propertyr>   r,   r5   r<   r   r   r   r6  r8  F  s+    	# 
	> 
	>	A	5	5r   r6  )NNri   )NF)r"   r#   r$   r%   rD   r`   classmethodr*  r"  r-  r0  r2  r,  r   r'   r6  r   r   r   r   r     sP    ,-
 
 
M
5; 5r   r   c                   N    e Zd ZdZddZed        Zd Zd Zd Z	d Z
d	 Zdd
Zy)Facetsa  Maps facet names to :class:`FacetType` objects, for creating multiple
    groupings of documents.

    For example, to group by tag, and **also** group by price range::

        facets = Facets()
        facets.add_field("tag")
        facets.add_facet("price", RangeFacet("price", 0, 1000, 100))
        results = searcher.search(myquery, groupedby=facets)

        tag_groups = results.groups("tag")
        price_groups = results.groups("price")

    (To group by the combination of multiple facets, use :class:`MultiFacet`.)
    Nc                 :    i | _         |r| j                  |       y y r   )r   
add_facets)r   xs     r   rD   zFacets.__init__m  s    OOA r   c                     |        }t        || t        f      r|j                  |       |S t        |t              r|j	                  |       |S t        |t
              r"|j                  |j                         |       |S t        |t        t        f      r)|D ]"  }|j                  | j                  |             $ |S t        d|z        )Nz'Don't know what to do with groupedby=%r)r   dictrJ  r   r-  r
   r,  r!   r   r   from_groupedbyr   )r'  	groupedbyr   r#  s       r   rN  zFacets.from_groupedbyr  s    i#t-i(  	;/Y'  	9-Y335yA  	D%=1! <!!#"4"4T":;<  E'( ) )r   c                 ,    t        | j                        S )z?Returns an iterator of the facet names in this object.
        )iterr   r    s    r   nameszFacets.names  s     DKK  r   c                 6    | j                   j                         S )zaReturns a list of (facetname, facetobject) tuples for the facets in
        this object.
        )r   r   r    s    r   r   zFacets.items  s    
 {{  ""r   c                 8    t        |fi || j                  |<   | S )z~Adds a :class:`FieldFacet` for the given field name (the field name
        is automatically used as the facet name).
        )r@   r   )r   rB   kwargss      r   r-  zFacets.add_field  s!    
 ",I!@!@Ir   c                 8    t        |fi || j                  |<   | S )zAdds a :class:`QueryFacet` under the given ``name``.

        :param name: a name for the facet.
        :param querydict: a dictionary mapping keys to
            :class:`whoosh.query.Query` objects.
        )r   r   )r   namer   rU  s       r   r0  zFacets.add_query  s!     'y;F;Dr   c                 f    t        |t              st        |d|d      || j                  |<   | S )zCAdds a :class:`FacetType` object under the given ``name``.
        :z is not a facet)r   r
   r   r   )r   rW  r   s      r   r,  zFacets.add_facet  s1     %+dEBCC!Dr   c                     t        |t        t        f      st        d|z        |j	                         D ]%  \  }}|s|| j
                  vs|| j
                  |<   ' | S )z]Adds the contents of the given ``Facets`` or ``dict`` object to this
        object.
        z!%r is not a Facets object or dict)r   rM  rH  r   r   r   )r   r   replacerW  r   s        r   rJ  zFacets.add_facets  s_    
 &4.1?&HII!<<> 	*KD%$dkk1$)D!	* r   r   )T)r"   r#   r$   r%   rD   rF  rN  rR  r   r-  r0  r,  rJ  r   r   r   rH  rH  \  s>     
  "!#	
r   rH  c                       e Zd ZdZd Zd Zy)FacetMapaK  Base class for objects holding the results of grouping search results by
    a Facet. Use an object's ``as_dict()`` method to access the results.

    You can pass a subclass of this to the ``maptype`` keyword argument when
    creating a ``FacetType`` object to specify what information the facet
    should record about the group. For example::

        # Record each document in each group in its sorted order
        myfacet = FieldFacet("size", maptype=OrderedList)

        # Record only the count of documents in each group
        myfacet = FieldFacet("size", maptype=Count)
    c                     t         )a*  Adds a document to the facet results.

        :param groupname: the name of the group to add this document to.
        :param docid: the document number of the document to add.
        :param sortkey: a value representing the sort position of the document
            in the full results.
        r   r   	groupnamer   sortkeys       r   addzFacetMap.add  s
     "!r   c                     t         )zReturns a dictionary object mapping group names to
        implementation-specific values. For example, the value might be a list
        of document numbers, or a integer representing the number of documents
        in the group.
        r   r    s    r   as_dictzFacetMap.as_dict  r   r   N)r"   r#   r$   r%   rb  rd  r   r   r   r]  r]    s    	""r   r]  c                   (    e Zd ZdZd Zd Zd Zd Zy)r   zStores a list of document numbers for each group, in the same order as
    they appear in the search results.

    The ``as_dict`` method returns a dictionary mapping group names to lists
    of document numbers.
    c                 ,    t        t              | _        y r   r   r   rM  r    s    r   rD   zOrderedList.__init__      %	r   c                 P    d| j                   j                  d| j                  dS N< >r1   r"   rM  r    s    r   r`   zOrderedList.__repr__       NN33TYY??r   c                 D    | j                   |   j                  ||f       y r   rM  r   r_  s       r   rb  zOrderedList.add  s    		)##We$45r   c                     i }t        | j                        D ]&  \  }}t        |      D cg c]  \  }}|	 c}}||<   ( |S c c}}w r   )r   rM  ro   )r   r  r;   r   r   docnums         r   rd  zOrderedList.as_dict  sI    #DII. 	=JC.4Um<Ff<AcF	= =s   ANr"   r#   r$   r%   rD   r`   rb  rd  r   r   r   r   r     s    &@6r   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)UnorderedListaO  Stores a list of document numbers for each group, in arbitrary order.
    This is slightly faster and uses less memory than
    :class:`OrderedListResult` if you don't care about the ordering of the
    documents within groups.

    The ``as_dict`` method returns a dictionary mapping group names to lists
    of document numbers.
    c                 ,    t        t              | _        y r   rg  r    s    r   rD   zUnorderedList.__init__  rh  r   c                 P    d| j                   j                  d| j                  dS rj  rn  r    s    r   r`   zUnorderedList.__repr__  ro  r   c                 @    | j                   |   j                  |       y r   rq  r_  s       r   rb  zUnorderedList.add  s    		)##E*r   c                 ,    t        | j                         S r   rM  r    s    r   rd  zUnorderedList.as_dict      DIIr   Nrt  r   r   r   rv  rv    s    &@+r   rv  c                   (    e Zd ZdZd Zd Zd Zd Zy)CountzStores the number of documents in each group.

    The ``as_dict`` method returns a dictionary mapping group names to
    integers.
    c                 ,    t        t              | _        y r   )r   intrM  r    s    r   rD   zCount.__init__  s    $	r   c                 P    d| j                   j                  d| j                  dS rj  rn  r    s    r   r`   zCount.__repr__  ro  r   c                 2    | j                   |xx   dz  cc<   y )Nr   r{  r_  s       r   rb  z	Count.add  s    		)!r   c                 ,    t        | j                         S r   r{  r    s    r   rd  zCount.as_dict  r|  r   Nrt  r   r   r   r~  r~    s    %@"r   r~  c                   (    e Zd ZdZd Zd Zd Zd Zy)BestzStores the "best" document in each group (that is, the one with the
    highest sort key).

    The ``as_dict`` method returns a dictionary mapping group names to
    docnument numbers.
    c                      i | _         i | _        y r   bestidsbestkeysr    s    r   rD   zBest.__init__+  s    r   c                 P    d| j                   j                  d| j                  dS rj  )r1   r"   r  r    s    r   r`   zBest.__repr__/  s     NN33T\\BBr   c                     || j                   vs|| j                  |   k  r|| j                   |<   || j                  |<   y y r   r  r_  s       r   rb  zBest.add2  s@    DLL(GdmmI6N,N&+DLL#'.DMM)$ -Or   c                     | j                   S r   )r  r    s    r   rd  zBest.as_dict7  s    ||r   Nrt  r   r   r   r  r  #  s    C/
r   r  Nc                    | j                   }| j                  }d}||v r||   }|j                  rt        d|z        |r%||vrDddlm}  ||      }|j                  ||       n#||v r|j                         }nt        d|z        | j                         }|j                  |      }	|j                         D ]$  \  }
}|	j                  |
|       |
j                         }|j                  |      rt        d|z        |j                         }|j                         }|j!                  ||      }|j#                  |      }	 |j%                  |      }|j'                         D ]F  }|	j)                  |	j+                  d|            }|j-                  |      }|j                  ||       H |j/                  |j1                                |j3                          ' ||_        y# |j3                          w xY w)a!  Adds a per-document value column to an existing field which was created
    without the ``sortable`` keyword argument.

    >>> from whoosh import index, sorting
    >>> ix = index.open_dir("indexdir")
    >>> with ix.writer() as w:
    ...   facet = sorting.FieldFacet("price")
    ...   sorting.add_sortable(w, "price", facet)
    ...

    :param writer: a :class:`whoosh.writing.IndexWriter` object.
    :param fieldname: the name of the field to add the per-document sortable
        values to. If this field doesn't exist in the writer's schema, the
        function will add a :class:`whoosh.fields.COLUMN` field to the schema,
        and you must specify the column object to using the ``column`` keyword
        argument.
    :param facet: a :class:`FacetType` object to use to generate the
        per-document values.
    :param column: a :class:`whosh.columns.ColumnType` object to use to store
        the per-document values. If you don't specify a column object, the
        function will use the default column type for the given field.
    Nz%r field is already sortabler   )COLUMNzField %r does not existz%r field already has a column)storagerI   rM   r   whoosh.fieldsr  rb  default_columnsearcherr   leaf_searchersr,   rK   rL   codecsegmentcolumn_filenamecreate_filewriterall_doc_idsr<   r5   to_column_valuefinishrm   close)r  rB   r   columnr  rI   r   r  r  r
  subsearcherr+   rK   r  r  colnamecolfile	colwriterrs  r   cvs                        r   add_sortabler  =  s   0 nnG]]FEFy!:YFGGF",6NEJJy%())+F5	ABB Hx(F"*"9"9"; YK3##%Y';iGHH.."'';%%g.	g.I ,,. *&&v~~dF'CD**1-fb)* V1134MMO), E MMOs   B	G))G;r   )r   collectionsr   whoosh.compatr   r   r   r   objectr
   r'   r@   rO   rP   rJ   rQ   r   r   r   r   r   r   r  r   rH  r]  r   rv  r~  r  r  r   r   r   <module>r     s4  8  # % 1 1
 >X& Xz4 4n5 5:8 1 84C[ CL8 8z0 0fOG OGdZ 8 B#FI #FL7"Y 7"t9)y 9)xi5 i5X[V [@!"v !"H( 0H .H (8 4Dr   