本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
压缩 HTTP 请求
Amazon Elasticsearch Service (Amazon ES) 域运行 Elasticsearch 6.0 或更高版本,对于大多数 HTTP 请求和响应支持 gzip 压缩,这可以减少延迟并节省带宽。有些 Elasticsearch 客户端具有对 gzip 压缩的内置支持,很多编程语言具有简化该过程的库。
启用 gzip 压缩
不要与类似的 Elasticsearch 设置混淆,http_compression.enabled
特定于 Amazon ES 并在域上启用或禁用 gzip 压缩。运行 Elasticsearch 7.x 的域默认启用 功能,而运行 6.x 的域默认禁用 功能。
要启用 gzip 压缩,请发送以下请求:
PUT _cluster/settings { "persistent" : { "http_compression.enabled": true } }
对 _cluster/settings
的请求必须未压缩,因此您可能需要使用单独的客户端或标准 HTTP 请求来更新集群设置。
必需的标头
在包含 gzip 压缩的请求正文时,请保留标准 Content-Type:
application/json
标头,然后添加 Content-Encoding: gzip
标头。要接受 gzip 压缩的响应,还请添加 Accept-Encoding: gzip
标头。如果 Elasticsearch 客户端支持 gzip 压缩,则它可能自动包含这些标头。
Sample代码 (Python 3)
以下示例使用 elasticsearch-py
from elasticsearch import Elasticsearch, 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. es = Elasticsearch( 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(es.index(index='movies', id='1', body=document, refresh=True)) # # Older versions of the client might require doc_type. # print(es.index(index='movies', doc_type='_doc', id='1', body=document, refresh=True))
或者,您也可以指定正确的标头,自行压缩请求正文,并使用标准 HTTP 库,如 Requests (请求)
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)