U
    W+d5                     @   s|   d dl mZ d dlmZmZmZ d dlZG dd deZG dd deZ	G dd	 d	e
ZG d
d de
ZG dd de
ZdS )    )ceil)jsonmapsixNc                   @   s   e Zd ZdS )SearchServiceExceptionN__name__
__module____qualname__ r   r   ;/tmp/pip-unpacked-wheel-dlxw5sjy/boto/cloudsearch/search.pyr      s   r   c                   @   s   e Zd ZdS )CommitMismatchErrorNr   r   r   r   r   r   !   s   r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
SearchResultsc                 K   s   |d d | _ |d d | _|d d | _|d d | _|d d | _|d d | _|d	 | _|d
 | _|d | _|d | _	i | _
d|kr|d  D ]6\}}d|krtdd tdd |d D | j
|< qt| j| jj | _d S )Ninforidzcpu-time-msztime-mshitsfoundhitstartrankz
match-exprquerysearch_servicefacetsconstraintsc                 s   s   | ]\}}||fV  qd S Nr   ).0kvr   r   r   	<genexpr>7   s     z)SearchResults.__init__.<locals>.<genexpr>c                 S   s   | d | d fS )Nvaluecountr   )xr   r   r   <lambda>7       z(SearchResults.__init__.<locals>.<lambda>)r   Zcpu_time_msZtime_msr   docsr   r   Zmatch_expressionr   r   r   itemsdictr   r   	real_sizenum_pages_needed)selfattrsfacetvaluesr   r   r   __init__&   s     



(zSearchResults.__init__c                 C   s
   t | jS r   )lenr$   r)   r   r   r   __len__;   s    zSearchResults.__len__c                 C   s
   t | jS r   )iterr$   r/   r   r   r   __iter__>   s    zSearchResults.__iter__c                 C   sF   | j j| jkr>| j  j| j j7  _| j  jd7  _| | j S tdS )zCall Cloudsearch to get the next page of search results

        :rtype: :class:`boto.cloudsearch.search.SearchResults`
        :return: the following page of search results
           N)r   pager(   r   r'   r   StopIterationr/   r   r   r   	next_pageA   s
    zSearchResults.next_pageN)r   r	   r
   r-   r0   r2   r6   r   r   r   r   r   %   s   r   c                   @   s*   e Zd ZdZdddZdd Zd	d
 ZdS )Queryi  N
   r   c                 C   sl   || _ || _|pg | _|pg | _|| _|p,g | _|p6i | _|	p@i | _|
pJi | _|pTi | _	d| _
| | d S Nr   )qbqr   return_fieldsr   r+   facet_constraints
facet_sortfacet_top_ntr4   update_sizer)   r:   r;   r   r<   sizer   r+   r=   r>   r?   r@   r   r   r   r-   S   s    






zQuery.__init__c                 C   s.   || _ | j tjks| j dkr"tjn| j | _d S r9   )rC   r7   RESULTS_PER_PAGEr'   )r)   Znew_sizer   r   r   rA   e   s    zQuery.update_sizec                 C   s  | j | jd}| jr| j|d< | jr.| j|d< | jrDd| j|d< | jrZd| j|d< | jrpd| j|d< | jrt	
| jD ]\}}||d| < q| jrt	
| jD ]\}}||d	| < q| jrt	
| jD ]\}}||d
| < q| jrt	
| jD ]\}}||d| < q|S )zTransform search parameters from instance properties to a dictionary

        :rtype: dict
        :return: search parameters
        )r   rC   r:   r;   ,r   zreturn-fieldsr+   zfacet-%s-constraintszfacet-%s-sortzfacet-%s-top-nzt-%s)r   r'   r:   r;   r   joinr<   r+   r=   r   	iteritemsr>   r?   r@   )r)   paramsr   r   r   r   r   	to_paramsj   s0    

zQuery.to_params)NNNNr8   r   NNNNN)r   r	   r
   rD   r-   rA   rI   r   r   r   r   r7   O   s                 
