将副本添加到索引模板上的 eslaticsearch

Add copy to to eslaticsearch on index template

我使用 elasticsearch 6.2,我想优化 elasticsearch 搜索功能,将所有字段值复制到一个值,然后生成一个字段而不是多个字段上的查询字符串搜索。怎么做?如何复制所有字段,现在不管是哪个字段。

初始化索引模板

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)
    }
}

放索引

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)
    }
})

最好的方法是创建一个索引模板,利用 dynamic template 捕获所有字段并将 copy_to 参数添加到它们的定义中。

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