U
    3d^?                     @   s   d dl mZ d dlmZmZmZ d dlZd dlmZ dZ	dZ
dZd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sixN)CloudSearchDomainConnectionsimpleZ
structuredZluceneZdismaxc                   @   s   e Zd ZdS )SearchServiceExceptionN)__name__
__module____qualname__ r   r   </tmp/pip-unpacked-wheel-d7dsrkjd/boto/cloudsearch2/search.pyr   "   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	 | _i | _d
|kr|d
  D ]:\}}d|krtt	dd t
dd |dg D | j|< qtt| j| jj | _d S )Nstatusridztime-mshitsfoundhitstartquerysearch_servicefacetsZbucketsc                 s   s   | ]\}}||fV  qd S Nr   ).0kvr   r   r   	<genexpr>4   s     z)SearchResults.__init__.<locals>.<genexpr>c                 S   s   | d | d fS )Nvaluecountr   )xr   r   r   <lambda>4       z(SearchResults.__init__.<locals>.<lambda>)r   Ztime_msr   docsr   r   r   r   itemsdictr   getr   	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__8   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.cloudsearch2.search.SearchResults`
        :return: the following page of search results
           N)r   pager'   r   r&   r   StopIterationr.   r   r   r   	next_page>   s
    zSearchResults.next_pageN)r	   r
   r   r,   r/   r1   r5   r   r   r   r   r   &   s   r   c                   @   s2   e Zd ZdZdddZdd Zd	d
 Zdd ZdS )Queryi  N
   r   c                 C   sj   || _ || _|| _|pi | _|p"g | _|p,g | _|| _|	p<i | _|
pFi | _|| _	|| _
d| _| | d S Nr   )qparserfqexprsortreturn_fieldsr   r*   	highlightpartialoptionsr3   update_size)r(   r9   r:   r;   r<   r>   sizer   r=   r*   r?   r@   rA   r   r   r   r,   P   s    




zQuery.__init__c                 C   s.   || _ | j tjks| j dkr"tjn| j | _d S r8   )rC   r6   RESULTS_PER_PAGEr&   )r(   Znew_sizer   r   r   rB   b   s    zQuery.update_sizec                 C   s$  | j | jd}| jr| j|d< | jr.| j|d< | jr>| j|d< | jrft| jD ]\}}||d| < qP| jrt| jD ]*\}}t	|tj
st|}||d| < qx| jrt| jD ]\}}||d| < q| jr| j|d< | jrd	| j|d
< | jdk	r| j|d< | jr d	| j|d< |S )zTransform search parameters from instance properties to a dictionary

        :rtype: dict
        :return: search parameters
        r   rC   r9   zq.parserr;   expr.%sfacet.%shighlight.%sz	q.options,returnNr@   r=   r   r&   r9   r:   r;   r<   r   	iteritemsr*   
isinstancestring_typesr   dumpsr?   rA   r>   joinr@   r=   )r(   paramsr   r   r   r   r   	to_paramsg   s6    





zQuery.to_paramsc                 C   sL  | j | jd}| jr| j|d< | jr.| j|d< | jr>| j|d< | jrri }t| jD ]\}}||d| < qT||d< | jri }t| jD ]*\}}t	|tj
st|}||d| < q||d< | jri }t| jD ]\}}||d	| < q||d
< | jr| j|d< | jrd| j|d< | jdk	r0| j|d< | jrHd| j|d< |S )z
        Transform search parameters from instance properties to a dictionary
        that CloudSearchDomainConnection can accept

        :rtype: dict
        :return: search parameters
        rE   r9   Zquery_parserZfilter_queryrF   r<   rG   r*   rH   r?   Zquery_optionsrI   retNr@   r=   rK   )r(   rQ   r<   r   r   r*   r?   r   r   r   to_domain_connection_params   sB    





z!Query.to_domain_connection_params)NNNNNr7   r   NNNNN)r	   r
   r   rD   r,   rB   rR   rT   r   r   r   r   r6   L   s                  
-r6   c                   @   sZ   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d Z
dd ZdS )SearchConnectionNc                 C   s   || _ || _t | _|s"|j| _d| _| j r| j jr| j jjrT| j j	 | jj
d< t| j jdd| _| jr| j j}t| j|j|j|j|jd| _d S )NFhttpsign_request)hostaws_access_key_idaws_secret_access_keyregionprovider)domainendpointrequestsSessionsessionZsearch_service_endpointrW   layer1	use_proxyZget_proxy_url_with_authproxiesgetattrr   rY   rZ   r[   r\   domain_connection)r(   r]   r^   rb   r   r   r   r,      s&    

zSearchConnection.__init__r7   r   c                 C   s    t |||||||||	|
||dS )N)r9   r:   r;   r<   r>   rC   r   r*   r?   r=   r@   rA   )r6   )r(   r9   r:   r;   rankr>   rC   r   r*   r?   r=   r@   rA   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 parser: string
        :param parser: The parser to use. 'simple', 'structured', 'lucene', 'dismax'

        :type fq: string
        :param fq: The filter query to use.

        :type sort: List of strings
        :param sort: A list of fields or rank expressions used to order the
            search results. Order is handled by adding 'desc' or 'asc' after the field name.
            ``['year desc', 'author asc']``

        :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: dict
        :param facet: Dictionary of fields for which facets should be returned
            The facet value is string of JSON options
            ``{'year': '{sort:"bucket", size:3}', 'genres': '{buckets:["Action","Adventure","Sci-Fi"]}'}``

        :type highlight: dict
        :param highlight: Dictionary of fields for which highlights should be returned
            The facet value is string of JSON options
            ``{'genres': '{format:'text',max_phrases:2,pre_tag:'<b>',post_tag:'</b>'}'}``

        :type partial: bool
        :param partial: Should partial results from a partioned service be returned if
            one or more index partitions are unreachable.

        :type options: str
        :param options: Options for the query parser specified in *parser*.
            Specified as a string in JSON format.
            ``{fields: ['title^5', 'description']}``

        :rtype: :class:`boto.cloudsearch2.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(q="'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(q="(and 'Tim' (field author 'John Smith'))", parser='structured')

        Facets allow you to show classification information about the search
        results. For example, you can retrieve the authors who have written
        about Tim with a max of 3

        >>> search(q='Tim', facet={'Author': '{sort:"bucket", size:3}'})
        )r9   r:   r;   rg   r>   rC   r   r*   r?   r=   r@   rA   )rh   )r(   r9   r:   r;   rg   r>   rC   r   r*   r?   r=   r@   rA   r   r   r   r   search   s    Z    zSearchConnection.searchc                 C   s   | j j|ddf|S )Nr9    )rf   ri   pop)r(   rQ   r   r   r   _search_with_authR  s    z"SearchConnection._search_with_authc                 C   s2   d| j |f }| jj||d}|jd|jdS )Nzhttp://%s/%s/search)rQ   zutf-8)bodystatus_code)r^   ra   r%   contentdecodern   )r(   rQ   api_versionurlrespr   r   r   _search_without_authU  s    z%SearchConnection._search_without_authc                 C   s\  d}| j r| j jr| j jj}| jr2| | }n| | |}|d }|d }zt	|}W n| t
k
r   |dkrd}ddl}|d|}	zd	|	 d   }W n tk
r   Y nX td
| td| |Y nX d|kr$d|kr$|d D ]&}
|
d dkrtdt|
d f |qnd|krBtdt| |||d< | |d< tf |S )zMake a call to CloudSearch

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

        :rtype: :class:`boto.cloudsearch2.search.SearchResults`
        :return: search results
        z