r7   c                   @   sJ   e Zd ZdddZdddZddd	Zd
d Zdd Zdd Zdd Z	dS )SearchConnectionNc                 C   s   || _ || _|s|j| _d S r   )domainendpointZsearch_service_endpoint)r)   rK   rL   r   r   r   r-      s    zSearchConnection.__init__r8   r   c                 C   s   t |||||||||	|
|dS )Nr:   r;   r   r<   rC   r   r+   r=   r>   r?   r@   )r7   rB   r   r   r   build_query   s    
    zSearchConnection.build_queryc                 C   s(   | j |||||||||	|
|d}| |S )a  
        Send a query to CloudSearch

        Each search query should use at least the q or bq argument to specify
        the search parameter. The other options are used to specify the
        criteria of the search.

        :type q: string
        :param q: A string to search the default search fields for.

        :type bq: string
        :param bq: A string to perform a Boolean search. This can be used to
            create advanced searches.

        :type rank: List of strings
        :param rank: A list of fields or rank expressions used to order the
            search results. A field can be reversed by using the - operator.
            ``['-year', 'author']``

        :type return_fields: List of strings
        :param return_fields: A list of fields which should be returned by the
            search. If this field is not specified, only IDs will be returned.
            ``['headline']``

        :type size: int
        :param size: Number of search results to specify

        :type start: int
        :param start: Offset of the first search result to return (can be used
            for paging)

        :type facet: list
        :param facet: List of fields for which facets should be returned
            ``['colour', 'size']``

        :type facet_constraints: dict
        :param facet_constraints: Use to limit facets to specific values
            specified as comma-delimited strings in a Dictionary of facets
            ``{'colour': "'blue','white','red'", 'size': "big"}``

        :type facet_sort: dict
        :param facet_sort: Rules used to specify the order in which facet
            values should be returned. Allowed values are *alpha*, *count*,
            *max*, *sum*. Use *alpha* to sort alphabetical, and *count* to sort
            the facet by number of available result.
            ``{'color': 'alpha', 'size': 'count'}``

        :type facet_top_n: dict
        :param facet_top_n: Dictionary of facets and number of facets to
            return.
            ``{'colour': 2}``

        :type t: dict
        :param t: Specify ranges for specific fields
            ``{'year': '2000..2005'}``

        :rtype: :class:`boto.cloudsearch.search.SearchResults`
        :return: Returns the results of this search

        The following examples all assume we have indexed a set of documents
        with fields: *author*, *date*, *headline*

        A simple search will look for documents whose default text search
        fields will contain the search word exactly:

        >>> search(q='Tim') # Return documents with the word Tim in them (but not Timothy)

        A simple search with more keywords will return documents whose default
        text search fields contain the search strings together or separately.

        >>> search(q='Tim apple') # Will match "tim" and "apple"

        More complex searches require the boolean search operator.

        Wildcard searches can be used to search for any words that start with
        the search string.

        >>> search(bq="'Tim*'") # Return documents with words like Tim or Timothy)

        Search terms can also be combined. Allowed operators are "and", "or",
        "not", "field", "optional", "token", "phrase", or "filter"

        >>> search(bq="(and 'Tim' (field author 'John Smith'))")

        Facets allow you to show classification information about the search
        results. For example, you can retrieve the authors who have written
        about Tim:

        >>> search(q='Tim', facet=['Author'])

        With facet_constraints, facet_top_n and facet_sort more complicated
        constraints can be specified such as returning the top author out of
        John Smith and Mark Smith who have a document with the word Tim in it.

        >>> search(q='Tim',
        ...     facet=['Author'],
        ...     facet_constraints={'author': "'John Smith','Mark Smith'"},
        ...     facet=['author'],
        ...     facet_top_n={'author': 1},
        ...     facet_sort={'author': 'count'})
        rM   )rN   )r)   r:   r;   r   r<   rC   r   r+   r=   r>   r?   r@   r   r   r   r   search   s    i
   zSearchConnection.searchc                 C   sF  d| j  }| }tj||d}|jd}zt|}W n tk
r } zn|j	dkrd}ddl
}	|	d|}
zd	|
 d   }W n tk
r   Y nX td
| td| |W 5 d}~X Y nX d|krd|kr|d D ]&}|d dkrtd||d f |qnd|kr,tdt| |||d< | |d< tf |S )zMake a call to CloudSearch

        :type query: :class:`boto.cloudsearch.search.Query`
        :param query: A group of search criteria

        :rtype: :class:`boto.cloudsearch.search.SearchResults`
        :return: search results
        zhttp://%s/2011-02-01/search)rH   zutf-8i   r   Nz*<html><body><h1>403 Forbidden</h1>([^<]+)<z: %sz"Authentication error from Amazon%sz%Got non-json response from Amazon. %smessageserrorZseverityfatalz Error processing search %s => %smessagez"Unknown error processing search %sr   r   )rL   rI   requestsgetcontentdecoder   loads
ValueErrorstatus_codererO   groupsstripAttributeErrorr   dumpsr   )r)   r   urlrH   rbodydataemsgr\   gmr   r   r   __call__  sD    	

 

zSearchConnection.__call__c                 c   sL   | | d}d}||krH| |}|j}|V  | j|j7  _|d7 }qdS )a  Get a generator to iterate over all pages of search results

        :type query: :class:`boto.cloudsearch.search.Query`
        :param query: A group of search criteria

        :type per_page: int
        :param per_page: Number of docs in each :class:`boto.cloudsearch.search.SearchResults` object.

        :rtype: generator
        :return: Generator containing :class:`boto.cloudsearch.search.SearchResults`
        r   r3   N)rA   r(   r   r'   )r)   r   Zper_pager4   r(   resultsr   r   r   get_all_paged>  s    
zSearchConnection.get_all_pagedc                 c   sL   d}d}||krH| |}|j }|D ]
}|V  q"| j|j7  _|d7 }qdS )a  Get a generator to iterate over all search results

        Transparently handles the results paging from Cloudsearch
        search results so even if you have many thousands of results
        you can iterate over all results in a reasonably efficient
        manner.

        :type query: :class:`boto.cloudsearch.search.Query`
        :param query: A group of search criteria

        :rtype: generator
        :return: All docs matching query
        r   r3   N)r(   r   r'   )r)   r   r4   r(   rj   docr   r   r   get_all_hitsT  s    zSearchConnection.get_all_hitsc                 C   s   | d | |jS )zReturn the total number of hits for query

        :type query: :class:`boto.cloudsearch.search.Query`
        :param query: a group of search criteria

        :rtype: int
        :return: Total number of hits for query
        r3   )rA   r   )r)   r   r   r   r   get_num_hitsl  s    	
zSearchConnection.get_num_hits)NN)NNNNr8   r   NNNNN)NNNNr8   r   NNNNN)
r   r	   r
   r-   rN   rO   ri   rk   rm   rn   r   r   r   r   rJ      s.   
             
             
q*rJ   )mathr   Zboto.compatr   r   r   rU   	Exceptionr   r   objectr   r7   rJ   r   r   r   r   <module>   s   *D