U
    W+d4&                     @   s   d dl Zd dlmZ d dl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G dd de
ZdS )    N)jsonc                   @   s   e Zd ZdS )SearchServiceExceptionN__name__
__module____qualname__ r   r   =/tmp/pip-unpacked-wheel-dlxw5sjy/boto/cloudsearch/document.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ZdS )EncodingErrorz
    Content sent for Cloud Search indexing was incorrectly encoded.

    This usually happens when a document is marked as unicode but non-unicode
    characters are present.
    Nr   r   r   __doc__r   r   r   r	   r   %   s   r   c                   @   s   e Zd ZdZdS )ContentTooLongErrorz
    Content sent for Cloud Search indexing was too long

    This will usually happen when documents queued for indexing add up to more
    than the limit allowed per upload batch (5MB)

    Nr   r   r   r   r	   r   .   s   r   c                   @   sL   e Zd Z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S )DocumentServiceConnectiona+  
    A CloudSearch document service.

    The DocumentServiceConection is used to add, remove and update documents in
    CloudSearch. Commands are uploaded to CloudSearch in SDF (Search Document Format).

    To generate an appropriate SDF, use :func:`add` to add or update documents,
    as well as :func:`delete` to remove documents.

    Once the set of documents is ready to be index, use :func:`commit` to send the
    commands to CloudSearch.

    If there are a lot of documents to index, it may be preferable to split the
    generation of SDF data and the actual uploading into CloudSearch. Retrieve
    the current SDF with :func:`get_sdf`. If this file is the uploaded into S3,
    it can be retrieved back afterwards for upload into CloudSearch using
    :func:`add_sdf_from_s3`.

    The SDF is not cleared after a :func:`commit`. If you wish to continue
    using the DocumentServiceConnection for another batch upload of commands,
    you will need to :func:`clear_sdf` first to stop the previous batch of
    commands from being uploaded again.

    Nc                 C   s*   || _ || _| js|j| _g | _d | _d S )N)domainendpointZdoc_service_endpointdocuments_batch_sdf)selfr   r   r   r   r	   __init__R   s    z"DocumentServiceConnection.__init__enc                 C   s    d||||d}| j | dS )a  
        Add a document to be processed by the DocumentService

        The document will not actually be added until :func:`commit` is called

        :type _id: string
        :param _id: A unique ID used to refer to this document.

        :type version: int
        :param version: Version of the document being indexed. If a file is
            being reindexed, the version should be higher than the existing one
            in CloudSearch.

        :type fields: dict
        :param fields: A dictionary of key-value pairs to be uploaded .

        :type lang: string
        :param lang: The language code the data is in. Only 'en' is currently
            supported
        add)typeidversionlangfieldsNr   append)r   _idr   r   r   dr   r   r	   r   Z   s    zDocumentServiceConnection.addc                 C   s   d||d}| j | dS )a  
        Schedule a document to be removed from the CloudSearch service

        The document will not actually be scheduled for removal until :func:`commit` is called

        :type _id: string
        :param _id: The unique ID of this document.

        :type version: int
        :param version: Version of the document to remove. The delete will only
            occur if this version number is higher than the version currently
            in the index.
        delete)r   r   r   Nr   )r   r   r   r    r   r   r	   r!   t   s    z DocumentServiceConnection.deletec                 C   s   | j r| j S t| jS )z
        Generate the working set of documents in Search Data Format (SDF)

        :rtype: string
        :returns: JSON-formatted string of the documents in SDF
        )r   r   dumpsr   r   r   r   r	   get_sdf   s    z!DocumentServiceConnection.get_sdfc                 C   s   d| _ g | _dS )z
        Clear the working documents from this DocumentServiceConnection

        This should be used after :func:`commit` if the connection will be reused
        for another set of documents.
        N)r   r   r#   r   r   r	   	clear_sdf   s    z#DocumentServiceConnection.clear_sdfc                 C   s   |  | _dS )a  
        Load an SDF from S3

        Using this method will result in documents added through
        :func:`add` and :func:`delete` being ignored.

        :type key_obj: :class:`boto.s3.key.Key`
        :param key_obj: An S3 key which contains an SDF
        N)Zget_contents_as_stringr   )r   Zkey_objr   r   r	   add_sdf_from_s3   s    z)DocumentServiceConnection.add_sdf_from_s3c                 C   s   |   }d|krBtjd |d}tj||d |d   d| j }t }tjj	dddd}|
