在 Amazon OpenSearch 服務中壓縮 HTTP 請求 - Amazon OpenSearch 服務

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

在 Amazon OpenSearch 服務中壓縮 HTTP 請求

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

所有運行 OpenSearch 或彈性搜索 6.0 或更高版本的域都支持 Gzip 壓縮。有些用 OpenSearch 戶端內建 gzip 壓縮支援,而且許多程式設計語言都有簡化程序的程式庫。

啟用 gzip 壓縮

不要與類似的 OpenSearch 設置混淆,特定http_compression.enabled於 OpenSearch 服務,並啟用或禁用域上的 gzip 壓縮。域運行 OpenSearch 或彈性搜索 7. x 默認情況下啟用了 gzip 壓縮,而運行彈性搜索 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)