2013-01-01rm   rn   i  rj   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   )r]   rb   Z
APIVersionrW   rl   rT   rt   rR   r   loads
ValueErrorreri   groupsstripAttributeErrorr   rQ   rO   r   )r(   r   rq   datar_bodyZ_status_codemsgr{   gmr   r   r   __call__[  sL    	


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.cloudsearch2.search.Query`
        :param query: A group of search criteria

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

        :rtype: generator
        :return: Generator containing :class:`boto.cloudsearch2.search.SearchResults`
        r   r2   N)rB   r'   r   r&   )r(   r   Zper_pager3   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.cloudsearch2.search.Query`
        :param query: A group of search criteria

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

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

        :rtype: int
        :return: Total number of hits for query
        r2   )rB   r   )r(   r   r   r   r   get_num_hits  s    	
zSearchConnection.get_num_hits)NN)NNNNNr7   r   NNNNN)NNNNNr7   r   NNNNN)r	   r
   r   r,   rh   ri   rl   rt   r   r   r   r   r   r   r   r   rU      s2   
             
             
a1rU   )mathr   Zboto.compatr   r   r   r_   Zboto.cloudsearchdomain.layer1r   ZSIMPLEZ
STRUCTUREDZLUCENEZDISMAX	Exceptionr   objectr   r6   rU   r   r   r   r   <module>   s   & 