본문 바로가기
Node.js

[Node.js] OpenSearch Node.js 클라이언트

by yonikim 2022. 12. 20.
728x90

 

AWS OpenSearch 의 경우 Node.js 에서 사용할 만한 라이브러리가 없어서 http 클라이언트를 이용하여 요청을 날렸었는데, 드디어 사용할 만한 라이브러리가 나왔다. 

 

$ npm install @opensearch-project/opensearch

 

 

AWS 에 API 요청을 보낼 땐 AWS 가 발신자를 식별할 수 있도록 서명해야 한다. 보안을 위해 대부분의 요청은 AWS 보안 자격 증명을 사용하여 서명되는데, 이를 위해 JavaScript 용 SDK 버전3의 credential-provider-node 모듈을 이용하여 자격 증명을 찾고, 그 후 API 요청에 서명해주기 위해 aws4 를 호출해줘야 한다.

 

따라서 아래 2개의 패키지도 다운로드 해준다.

$ npm install @aws-sdk/credential-provider-node
$ npm install aws4

 


 

▷ ./aws/opensearch.js 

const aws4 = require("aws4");
const { defaultProvider } = require("@aws-sdk/credential-provider-node");
const { Client, Connection } = require("@opensearch-project/opensearch");

const { REGION, OPENSEARCH_HOST } = process.env;
const host = `https://${OPENSEARCH_HOST}`;

const getClient = async () => {
  const credentials = await defaultProvider()();
  return new Client({
    ...createAwsConnector(credentials, REGION),
    node: host,
  });
};

const createAwsConnector = (credentials, region) => {
  class AmazonConnection extends Connection {
    buildRequestObject(params) {
      const request = super.buildRequestObject(params);
      request.service = "es";
      request.region = region;
      request.headers = request.headers || {};
      request.headers["host"] = request.hostname;

      return aws4.sign(request, credentials);
    }
  }
  return {
    Connection: AmazonConnection,
  };
};

 


 

인덱스를 생성하고 단일 문서 생성하는 코드만 샘플로 짜봤는데, Document 는 아래 깃헙을 참조하면 된다.

 

▷ handler.js

const { getClient } = require("./aws/opensearch")

const createIndex = async () => {
  try {
    // Initialize the client
    const client = await getClient();

    const indexName = "index-test";

    const response = await client.indices.create({
      index: indexName,
    });

    console.log(`Creating index: ${response.body}`);
    return response.body;
  } catch (err) {
    console.log(err);
    throw err;
  }
};

const putDocument = async () => {
  try {
    // Initialize the client
    const client = await getClient();

    const indexName = "index-test";

    const document = {
      title: "[Node.js] OpenSearch Node.js 클라이언트",
      writer: "yoni",
      createdDate: "2022-12-20",
    };

    const response = await client.index({
      index: indexName,
      body: document,
    });

    console.log(`Put document: ${response.body}`);
    return response.body;
  } catch (err) {
    console.log(err);
    throw err;
  }
};
728x90