重新索引

编辑

reindex API 从源索引中提取文档源,并将文档索引到目标索引。您可以将所有文档复制到目标索引,重新索引文档的子集,或在重新索引之前更新源。

在以下示例中,我们有一个包含不同角色各种引语的 game-of-thrones 索引,我们想要创建一个仅用于史塔克家族的新索引,并从文档源中移除 house 字段。

'use strict'

const { Client } = require('@elastic/elasticsearch')
const client = new Client({
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' }
})

async function run () {
  await client.index({
    index: 'game-of-thrones',
    document: {
      character: 'Ned Stark',
      quote: 'Winter is coming.',
      house: 'stark'
    }
  })

  await client.index({
    index: 'game-of-thrones',
    document: {
      character: 'Arya Stark',
      quote: 'A girl is Arya Stark of Winterfell. And I\'m going home.',
      house: 'stark'
    }
  })

  await client.index({
    index: 'game-of-thrones',
    refresh: true,
    document: {
      character: 'Tyrion Lannister',
      quote: 'A Lannister always pays his debts.',
      house: 'lannister'
    }
  })

  await client.reindex({
    wait_for_completion: true,
    refresh: true,
    source: {
      index: 'game-of-thrones',
      query: {
        match: { house: 'stark' }
      }
    },
    dest: {
      index: 'stark-index'
     },
    script: {
      lang: 'painless',
      source: 'ctx._source.remove("house")'
    }
  })

  const result = await client.search({
    index: 'stark-index',
    query: { match_all: {} }
  })

  console.log(result.hits.hits)
}

run().catch(console.log)