nodejs
nodejs
connect
import { Client, errors } from "@elastic/elasticsearch";
const client = new Client({
node: "http://example.com",
auth: {
username: "",
password: "",
},
// auth: {
// apiKey: ''
// }
});
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 });
});
create index
async createIndex(indexName: string) {
return this.client.indices.create({
index: indexName,
mappings: {},
settings: {}
});
};
Check Index Exists
async indexExists(indexName: string) {
return this.client.indices.exists({
index: indexName,
});
};
Add Settings
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',
},
}
});
};
add mappings
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' },
},
},
});
};
add document
// add single
async addDocument(indexName: string, payload: DataType) {
return this.client.index({
index: indexName,
type: '_doc',
id: payload.id,
body: payload
});
};
// add bulk
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
});
};
update document
async updateDocument(indexName: string, payload: DataType) {
return this.client.update({
index: indexName,
type: '_doc',
id: payload.id,
body: payload
});
};
delete document
async deleteDocument(indexName: string, id: string) {
return this.client.delete({
index: indexName,
id,
});
};
Page Source