Search code examples
javascriptnode.jselasticsearchelasticsearch-5elasticsearch-6

Add copy to to eslaticsearch on index template


I use elasticsearch 6.2, and I want to optimize the elasticsearch search functionality to copy all field value to one value and generate than searching by query string on one field instead of multiple field. How to do that? How to copy all fields, now matter which to one filed.

initialize index template

export const init = async types => {
    try {
        let client = createClient()

        const templateSettings = {
            index_patterns : ['*'],
            settings: indexTemplateSettings,
            mappings : types.reduce((p, type) => ({
                ...p,
                [type] : {
                    numeric_detection: true,
                    _source : {enabled : true},
                    'properties': {
                        'searchIndex': {
                            'type': 'text',
                        },
                        '*': {
                            'type': 'text',
                            'copy_to': 'searchIndex',
                        },
                    },
                },
            }), {}),
        }

        await client.indices.putTemplate({
            name: 'default',
            body: templateSettings,
        },(error, response) => {
            logger.silly('Pushing of index template completed', response)
        })
    } catch (e) {
        logger.error(e)
    }
}

put index

export const push = (message, type) => new Promise(async resolve => {
    try {
        let client = createClient()
        let indexCreationTime = new Date('2016-02-08').toISOString().substring(0, 10)

        // '2016-02-08'
        console.log(message, 'message')
        console.log(type, 'type')

        await client.index({
            index: type.toLowerCase(),
            type,
            body: {
                ...message,
                _timestampIndex: indexCreationTime,
            },
        },
        (error, response) => {
            logger.silly('Pushing of data completed', response)

            resolve(response)
        })

    } catch (e) {
        logger.error(e)
    }
})

Solution

  • The best way is to create an index template which leverages a dynamic template that will catch all fields and add the copy_to parameter to their definition.

    PUT _template/my-template
    {
      "index_patterns": ["*"],
      "settings": {},
      "mappings": {
        "_doc": {
          "dynamic_templates": [
            {
              "all": {
                "match": "*",
                "mapping": {
                  "type": "text",
                  "copy_to": "searchIndex"
                }
              }
            }
          ],
          "properties": {
            "searchIndex": {
              "type": "text"
            }
          }
        }
      }
    }