def delete_doc_in_cloudsearch(doc_ids, cloudsearch_domain_name, validate=True, region='ap-southeast-2'): """ :param doc_ids: the doc id array :param cloudsearch_domain_name: the domain name !!! This method is in-efficient for validating. """ conn = boto.cloudsearch2.connect_to_region(region) domain = conn.describe_domains([cloudsearch_domain_name]) \ ['DescribeDomainsResponse']['DescribeDomainsResult']['DomainStatusList'] doc_service = CloudSearchDomainConnection( host=domain[0]['DocService']['Endpoint'], region=region) if len(doc_ids) > 0: batch = [] for id in doc_ids: batch.append({"id": str(id), "type": "delete"}) doc_service.upload_documents(json.dumps(batch), 'application/json') if validate: # we need some time for the cloudsearch to apply the deletion. MAX_RETRIES = 100 SLEEP_GAP = 10 for id in doc_ids: retry = 0 while retry < MAX_RETRIES: result = doc_service.search(query="(term field=_id '%s')" % id, query_parser='structured') if (result['hits']['found'] == 0): break retry += 1 sleep(SLEEP_GAP) if retry >= MAX_RETRIES: raise ValueError( "Intended to delete cloudsearch documents with id %s, but it still exists after deletion. " "Culprit document: %s" % (doc_ids, id))
class DocumentServiceConnection(object): """ 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. """ def __init__(self, domain=None, endpoint=None): self.domain = domain self.endpoint = endpoint if not self.endpoint: self.endpoint = domain.doc_service_endpoint self.documents_batch = [] self._sdf = None # Copy proxy settings from connection and check if request should be signed self.proxy = {} self.sign_request = False if self.domain and self.domain.layer1: if self.domain.layer1.use_proxy: self.proxy = {'http': self.domain.layer1.get_proxy_url_with_auth()} self.sign_request = getattr(self.domain.layer1, 'sign_request', False) if self.sign_request: # Create a domain connection to send signed requests layer1 = self.domain.layer1 self.domain_connection = CloudSearchDomainConnection( host=self.endpoint, aws_access_key_id=layer1.aws_access_key_id, aws_secret_access_key=layer1.aws_secret_access_key, region=layer1.region, provider=layer1.provider ) def add(self, _id, fields): """ 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 fields: dict :param fields: A dictionary of key-value pairs to be uploaded . """ d = {'type': 'add', 'id': _id, 'fields': fields} self.documents_batch.append(d) def delete(self, _id): """ 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. """ d = {'type': 'delete', 'id': _id} self.documents_batch.append(d) def get_sdf(self): """ Generate the working set of documents in Search Data Format (SDF) :rtype: string :returns: JSON-formatted string of the documents in SDF """ return self._sdf if self._sdf else json.dumps(self.documents_batch) def clear_sdf(self): """ 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. """ self._sdf = None self.documents_batch = [] def add_sdf_from_s3(self, key_obj): """ 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 """ #@todo:: (lucas) would be nice if this could just take an s3://uri..." self._sdf = key_obj.get_contents_as_string() def _commit_with_auth(self, sdf, api_version): return self.domain_connection.upload_documents(sdf, 'application/json') def _commit_without_auth(self, sdf, api_version): url = "http://%s/%s/documents/batch" % (self.endpoint, api_version) # Keep-alive is automatic in a post-1.0 requests world. session = requests.Session() session.proxies = self.proxy adapter = requests.adapters.HTTPAdapter( pool_connections=20, pool_maxsize=50, max_retries=5 ) session.mount('http://', adapter) session.mount('https://', adapter) resp = session.post(url, data=sdf, headers={'Content-Type': 'application/json'}) return resp def commit(self): """ 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 """ sdf = self.get_sdf() if ': null' in sdf: boto.log.error('null value in sdf detected. This will probably ' 'raise 500 error.') index = sdf.index(': null') boto.log.error(sdf[index - 100:index + 100]) api_version = '2013-01-01' if self.domain and self.domain.layer1: api_version = self.domain.layer1.APIVersion if self.sign_request: r = self._commit_with_auth(sdf, api_version) else: r = self._commit_without_auth(sdf, api_version) return CommitResponse(r, self, sdf, signed_request=self.sign_request)
class DocumentServiceConnection(object): """ 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. """ def __init__(self, domain=None, endpoint=None): self.domain = domain self.endpoint = endpoint if not self.endpoint: self.endpoint = domain.doc_service_endpoint self.documents_batch = [] self._sdf = None # Copy proxy settings from connection and check if request should be signed self.proxy = {} self.sign_request = False if self.domain and self.domain.layer1: if self.domain.layer1.use_proxy: self.proxy = { 'http': self.domain.layer1.get_proxy_url_with_auth() } self.sign_request = getattr(self.domain.layer1, 'sign_request', False) if self.sign_request: # Create a domain connection to send signed requests layer1 = self.domain.layer1 self.domain_connection = CloudSearchDomainConnection( host=self.endpoint, aws_access_key_id=layer1.aws_access_key_id, aws_secret_access_key=layer1.aws_secret_access_key, region=layer1.region, provider=layer1.provider) def add(self, _id, fields): """ 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 fields: dict :param fields: A dictionary of key-value pairs to be uploaded . """ d = {'type': 'add', 'id': _id, 'fields': fields} self.documents_batch.append(d) def delete(self, _id): """ 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. """ d = {'type': 'delete', 'id': _id} self.documents_batch.append(d) def get_sdf(self): """ Generate the working set of documents in Search Data Format (SDF) :rtype: string :returns: JSON-formatted string of the documents in SDF """ return self._sdf if self._sdf else json.dumps(self.documents_batch) def clear_sdf(self): """ 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. """ self._sdf = None self.documents_batch = [] def add_sdf_from_s3(self, key_obj): """ 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 """ #@todo:: (lucas) would be nice if this could just take an s3://uri..." self._sdf = key_obj.get_contents_as_string() def _commit_with_auth(self, sdf, api_version): return self.domain_connection.upload_documents(sdf, 'application/json') def _commit_without_auth(self, sdf, api_version): url = "http://%s/%s/documents/batch" % (self.endpoint, api_version) # Keep-alive is automatic in a post-1.0 requests world. session = requests.Session() session.proxies = self.proxy adapter = requests.adapters.HTTPAdapter(pool_connections=20, pool_maxsize=50, max_retries=5) session.mount('http://', adapter) session.mount('https://', adapter) resp = session.post(url, data=sdf, headers={'Content-Type': 'application/json'}) return resp def commit(self): """ 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 """ sdf = self.get_sdf() if ': null' in sdf: boto.log.error('null value in sdf detected. This will probably ' 'raise 500 error.') index = sdf.index(': null') boto.log.error(sdf[index - 100:index + 100]) api_version = '2013-01-01' if self.domain and self.domain.layer1: api_version = self.domain.layer1.APIVersion if self.sign_request: r = self._commit_with_auth(sdf, api_version) else: r = self._commit_without_auth(sdf, api_version) return CommitResponse(r, self, sdf, signed_request=self.sign_request)