Elastic Search NodeJs 클라이언트 시작하기
ES: 탄력적 검색
전제 조건
탄력적 검색이란 무엇입니까? Elastic Search는 어떻게 작동합니까? Elastic Search에서 매핑 및 설정으로 새 색인을 만드시겠습니까?Elastic Search에 대한 이전 기사에서 Elastic Search의 기본 사항, 작동 방식 및 새 인덱스를 생성하는 방법에 대해 배웠습니다. 이 기사에서는 Elastic Search NodeJS 클라이언트로 계속 작업하고 새 문서를 인덱싱하는 방법, 기존 인덱싱된 문서를 업데이트하고 인덱싱된 문서를 삭제하는 방법을 살펴봅니다. 이러한 기능을 이해하면 Elastic Search를 보다 효과적으로 사용하여 프로젝트의 데이터를 관리하고 업데이트할 수 있습니다. 시작하여 이러한 기능이 실제로 어떻게 작동하는지 살펴보겠습니다.
아래 예제는 모두 ES Node 클라이언트 를 기반으로 합니다.
설치
nodejs 애플리케이션에서 npm Elastic Search 패키지를 사용할 수 있습니다.
npm install @elastic/elasticsearch
ES 클러스터는 보안이 명시적으로 비활성화 되도록 구성되어 있으므로 HTTP를 통해 연결할 수 있습니다.
import { Client, errors } from '@elastic/elasticsearch';
const client = new Client({
node: 'http://example.com'
});
다른 모든 ES 관련 참조 자료는 여기에서 얻을 수 있습니다 .
핑
ES 클라이언트가 정의된 http 클러스터와 연결되어 있는지 확인하려면 ping 작업을 수행하십시오.
client
.ping({
// ping usually has a 3000ms timeout
requestTimeout: 1000,
})
.then(() => {
this.logger.info('Elasticsearch connected');
})
.catch((err: errors.ConnectionError) => {
this.logger.error('Elasticsearch unavailable', { error: err });
});
async createIndex(indexName: string) {
return this.client.indices.create({
index: indexName,
mappings: {},
settings: {}
});
};
인덱스가 존재하는지 확인하십시오.
async indexExists(indexName: string) {
return this.client.indices.exists({
index: indexName,
});
};
색인에 문서를 추가하기 전에 색인 설정을 업데이트하고 검색 기능에 따라 필요한 분석기를 추가하는 것이 좋습니다. 다음은 인덱스 설정의 예입니다.
async indexSetting(indexName: string) {
return this.client.indices.putSettings({
index: indexName,
body: {
settings: {
max_ngram_diff: 19,
analysis: {
filter: {
autocomplete_filter: {
type: 'ngram',
min_gram: '1',
max_gram: '20',
},
},
analyzer: {
autocomplete: {
filter: ['lowercase', 'autocomplete_filter'],
type: 'custom',
tokenizer: 'standard',
},
},
},
number_of_replicas: '1',
},
}
});
};
매핑 추가
색인에 문서를 추가하기 전에 색인 설정을 업데이트한 다음 색인 매핑을 업데이트하고 분석기 속성을 필드에 할당하는 것이 좋습니다. 다음은 인덱스 매핑의 예입니다.
설정을 업데이트하면서 autocomplete매핑에서 검색 속성으로 정의할 수 있는 분석기를 추가했습니다. 인덱스 매핑은 인덱스마다 다를 수 있습니다.
const searchProperty = {
type: 'text',
analyzer: 'autocomplete',
search_analyzer: 'standard',
};
async indexMapping(indexName: string) {
return this.client.indices.putMapping({
index: indexName,
body: {
properties: {
id: { type: 'keyword' },
createdAt: { type: 'date' },
updatedAt: { type: 'date' },
caseCode: searchProperty,
policyNo: searchProperty,
claimRegNo: searchProperty,
vehicleRegNo: searchProperty,
vehicleChassisNo: searchProperty,
claimStatus: { type: 'keyword' },
lossType: { type: 'keyword' },
vehicleType: { type: 'keyword' },
zone: { type: 'keyword' },
insurer: { type: 'keyword' },
caseStatus: { type: 'keyword' },
business: { type: 'keyword' },
},
},
});
};
문서 추가
색인에 문서를 추가하는 방법에는 여러 가지가 있습니다.
단일 문서
async addDocument(indexName: string, payload: DataType) {
return this.client.index({
index: indexName,
type: '_doc',
id: payload.id,
body: payload
});
};
async addBulkDocuments(indexName: data = []) {
const payload = data.map((item) => {
return [
{
index: {
_index: indexName,
_type: '_doc',
_id: item.id,
},
},
item,
]
})
return this.client.bulk({
refresh: true,
body: payload
});
};
async updateDocument(indexName: string, payload: DataType) {
return this.client.update({
index: indexName,
type: '_doc',
id: payload.id,
body: payload
});
};
단일 문서 업데이트: 스크립트 또는 부분 문서로 문서를 업데이트합니다.
client.update(...)
client.updateByQuery(...)
단일 문서 삭제
async deleteDocument(indexName: string, id: string) {
return this.client.delete({
index: indexName,
id,
});
};
단일 문서 삭제: 스크립트 또는 부분 문서로 문서를 업데이트합니다.
client.delete(...)
client.deleteByQuery(...)
Elasticsearch JavaScript 클라이언트 [8.5] | 탄력있는
API 참조 | Elasticsearch JavaScript 클라이언트 [8.5] | 탄력있는
예 | Elasticsearch JavaScript 클라이언트 [8.5] | 탄력있는
사용자 지정 분석기 만들기 | Elasticsearch 가이드[8.5] | 탄력있는
내장 분석기 참조 | Elasticsearch 가이드[8.5] | 탄력있는
필드 데이터 유형 | Elasticsearch 가이드[8.5] | 탄력있는
Elastic Search와 이를 사용하여 다양한 애플리케이션에서 검색 및 분석을 최적화하는 방법에 대해 즐겁게 읽으셨기를 바랍니다. 이 기사가 도움이 되었거나 추가 질문이 있는 경우 주저하지 말고 의견을 통해 저에게 연락하십시오.
최신 기술 동향에 대한 더 많은 업데이트와 통찰력을 얻으려면 Twitter 또는 LinkedIn 에서 저를 팔로우하십시오 . 읽어주셔서 감사합니다. 소셜 미디어에서 여러분과 소통하기를 기대합니다.
트위터 :https://twitter.com/geekfarmer_
링크드 인 :https://www.linkedin.com/in/geekfarmer

![연결된 목록이란 무엇입니까? [1 부]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































