How to make calls to elasticsearch apis through NodeJS?

前端 未结 2 1733
Happy的楠姐
Happy的楠姐 2021-01-13 21:40

I have been tasked with making a POST api call to elastic search api,

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

2条回答
  •  天涯浪人
    2021-01-13 22:39

    The reason your seeing the error User: anonymous is not authorized to perform: es:ESHttpPost is because you're making requesting data without letting ElasticSearch know who you are - this is why it says 'Anonymous'.

    There are a couple ways of authentication, the easiest being using the elasticsearch library. With this library you'll give the library a set of credentials (access key, secret key) to the IAM role / user. It will use this to create signed requests. Signed requests will let AWS know who's actually making the request, so it won't be received as anonymous, but rather, yourself.

    Another way of getting this to work is to adjust your access policy to be IP-based:

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

    This particular policy will be wide open for anyone with the ip(range) that you provide here. It will spare you the hassle of having to go through signing your requests though.

    A library that helps setting up elasticsearch-js with AWS ES is this one

    A working example is the following:

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

提交回复
热议问题