代码之家  ›  专栏  ›  技术社区  ›  thedreamsaver

如何通过nodejs调用elasticsearch api?

  •  3
  • thedreamsaver  · 技术社区  · 6 年前

    我的任务是为弹性搜索API做一个API后调用。

    https://search-test-search-fqa4l6ubylznt7is4d5yxlmbxy.us-west-2.es.amazonaws.com/klove-ddb/recipe/_search

    我以前没有做过AWS服务API调用的经验。

    所以,我试过了-

    axios.post('https://search-test-search-fqa4l6ubylznt7is4d5yxlmbxy.us-west-2.es.amazonaws.com/klove-ddb/recipe/_search')
                .then(res => res.data)
                .then(res => console.log(res));
    

    但是我收到了{“消息”:“user:anonymous未被授权执行:es:eshttpost”}

    我还签出了一些iam角色,并在我的配置文件中添加了一个完整的访问策略。

    但我还是不能解决任何问题。

    请帮帮我。

    1 回复  |  直到 6 年前
        1
  •  4
  •   trojanh Tom Nijs    5 年前

    你看到错误的原因 User: anonymous is not authorized to perform: es:ESHttpPost 这是因为你在不让弹性搜索知道你是谁的情况下做出请求数据——这就是为什么它说“匿名”的原因。

    有两种身份验证方法,最简单的是使用 elasticsearch library . 使用此库,您将为该库提供一组凭据(访问密钥、密钥)给iam角色/用户。它将使用此来创建已签名的请求。签名的请求将让AWS知道谁在实际请求,所以它不会被匿名地接收,而是你自己。

    另一种方法是将访问策略调整为基于IP:

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "AWS": "*"
                },
                "Action": "es:*",
                "Condition": {
                    "IpAddress": {
                        "aws:SourceIp": [
                            "AAA.BBB.CCC.DDD"
                        ]
                    }
                },
                "Resource": "YOUR_ELASTICSEARCH_CLUSTER_ARN"
            }
        ]
    }
    

    这个特殊的政策将广泛适用于这里提供的IP(范围)。不过,这会让你免去签署请求的麻烦。

    帮助建立 elasticsearch-js 与AWS ES一起 this one

    一个工作示例如下:

    const AWS = require('aws-sdk')
    const elasticsearch = require('elasticsearch')
    const awsHttpClient = require('http-aws-es')
    
    let client = elasticsearch.Client({
        host: '<YOUR_ES_CLUSTER_ID>.<YOUR_ES_REGION>.es.amazonaws.com',
        connectionClass: awsHttpClient,
        amazonES: {
            region: '<YOUR_ES_REGION>',
            credentials: new AWS.Credentials('<YOUR_ACCESS_KEY>', '<YOUR_SECRET_KEY>')
        }
    });
    
    client.search({
        index: 'twitter',
        type: 'tweets',
        body: {
            query: {
                match: {
                    body: 'elasticsearch'
                }
            }
        }
    })
    .then(res => console.log(res));