From 42c21b6fbc82c8d4a4adbf55f00408c2adbe88f0 Mon Sep 17 00:00:00 2001 From: Steve Mao Date: Sat, 21 Apr 2018 14:47:59 +1000 Subject: [PATCH] replace invalid chars in index See https://github.com/elastic/elasticsearch/blob/608a61ab85e82f8f6e88002ba7d8458411e7da62/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java#L188-L202 --- lib/handler.js | 2 +- lib/utils.js | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/handler.js b/lib/handler.js index ec39c92..9159778 100644 --- a/lib/handler.js +++ b/lib/handler.js @@ -48,7 +48,7 @@ module.exports = function(options) { const actionDescriptionObj = { _index: options.index - || `${indexPrefix}${utils.assembleField(parsedRecord, options.indexField, separator)}`, + || `${indexPrefix}${utils.assembleField(parsedRecord, options.indexField, separator, true)}`, _type: options.type || utils.assembleField(parsedRecord, options.typeField, separator), _id: id diff --git a/lib/utils.js b/lib/utils.js index aeb83c8..eba229d 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -5,6 +5,13 @@ const joi = require('joi'); const errors = require('./errors'); +const replaceInvalidChars = (value) => + value + .replace(/[\\\/\*\?\"\<\>\| \,]/g, '-') + .replace(/#/g, '-') + .replace(/^[_\-+]/, '') + .toLowerCase() + module.exports = { validate(value, schema, options) { const validationResult = joi.validate( @@ -27,7 +34,7 @@ module.exports = { return validationResult.value; }, - getField(parsedRecord, path) { + getField(parsedRecord, path, isIndex) { const value = [parsedRecord.Keys, parsedRecord.NewImage, parsedRecord.OldImage] .reduce((acc, entry) => { return acc === undefined @@ -39,13 +46,17 @@ module.exports = { throw new errors.FieldNotFoundError(parsedRecord, path); } + if (isIndex) { + return replaceInvalidChars(value); + } + return value; }, - assembleField(parsedRecord, paths, separator) { + assembleField(parsedRecord, paths, separator, isIndex) { if (Array.isArray(paths)) { - return paths.map(path => this.getField(parsedRecord, path)).join(separator); + return paths.map(path => this.getField(parsedRecord, path, isIndex)).join(separator); } - return this.getField(parsedRecord, paths); + return this.getField(parsedRecord, paths, isIndex); } };