View a markdown version of this page

向亚马逊摄取数据 OpenSearch 无服务器集合 - 亚马逊 OpenSearch 服务
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)。

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

向亚马逊摄取数据 OpenSearch 无服务器集合

以下部分提供了有关支持向亚马逊提取数据的采集管道的详细信息 OpenSearch 无服务器集合。它们还涵盖了一些可用于与之交互的客户端 OpenSearch API 操作。您的客户应与兼容 OpenSearch 2.x 以便与集成 OpenSearch 无服务器。

亚马逊 OpenSearch 无服务器支持 OpenSearch 采集管道,无论您使用哪个客户端或集成来发送文档,都可以在为文档编制索引之前对其进行转换或丰富。采集管道是一系列处理器,用于在为文档编制索引之前对其进行转换。例如,您可以使用采集管道移除敏感字段、规范化字段值、解析时间戳或生成用于语义搜索的向量嵌入。因为管道在流入 OpenSearch 无服务器,您的文档无需在每个客户端中自定义预处理逻辑即可获得一致的转换。有关更多信息,请参阅 在亚马逊收录管道 OpenSearch 无服务器。

所需的最低权限

为了将数据摄取到 OpenSearch 无服务器集合,写入数据的主体必须具有以下最低权限 数据访问政策:

[ { "Rules":[ { "ResourceType":"index", "Resource":[ "index/target-collection/logs" ], "Permission":[ "aoss:CreateIndex", "aoss:WriteDocument", "aoss:UpdateIndex" ] } ], "Principal":[ "arn:aws:iam::123456789012:user/my-user" ] } ]

