在 Amazon OpenSearch Service 中壓縮 HTTP 請求 - Amazon OpenSearch Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

在 Amazon OpenSearch Service 中壓縮 HTTP 請求

您可以使用 gzip 壓縮來壓縮 Amazon OpenSearch Service 網域中的 HTTP 請求和回應。Gzip 壓縮可以幫助您減少文件的大小,降低頻寬使用率和延遲,進而提高傳輸速度。

執行 OpenSearch 或 Elasticsearch 6.0 或更高版本的所有網域都支援 Gzip 壓縮。有些 OpenSearch 用戶端內建支援 gzip 壓縮,許多程式設計語言都有可簡化該程序的程式庫。

啟用 gzip 壓縮

不要與類似的 OpenSearch 設定混淆,http_compression.enabled 專門針對 OpenSearch Service,可以啟用或停用網域上的 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)