本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
在 Amazon OpenSearch Service 中压缩 HTTP 请求
您可以使用 gzip 压缩压缩在 Amazon OpenSearch Service 域中压缩 HTTP 请求和响应。Gzip 压缩可帮助您缩小文档的大小,降低带宽利用率和延迟时间,从而提高传输速度。
所有运行 OpenSearch 或 Elasticsearch 6.0 或更高版本的域都支持 Gzip 压缩。一些 OpenSearch 客户端具有对 gzip 压缩的内置支持,许多编程语言都具有简化过程的库。
启用 gzip 压缩
不要与类似的 Opensearch 设置混淆,http_compression.enabled
特定于 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
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 库,比如请求
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)