Skip to content

Instantly share code, notes, and snippets.

@ppshein
Created January 31, 2020 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ppshein/65bc7ed5ef0e5b598dc2ac60a399b64c to your computer and use it in GitHub Desktop.
Save ppshein/65bc7ed5ef0e5b598dc2ac60a399b64c to your computer and use it in GitHub Desktop.
Check index whether exist or not then if not yet exist, create Index and Save document.
const elasticsearch = require('elasticsearch');
const esClient = new elasticsearch.Client({
host: process.env.ES_ENDPOINT,
apiVersion: "7.1",
});
exports.handler = async (event, context, callback) => {
const indexName = 'notifications';
const id = event.input.id;
const documents = event.input;
delete documents.id;
let checkIndex = await checkESIndices(indexName);
if (!checkIndex) {
return await createESIndex(indexName).then(async () => {
return await addESDocument(indexName, 'logs', id, documents);
});
} else {
return await addESDocument(indexName, 'logs', id, documents);
}
};
const checkESIndices = async (indexName) => {
return await esClient.indices.exists({ index: indexName });
};
const createESIndex = async (indexName) => {
return await esClient.indices.create({ index: indexName });
};
const addESDocument = async (indexName, indexType, id, indexDocuments) => {
return await esClient.index({
index: indexName,
type: indexType,
id: id,
body: indexDocuments
}).then(() => {
const response = {
statusCode: 200,
body: {
title: indexDocuments.title,
username: indexDocuments.username
}
};
console.log(JSON.stringify(response));
return response;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment