重新索引编辑

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)