弹性搜索和nodejs连接

Elastic search and nodejs connection

我正在尝试使用 rest api 创建一个 node.js 应用程序来查询弹性搜索应用云上的数据。我遵循了弹性搜索连接的代码

var elasticsearch = require('elasticsearch');

var client = new elasticsearch.Client({
    host:'localhost:9200'
});

以上连接正确连接,如果我添加任何数据,它也会被添加。但我希望数据不被添加到本地主机。我希望我的实际集群拥有数据。 我试过下面的代码

var elasticsearch = require('elasticsearch');

var client = new elasticsearch.Client({
    cloud: {
        id: 'cloud_id',
    },
    auth: {
        username: "username",
        password: "pass",
    },
});

//data I am trying to add

let data = {
    "id": "park_somethign",
    "title": "Something",
    "description": "Split into the separate Rincon Mountain and Tucson Mountain districts, this park is evidence that the dry Sonoran Desert is still home to a great variety of life spanning six biotic communities. Beyond the namesake giant saguaro cacti, there are barrel cacti, chollas, and prickly pears, as well as lesser long-nosed bats, spotted owls, and javelinas.",
    "nps_link": "https://www.nps.gov/sagu/index.htm",
    "states": [
        "Arizona"
    ],
    "visitors": 838456,
    "world_heritage_site": false,
    "location": "32.20,-109.5",
    "acres": 9215.72,
    "square_km": 2271.2,
    "date_established": "1997-10-14T05:00:00Z"
}

//this is what I am trying to do
 client.index({
        index: 'engines',
        body: data
    }).then(resp => {
        return res.status(200).json({
            message: "Added Data"
        })
    }).catch(e => {
        console.log(e)
        return res.status(500).json({
            message: "Error",
            e
        })
    })

以上代码仍然没有添加数据或从我的云集群中检索数据... 在互联网上的每个地方我都只找到本地主机的例子。请谁能告诉我如何将 nodejs 直接连接到弹性搜索云集群?

确保使用 Elastic Cloud 提供的 Cloud ID UI:

然后使用您在创建部署时创建的凭据。或者,您也可以创建 API 密钥来进行身份验证:

const { Client } = require('@elastic/elasticsearch')

const client = new Client({
  cloud: {
    id: 'name:bG9jYWxob3N0JGFiY2QkZWZnaA==',
  },
  auth: {
    apiKey: {
      id: 'foo',
      api_key: 'bar'
    }
  }
})

这里有更多信息:https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/client-connecting.html

我有同样的问题。因此,连接到企业搜索的主机 url 即可。像这样


var client = new elasticsearch.Client({
// do not forget to add the username and password in the url
  host:"https://<username>:<password>[complete_host_url]" 
}); 

如果这不起作用,请尝试 node:"https://<username>:<password>@<ip1><port>"

您还可以通过提供 urls 作为主机 urls 的数组来一次连接到多个主机。

Refer This