Created
January 31, 2020 10:25
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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