d	| |
d
| |j||ddid}t|| |S )aD  
        Actually send an SDF to CloudSearch for processing

        If an SDF file has been explicitly loaded it will be used. Otherwise,
        documents added through :func:`add` and :func:`delete` will be used.

        :rtype: :class:`CommitResponse`
        :returns: A summary of documents added and deleted
        z: nullz@null value in sdf detected.  This will probably raise 500 error.d   z$http://%s/2011-02-01/documents/batch   2      )pool_connectionspool_maxsizemax_retrieszhttp://zhttps://zContent-Typezapplication/json)dataheaders)r$   botologerrorindexr   requestsSessionadaptersHTTPAdaptermountpostCommitResponse)r   sdfr3   urlsessionadapterrr   r   r	   commit   s     

z DocumentServiceConnection.commit)NN)r   )r   r   r   r   r   r   r!   r$   r%   r&   r@   r   r   r   r	   r   8   s   


r   c                   @   s    e Zd ZdZdd Zdd ZdS )r:   aj  Wrapper for response to Cloudsearch document batch commit.

    :type response: :class:`requests.models.Response`
    :param response: Response from Cloudsearch /documents/batch API

    :type doc_service: :class:`boto.cloudsearch.document.DocumentServiceConnection`
    :param doc_service: Object containing the documents posted and methods to
        retry

    :raises: :class:`boto.exception.BotoServerError`
    :raises: :class:`boto.cloudsearch.document.SearchServiceException`
    :raises: :class:`boto.cloudsearch.document.EncodingError`
    :raises: :class:`boto.cloudsearch.document.ContentTooLongError`
    c              	   C   s0  || _ || _|| _|jd}zt|| _W n8   tj	d
|| j tjj| j jd|dY nX | jd | _| jdkrdd | jd	g D | _| jD ]&}d
|krtdq|dkrtdqd| jksd| jkrtd| jdd ng | _| jd | _| jd | _| d| j | d| j d S )Nzutf-8z9Error indexing documents.
Response Content:
{0}

SDF:
{1} )bodystatusr2   c                 S   s   g | ]}| d qS )message)get).0er   r   r	   
<listcomp>   s     z+CommitResponse.__init__.<locals>.<listcomp>errorszIllegal Unicode characterz%Illegal Unicode character in documentzThe Content-Length is too longzContent was too longaddsdeleteszError indexing documents => %srD   r   r!   )responsedoc_servicer;   contentdecoder   loadsr0   r1   r2   format	exceptionZBotoServerErrorstatus_coderC   rE   rI   r   r   r   rJ   rK   _check_num_ops)r   rL   rM   r;   _bodyrG   r   r   r	   r      sB    
 




zCommitResponse.__init__c                    s8   t  fdd| jjD }||kr4td ||dS )aX  Raise exception if number of ops in response doesn't match commit

        :type type_: str
        :param type_: Type of commit operation: 'add' or 'delete'

        :type response_num: int
        :param response_num: Number of adds or deletes in the response.

        :raises: :class:`boto.cloudsearch.document.CommitMismatchError`
        c                    s   g | ]}|d   kr|qS )r   r   )rF   r    type_r   r	   rH   	  s    z1CommitResponse._check_num_ops.<locals>.<listcomp>z<Incorrect number of {0}s returned. Commit: {1} Response: {2}N)lenrM   r   r
   rQ   )r   rW   Zresponse_numZ
commit_numr   rV   r	   rT      s      zCommitResponse._check_num_opsN)r   r   r   r   r   rT   r   r   r   r	   r:      s   #r:   )Zboto.exceptionr0   Zboto.compatr   r4   	Exceptionr   r
   r   r   objectr   r:   r   r   r   r	   <module>   s   	
 