Node.js

[NodeJS] node로 elasticsearch 검색하기

SongMinu 2021. 2. 27. 14:33
728x90

먼저 elasticsearch 패키지가 없다면 설치

npm install elasticsearch

 

소스

const elasticsearch = require("elasticsearch");
const client = new elasticsearch.Client({
  hosts: ["http://localhost:9200"]
  //프로토콜이 https이고 elasticsearch에 id, password가 있다면
  //hosts: ["https://es_id:es_pass@localhost:9200"]
});

async function test() {
  try {
    const rs =  await client.search({
      index: 'user_data',
      body: {
        "query": {
          "bool": {
            "must": [
              {
                "term": {
                  "user_name": "민우"
                }
              }
            ]
          }
        }
      }
    });
    console.log(rs);
  } catch (err) {
    console.error(err);
  }
}
test();

위 소스는 가장 기본적인 걸로 예시

body 부분에다가 검색하고자 하는 쿼리를 작성해주면 된다.

위 파일의 결과

사용 용도에 맞게끔 만들어서 처리 로직을 해주면 되고,

client.search 외에도 update, bulk, count, bulk 등 제공해주는 기능이 생각보다 많기 때문에 어지간한 기능은 만들 수 있다.

데이터 수정, 인덱스 생성, 검색, 필드 추가, 리인덱스 등을 할 수 있다.

 

만들어봤던 몇 가지로 예를 들어보면

API 방식으로 요청이 들어오면 특정 데이터들을 찾아서 결과를 반환한다거나, 데이터 수정,

bulk 형식의 데이터가 들어 있는 파일을 읽어서 bulk 처리, 인덱스 필드 수정, 쿼리로 뽑은 데이터 파일로 생성 등이 있었다.

 

사용할 예정이고 좀더 많은 정보를 알고 싶다면

www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html

 

API Reference | Elasticsearch Node.js client [7.x] | Elastic

This document contains the entire list of the Elasticsearch API supported by the client, both OSS and commercial. The client is entirely licensed under Apache 2.0. Elasticsearch exposes an HTTP layer to communicate with, and the client is a library that wi

www.elastic.co

여기를 한번 보는것을 추천

 

 

 

반응형