在亚马逊 OpenSearch 服务中压缩 HTTP 请求 - 亚马逊 OpenSearch 服务
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在亚马逊 OpenSearch 服务中压缩 HTTP 请求

您可以使用 gzip 压缩来压缩亚马逊 OpenSearch 服务域中的 HTTP 请求和响应。Gzip 压缩可帮助您缩小文档的大小,降低带宽利用率和延迟时间,从而提高传输速度。

所有运行 OpenSearch 或 Elasticsearch 6.0 或更高版本的域都支持 Gzip 压缩。有些 OpenSearch 客户端内置了对 gzip 压缩的支持,而许多编程语言都有简化该过程的库。

启用 gzip 压缩

不要与类似的设置混淆,http_compression.enabled该 OpenSearch 设置特定于 OpenSearch 服务,可在域上启用或禁用 gzip 压缩。域名正在运行 OpenSearch 或 Elasticsearch 7. x 默认启用了 gzip 压缩,而运行 Elasticsearch 的域名则为 6。 x 默认将其禁用。

要启用 gzip 压缩,请发送以下请求:

PUT _cluster/settings { "persistent" : { "http_compression.enabled": true } }

必须解压缩对 _cluster/settings 的请求,因此您可能需要使用单独的客户端或标准 HTTP 请求来更新群集设置。

要确认您已成功启用 gzip 压缩,请发送以下请求:

GET _cluster/settings?include_defaults=true

确保在响应中看到以下设置:

... "http_compression": { "enabled": "true" } ...

必需的标头

当包含 gzip 压缩的请求主体时,请保留标准的 Content-Type: application/json 标头,然后添加 Content-Encoding: gzip 标头。要接受 gzip 压缩的响应,也请添加 Accept-Encoding: gzip 标头。如果 OpenSearch 客户端支持 gzip 压缩,则可能会自动包含这些标头。

示例代码 (Python 3)

以下示例使用 opensearch-py 执行压缩并发送请求。此代码使用您的 IAM 证书对请求进行签名。

from opensearchpy import OpenSearch, RequestsHttpConnection from requests_aws4auth import AWS4Auth import boto3 host = '' # e.g. my-test-domain.us-east-1.es.amazonaws.com region = '' # e.g. us-west-1 service = 'es' credentials = boto3.Session().get_credentials() awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token) # Create the client. search = OpenSearch( hosts = [{'host': host, 'port': 443}], http_auth = awsauth, use_ssl = True, verify_certs = True, http_compress = True, # enables gzip compression for request bodies connection_class = RequestsHttpConnection ) document = { "title": "Moneyball", "director": "Bennett Miller", "year": "2011" } # Send the request. print(search.index(index='movies', id='1', body=document, refresh=True)) # print(search.index(index='movies', doc_type='_doc', id='1', body=document, refresh=True))

或者,您可以指定适当的头,自己压缩请求正文,并使用标准的 HTTP 库,比如请求。此代码使用 HTTP 基本凭据对请求进行签名,如果您使用访问权限的精细控制,则域会提供支持。

import requests import gzip import json base_url = '' # The domain with https:// and a trailing slash. For example, https://my-test-domain.us-east-1.es.amazonaws.com/ auth = ('master-user', 'master-user-password') # For testing only. Don't store credentials in code. headers = {'Accept-Encoding': 'gzip', 'Content-Type': 'application/json', 'Content-Encoding': 'gzip'} document = { "title": "Moneyball", "director": "Bennett Miller", "year": "2011" } # Compress the document. compressed_document = gzip.compress(json.dumps(document).encode()) # Send the request. path = 'movies/_doc?refresh=true' url = base_url + path response = requests.post(url, auth=auth, headers=headers, data=compressed_document) print(response.status_code) print(response.text)