首页 > 解决方案 > 签署对 Amazon Elasticsearch Service 的 GET HTTP 请求

问题描述

我需要使用 lambda 函数调用“向 Amazon Elasticsearch Service 签署 GET HTTP 请求”。

我已经尝试过http包,它在http请求中工作正常

http.get(`http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com/${event['index']}/doc/_search/?q=${event['keyParam']}`, 
  function(res) { 
    var body = '';
        res.on('data', function(d) {
            body += d;
        });

        res.on('end', function() {
            context.succeed(JSON.parse(body.replace(/\n|\r/g, ""))); //Remove and newline/linebreak chars
        });
  }).on('error', function(e) {
    console.log("Error: " + e.message);
    context.done(null, 'FAILURE');
  });
var AWS = require('aws-sdk');

exports.handler = function(event, context) {
  var region = 'xx-xxxx-x';
  var domain = 'http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com';
  var index = event['index'];
  var type = `_doc/_search`;

  var endpoint = new AWS.Endpoint(domain);
  var request = new AWS.HttpRequest(endpoint, region);
  request.method = 'GET';
  request.path += index + '/' + type+'?q=_doc_key_here:_doc_key_value';
  request.headers['host'] = domain;
  > e.g. URL genrate like: http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com/node-test/doc/_search/?q=user_name:johndoe

  var credentials = new AWS.EnvironmentCredentials('AWS');
  var signer = new AWS.Signers.V4(request, 'es');
  signer.addAuthorization(credentials, new Date());

  var client = new AWS.HttpClient();
  client.handleRequest(request, null, function(response) {
    console.log("response: ",response.statusCode);
    var responseBody = '';
    response.on('data', function (chunk) {
      responseBody += chunk;
    });
    response.on('end', function (chunk) {
      console.log('Response body: ' + responseBody);
      context.succeed(responseBody)
    });
  }, function(error) {
    console.log('Error: ' + error);
    context.done(error);
  });
}

当我尝试使用上述函数调用“Signing GET HTTP Requests”时,它向我抛出了以下错误:

响应:400 错误请求

标签: amazon-web-serviceselasticsearchaws-lambdaaws-sdk-nodejsaws-elasticsearch

解决方案


这里只缺少一件事,我encodeURI()请求中添加了它对我来说很好用

var index = event['index'];
var type = `_doc/_search?q=_doc_key_here:_doc_key_value`;
request.method = 'GET';
request.path += index + '/' + encodeURI(type);

我希望它会帮助其他人

谢谢


推荐阅读