如果您计划写入到其他索引,则权限可以更广。例如,您可以授予所有索引的权限,而不是指定单个目标索引(索引/target-collection/*),或索引的子集(索引/target-collection/logs*)。

供所有可用内容参考 OpenSearch API 操作及其相关权限,请参阅 Amazon OpenSearch Serverless 中支持的操作和插件。

OpenSearch 摄取

而不是使用第三方客户端将数据直接发送到 OpenSearch 无服务器收集,你可以使用亚马逊 OpenSearch 摄取。您可以将数据生成器配置为将数据发送到 OpenSearch 摄取,它会自动将数据传送到您指定的集合中。你也可以配置 OpenSearch 在交付数据之前,先摄取数据以对其进行转换。有关更多信息,请参阅 亚马逊 OpenSearch 摄取概述。

一个 OpenSearch 摄取管道需要权限才能写入 OpenSearch 配置为其接收器的无服务器集合。这些权限包括能够描述集合以及向其发送 HTTP 请求。有关使用说明 OpenSearch 摄取以向集合中添加数据,请参阅 授予 Amazon OpenSearch Ingestion 管道访问集合的权限。

要开始使用 OpenSearch 摄取,参见 教程:使用 Amazon Ingestion 将数据提取到集合中 OpenSearch。

Fluent Bit

你可以使用 Amazon 适用于 Fluent Bit 图片 还有 OpenSearch 输出插件 将数据摄入到 OpenSearch 无服务器集合。

注意

你必须拥有 2.30.0 或更高版本的 Amazon 用于 Fluent Bit 图像以便与之集成 OpenSearch 无服务器。

示例配置:

配置文件的此示例输出部分显示了如何使用 OpenSearch 以无服务器收集为目的地。添加 AWS_Service_Name 参数(即 aoss)十分重要。Host 是集合端点。

[OUTPUT] Name opensearch Match * Host collection-endpoint.us-west-2.aoss.amazonaws.com Port 443 Index my_index Trace_Error On Trace_Output On AWS_Auth On AWS_Region <region> AWS_Service_Name aoss tls On Suppress_Type_Name On

Amazon Data Firehose

消防水带支架 OpenSearch 无服务器作为交付目的地。有关将数据发送到的说明 OpenSearch 无服务器,请参阅 创建 Kinesis Data Firehose 交付流 和 选择 OpenSearch 为您的目的地提供无服务器 在 亚马逊数据 Firehose 开发者指南。

您提供给 Firehose 用于传输的 IAM 角色,必须在具有目标集合的 aoss:WriteDocument 最低权限的数据访问策略中指定,并且您必须具有预先存在的索引以向其发送数据。有关更多信息,请参阅 所需的最低权限。

在将数据发送到之前 OpenSearch 无服务器,您可能需要对数据执行转换。要了解有关使用 Lambda 函数执行此任务的更多信息,请参阅此同一指南中的 Amazon Kinesis Data Firehose 数据转换。

Go

以下示例代码使用 opensearch-go Go 的客户端,用于建立与指定对象的安全连接 OpenSearch 无服务器收集并创建单一索引。必须提供 region 和 host 的值。

package main import ( "context" "log" "strings" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" opensearch "github.com/opensearch-project/opensearch-go/v2" opensearchapi "github.com/opensearch-project/opensearch-go/v2/opensearchapi" requestsigner "github.com/opensearch-project/opensearch-go/v2/signer/awsv2" ) const endpoint = "" // serverless collection endpoint func main() { ctx := context.Background() awsCfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("<AWS_REGION>"), config.WithCredentialsProvider( getCredentialProvider("<AWS_ACCESS_KEY>", "<AWS_SECRET_ACCESS_KEY>", "<AWS_SESSION_TOKEN>"), ), ) if err != nil { log.Fatal(err) // don't log.fatal in a production-ready app } // create an AWS request Signer and load AWS configuration using default config folder or env vars. signer, err := requestsigner.NewSignerWithService(awsCfg, "aoss") // "aoss" for Amazon OpenSearch Serverless if err != nil { log.Fatal(err) // don't log.fatal in a production-ready app } // create an opensearch client and use the request-signer client, err := opensearch.NewClient(opensearch.Config{ Addresses: []string{endpoint}, Signer: signer, }) if err != nil { log.Fatal("client creation err", err) } indexName := "go-test-index" // define index mapping mapping := strings.NewReader(`{ "settings": { "index": { "number_of_shards": 4 } } }`) // create an index createIndex := opensearchapi.IndicesCreateRequest{ Index: indexName, Body: mapping, } createIndexResponse, err := createIndex.Do(context.Background(), client) if err != nil { log.Println("Error ", err.Error()) log.Println("failed to create index ", err) log.Fatal("create response body read err", err) } log.Println(createIndexResponse) // delete the index deleteIndex := opensearchapi.IndicesDeleteRequest{ Index: []string{indexName}, } deleteIndexResponse, err := deleteIndex.Do(context.Background(), client) if err != nil { log.Println("failed to delete index ", err) log.Fatal("delete index response body read err", err) } log.Println("deleting index", deleteIndexResponse) } func getCredentialProvider(accessKey, secretAccessKey, token string) aws.CredentialsProviderFunc { return func(ctx context.Context) (aws.Credentials, error) { c := &aws.Credentials{ AccessKeyID: accessKey, SecretAccessKey: secretAccessKey, SessionToken: token, } return *c, nil } }

Java

以下示例代码使用 Amazon OpenSearch Java 客户端 在 GitHub 网站(software.amazon.opensearch:opensearch-java) 与指定设备建立安全连接 OpenSearch 无服务器收集并创建单一索引。在每个示例中,将示例收集终端节点和签名区域替换为您自己的值。

客户包括 software.amazon.opensearch.client.aoss.OpenSearchClient 为了 OpenSearch 无服务器集合。它是 OpenSearchClient.create 工厂方法使用签名版本 4 签署请求 aoss 服务。如果你通过 null 对于传输选项,客户端使用默认的凭证提供程序链 Amazon 适用于 Java 2.x 的软件开发工具包。

这个 Amazon 客户端的 SDK 依赖关系是可选的,因此您必须声明 software.amazon.awssdk:sdk-core, software.amazon.awssdk:auth, software.amazon.awssdk:http-auth-aws,以及 HTTP 客户端,例如 software.amazon.awssdk:url-connection-client 在你的项目中。客户需要 Amazon 适用于 Java 2.x 的 SDK 版本 2.25.69 或更高版本。以下示例显示了 Maven 依赖关系:

<dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>aws-sdk-version</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.opensearch</groupId> <artifactId>opensearch-java</artifactId> <version>0.1.0</version> </dependency> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>sdk-core</artifactId> </dependency> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>auth</artifactId> </dependency> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>http-auth-aws</artifactId> </dependency> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>url-connection-client</artifactId> </dependency> </dependencies>
import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.opensearch.client.aoss.OpenSearchClient; import software.amazon.opensearch.client.aoss.indices.CreateIndexResponse; import software.amazon.opensearch.client.aoss.indices.DeleteIndexResponse; try (SdkHttpClient httpClient = UrlConnectionHttpClient.builder().build()) { OpenSearchClient client = OpenSearchClient.create( httpClient, "my-collection-id.us-west-2.aoss.amazonaws.com", // Serverless collection endpoint. Region.US_WEST_2, // Signing Region. null // Default credentials provider chain. ); String index = "sample-index"; // Create an index. CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index(index)); System.out.println("Create index response: " + createIndexResponse.acknowledged()); // Delete the index. DeleteIndexResponse deleteIndexResponse = client.indices().delete(d -> d.index(index)); System.out.println("Delete index response: " + deleteIndexResponse.acknowledged()); }

以下示例代码建立安全连接并将文档索引到集合中。

import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.opensearch.client.aoss.OpenSearchClient; import software.amazon.opensearch.client.aoss.core.IndexResponse; try (SdkHttpClient httpClient = UrlConnectionHttpClient.builder().build()) { OpenSearchClient client = OpenSearchClient.create( httpClient, "my-collection-id.us-west-2.aoss.amazonaws.com", Region.US_WEST_2, null); // Index a document. Map<String, Object> document = new HashMap<>(); document.put("title", "The Green Mile"); document.put("director", "Frank Darabont"); document.put("year", "1999"); IndexResponse indexResponse = client.index(i -> i.index("books-index").document(document)); System.out.println("Index response: " + indexResponse.result()); }

以下示例代码建立安全连接,然后搜索 books-index 前一个示例写入的索引。新建索引的文档可能需要很短的时间才能变为可搜索的文档,因此搜索可能不会在您索引文档后立即返回该文档。

import java.util.Map; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.opensearch.client.aoss.OpenSearchClient; import software.amazon.opensearch.client.aoss.core.SearchResponse; try (SdkHttpClient httpClient = UrlConnectionHttpClient.builder().build()) { OpenSearchClient client = OpenSearchClient.create( httpClient, "my-collection-id.us-west-2.aoss.amazonaws.com", Region.US_WEST_2, null); SearchResponse<Map> response = client.search(s -> s .index("books-index") .query(q -> q.matchAll(m -> m)), Map.class); response.hits().hits().forEach(hit -> System.out.println(hit.source())); }

如果你使用开源 开放搜索-java 客户,通行证 aoss 作为签名服务名称到 AwsSdk2Transport。以下示例代码建立了与指定内容的安全连接 OpenSearch 无服务器收集并创建单一索引。在每个示例中,将示例收集终端节点和签名区域替换为您自己的值。

import org.opensearch.client.opensearch.OpenSearchClient; import org.opensearch.client.opensearch.indices.CreateIndexRequest; import org.opensearch.client.opensearch.indices.CreateIndexResponse; import org.opensearch.client.opensearch.indices.DeleteIndexRequest; import org.opensearch.client.opensearch.indices.DeleteIndexResponse; import org.opensearch.client.transport.aws.AwsSdk2Transport; import org.opensearch.client.transport.aws.AwsSdk2TransportOptions; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; // Configure credential provider AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.create(); SdkHttpClient httpClient = ApacheHttpClient.builder().build(); // create an opensearch client and use the request-signer OpenSearchClient client = new OpenSearchClient( new AwsSdk2Transport( httpClient, "my-collection-id.us-west-2.aoss.amazonaws.com", // serverless collection endpoint "aoss", // signing service name Region.US_WEST_2, // signing service region AwsSdk2TransportOptions.builder().setCredentials(credentialsProvider).build() ) ); String index = "sample-index"; // create an index CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(index).build(); CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest); System.out.println("Create index reponse: " + createIndexResponse); // delete the index DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(index).build(); DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest); System.out.println("Delete index reponse: " + deleteIndexResponse); httpClient.close();

以下示例代码建立安全连接并将文档索引到集合中。

import java.util.HashMap; import java.util.Map; import org.opensearch.client.opensearch.OpenSearchClient; import org.opensearch.client.opensearch.core.IndexRequest; import org.opensearch.client.opensearch.core.IndexResponse; import org.opensearch.client.transport.aws.AwsSdk2Transport; import org.opensearch.client.transport.aws.AwsSdk2TransportOptions; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.create(); SdkHttpClient httpClient = ApacheHttpClient.builder().build(); OpenSearchClient client = new OpenSearchClient( new AwsSdk2Transport( httpClient, "my-collection-id.us-west-2.aoss.amazonaws.com", // serverless collection endpoint "aoss", // signing service name Region.US_WEST_2, // signing service region AwsSdk2TransportOptions.builder().setCredentials(credentialsProvider).build() ) ); // index a document Map<String, Object> document = new HashMap<>(); document.put("title", "The Green Mile"); document.put("director", "Frank Darabont"); document.put("year", "1999"); IndexRequest<Map<String, Object>> indexRequest = IndexRequest.of(i -> i .index("books-index") .document(document) ); IndexResponse indexResponse = client.index(indexRequest); System.out.println("Index response: " + indexResponse.result()); httpClient.close();

以下示例代码再次建立安全连接,然后搜索 books-index 前一个示例写入的索引。新建索引的文档可能需要很短的时间才能变为可搜索的文档,因此搜索可能不会在您索引文档后立即返回该文档。

import org.opensearch.client.opensearch.OpenSearchClient; import org.opensearch.client.opensearch.generic.Requests; import org.opensearch.client.opensearch.generic.Response; import org.opensearch.client.transport.aws.AwsSdk2Transport; import org.opensearch.client.transport.aws.AwsSdk2TransportOptions; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.create(); SdkHttpClient httpClient = ApacheHttpClient.builder().build(); OpenSearchClient client = new OpenSearchClient( new AwsSdk2Transport( httpClient, "my-collection-id.us-west-2.aoss.amazonaws.com", // serverless collection endpoint "aoss", // signing service name Region.US_WEST_2, // signing service region AwsSdk2TransportOptions.builder().setCredentials(credentialsProvider).build() ) ); Response response = client.generic() .execute( Requests.builder() .endpoint("/" + "books-index" + "/_search?typed_keys=true") .method("GET") .json("{" + " \"query\": {" + " \"match_all\": {}" + " }" + "}") .build()); httpClient.close();

JavaScript

以下示例代码使用 opensearch-js 的客户端 JavaScript 与指定设备建立安全连接 OpenSearch 无服务器集合,创建单一索引,添加文档并删除索引。必须提供 node 和 region 的值。

与之相比的重要区别 OpenSearch 服务 域 是服务名称 (aoss 而不是 es)。

Version 3

这个例子使用了 版本 3 的软件开发工具包的用于 JavaScript 在 Node.js。

const { defaultProvider } = require('@aws-sdk/credential-provider-node'); const { Client } = require('@opensearch-project/opensearch'); const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws'); async function main() { // create an opensearch client and use the request-signer const client = new Client({ ...AwsSigv4Signer({ region: 'us-west-2', service: 'aoss', getCredentials: () => { const credentialsProvider = defaultProvider(); return credentialsProvider(); }, }), node: '' # // serverless collection endpoint }); const index = 'movies'; // create index if it doesn't already exist if (!(await client.indices.exists({ index })).body) { console.log((await client.indices.create({ index })).body); } // add a document to the index const document = { foo: 'bar' }; const response = await client.index({ id: '1', index: index, body: document, }); console.log(response.body); // delete the index console.log((await client.indices.delete({ index })).body); } main();
Version 2

这个例子使用了 版本 2 的软件开发工具包的用于 JavaScript 在 Node.js。

const AWS = require('aws-sdk'); const { Client } = require('@opensearch-project/opensearch'); const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws'); async function main() { // create an opensearch client and use the request-signer const client = new Client({ ...AwsSigv4Signer({ region: 'us-west-2', service: 'aoss', getCredentials: () => new Promise((resolve, reject) => { AWS.config.getCredentials((err, credentials) => { if (err) { reject(err); } else { resolve(credentials); } }); }), }), node: '' # // serverless collection endpoint }); const index = 'movies'; // create index if it doesn't already exist if (!(await client.indices.exists({ index })).body) { console.log((await client.indices.create({ index })).body); } // add a document to the index const document = { foo: 'bar' }; const response = await client.index({ id: '1', index: index, body: document, }); console.log(response.body); // delete the index console.log((await client.indices.delete({ index })).body); } main();

Logstash

你可以使用 Logstash OpenSearch 插件 将日志发布到 OpenSearch 无服务器集合。

使用 Logstash 将数据发送到 OpenSearch 无服务器
  1. 使用 Docker 或 Linux,安装 logstash-output-opensearch 插件的 2.0.0 或更高版本。

    Docker

    Docker 使用 Logstash OSS 软件托管 OpenSearch 预安装的输出插件: opensearchproject/logstash带有opensearch输出插件的操作系统。您可以像任何其他映像一样拉取该映像:

    docker pull opensearchproject/logstash-oss-with-opensearch-output-plugin:latest
    Linux

    首先,请安装最新版本的 Logstash(如果您尚未这样做)。然后,安装版本 2.0.0 的输出插件:

    cd logstash-8.5.0/ bin/logstash-plugin install --version 2.0.0 logstash-output-opensearch

    如果已安装该插件,请将其更新到最新版本:

    bin/logstash-plugin update logstash-output-opensearch

    从插件的 2.0.0 版本开始, Amazon SDK 使用版本 3。如果你使用的是早于 8.4.0 的 Logstash 版本,则必须移除所有预安装的 Logstash 版本 Amazon 插件并安装 logstash-integration-aws 插件:

    /usr/share/logstash/bin/logstash-plugin remove logstash-input-s3 /usr/share/logstash/bin/logstash-plugin remove logstash-input-sqs /usr/share/logstash/bin/logstash-plugin remove logstash-output-s3 /usr/share/logstash/bin/logstash-plugin remove logstash-output-sns /usr/share/logstash/bin/logstash-plugin remove logstash-output-sqs /usr/share/logstash/bin/logstash-plugin remove logstash-output-cloudwatch /usr/share/logstash/bin/logstash-plugin install --version 0.1.0.pre logstash-integration-aws
  2. 为了 OpenSearch 要使用的输出插件 OpenSearch 无服务器,必须对 opensearch logstash.conf 的输出部分:

    • 在 auth_type 下,将 aoss 指定为 service_name。

    • 为 hosts 指定您的集合端点。

    • 添加参数 default_server_major_version 和 legacy_template。这些参数是插件使用所必需的 OpenSearch 无服务器。

    output { opensearch { hosts => "collection-endpoint:443" auth_type => { ... service_name => 'aoss' } default_server_major_version => 2 legacy_template => false } }

    此示例配置文件从 S3 存储桶中的文件中获取输入并将其发送到 OpenSearch 无服务器收集:

    input { s3 { bucket => "my-s3-bucket" region => "us-east-1" } } output { opensearch { ecs_compatibility => disabled hosts => "https://my-collection-endpoint.us-east-1.aoss.amazonaws.com:443" index => my-index auth_type => { type => 'aws_iam' aws_access_key_id => 'your-access-key' aws_secret_access_key => 'your-secret-key' region => 'us-east-1' service_name => 'aoss' } default_server_major_version => 2 legacy_template => false } }
  3. 然后,使用新配置运行 Logstash,以测试该插件:

    bin/logstash -f config/test-plugin.conf

Python

以下示例代码使用 opensearch-py Python 的客户端,用于建立与指定内容的安全连接 OpenSearch 无服务器集合,创建单一索引,然后搜索该索引。必须提供 region 和 host 的值。

与之相比的重要区别 OpenSearch 服务 域 是服务名称 (aoss 而不是 es)。

from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth import boto3 host = '' # serverless collection endpoint, without https:// region = '' # e.g. us-east-1 service = 'aoss' credentials = boto3.Session().get_credentials() auth = AWSV4SignerAuth(credentials, region, service) # create an opensearch client and use the request-signer client = OpenSearch( hosts=[{'host': host, 'port': 443}], http_auth=auth, use_ssl=True, verify_certs=True, connection_class=RequestsHttpConnection, pool_maxsize=20, ) # create an index index_name = 'books-index' create_response = client.indices.create( index_name ) print('\nCreating index:') print(create_response) # index a document document = { 'title': 'The Green Mile', 'director': 'Stephen King', 'year': '1996' } response = client.index( index = 'books-index', body = document, id = '1' ) delete_response = client.indices.delete( index_name ) print('\nDeleting index:') print(delete_response)
注意

这个 id = '1' 此示例中的参数指定自定义文档 ID。仅支持自定义文档 ID 搜索 集合。对于时间序列和矢量搜索集合,不支持使用自定义文档 ID 进行索引,这将返回错误。省略 id 索引到时间序列或向量搜索集合时的参数。

注意

您收录到的每份文档 NextGen 时间序列 集合必须包含索引的指定时间戳字段,并且其值必须是有效的 date。 OpenSearch Serverless 拒绝省略该字段或提供无效值的文档。有关更多信息,请参阅 在时间序列集合中使用时间戳字段。

Ruby

这个 opensearch-aws-sigv4 gem 提供访问权限 OpenSearch 无服务器,以及 OpenSearch 服务,开箱即用。它具有 opensearch-ruby 客户端的所有功能,因为它是这款 Gem 的依赖项。

在实例化 Sigv4 签名程序时,指定 aoss 为服务名称:

require 'opensearch-aws-sigv4' require 'aws-sigv4' signer = Aws::Sigv4::Signer.new(service: 'aoss', region: 'us-west-2', access_key_id: 'key_id', secret_access_key: 'secret') # create an opensearch client and use the request-signer client = OpenSearch::Aws::Sigv4Client.new( { host: 'https://your.amz-opensearch-serverless.endpoint', log: true }, signer) # create an index index = 'prime' client.indices.create(index: index) # insert data client.index(index: index, id: '1', body: { name: 'Amazon Echo', msrp: '5999', year: 2011 }) # query the index client.search(body: { query: { match: { name: 'Echo' } } }) # delete index entry client.delete(index: index, id: '1') # delete the index client.indices.delete(index: index)

与其他客户端签署 HTTP 请求

以下要求在以下情况下适用 签署请求 到 OpenSearch 使用其他客户端构建 HTTP 请求时的无服务器集合。

  • 必须将服务名称指定为 aoss。

  • 所有 Amazon 签名版本 4 请求都需要 x-amz-content-sha256 标头。它将提供请求负载的哈希。如果有请求负载,请将该值设置为其安全哈希算法(SHA)加密哈希(SHA256)。如果没有请求负载,请将该值设置为 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855,它是空字符串的哈希。

使用 cURL 创建索引

以下示例请求使用客户端 URL 请求库(cURL)将单个文档发送到集合中名为 movies-index 的索引:

curl -XPOST \ --user "$AWS_ACCESS_KEY_ID":"$AWS_SECRET_ACCESS_KEY" \ --aws-sigv4 "aws:amz:us-east-1:aoss" \ --header "x-amz-content-sha256: $REQUEST_PAYLOAD_SHA_HASH" \ --header "x-amz-security-token: $AWS_SESSION_TOKEN" \ "https://my-collection-endpoint.us-east-1.aoss.amazonaws.com/movies-index/_doc" \ -H "Content-Type: application/json" -d '{"title": "Shawshank Redemption"}'

使用 Postman 创建索引

下图演示了如何使用 Postman 将请求发送到集合。有关身份验证的说明,请参阅 使用进行身份验证 Amazon Postman 中的签名身份验证工作流程。

Postman 界面显示 POST 请求,其中 JSON 正文包含标题字段设置为 Shawshank Redemption。