Aws

Node.js | A function to interact with AWS OpenSearch Serverless

Hello to my dear friends.

Welcome to this wonderful day and I hope you are all enjoying your programming days.

Today I have a function that can help you to connect to AWS OpenSearch Serverless , execute a query and fetch the results.

first we need a node package to be installed.

npm install @opensearch-project/opensearch

The function (i stored it in file names “getOpenSearchResponse.js”)


const { defaultProvider } = require('@aws-sdk/credential-provider-node')
const { Client } = require('@opensearch-project/opensearch')
const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws')

module.exports = {
getResponse: (host_url, body, index) => {
return new Promise((resolve, reject) => {
var region = "us-east-1";
var domain = host_url;
try {
const searchQuery = {
index: index,
body: body,
};

const client = new Client({
...AwsSigv4Signer({
region: region,
service: 'aoss',
getCredentials: async () => {
const credentialsProvider = defaultProvider()
const credentials = await credentialsProvider()
console.log(credentials)
return credentials;
}
}),
node: domain, // serverless collection endpoint
})

client.search(searchQuery).then((response) => {
console.log('got result from Open search')
resolve(response.body)
}).catch((err) => {
var err1 = {
status: 500,
message: 'error occurred while fetching data from open search',
actualMessage: err
}
reject(err1)
});
} catch (err) {
var err1 = {
status: 500,
message: 'error occurred while initializing the client',
actualMessage: err
}
reject(err1)
}
})
}
}

Usage



const { getResponse } = require('./getOpenSearchResponse')

module.exports = async function () {
return new Promise(async (resolve, reject) => {
console.log('========== [Enter Service get aoss data] ==========')
try {
var aoss_url = "https://xxxxxxx.us-east-1.aoss.amazonaws.com"
var aoss_query = {
query: {
size: 10,
},
}
var aoss_index = "access"
var ret = await getResponse(aoss_url, aoss_query, aoss_index)
return resolve(ret)
} catch (err) {
return reject(err)
}
})
}

Note: this is just a snippet from my code. you will have arrange and place it accordingly to get it working.

Happy Programing 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *