UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Elasticsearch】Reindexのscriptで文字列の加工

Elasticsearchで以下のようなフィールドがある

id: 00000001:ja

この値をコロン「:」でスプリットした時の最後の要素は言語コードjaは日本語)を示しているのだが、これを変更してマレーシ語を意味する以下のようなデータをつくりたい

id: 00000001:ms

案としては元々のindexをReindexする際にidを変更することにした

これができるかを調査した結果、ESのディスカッションがあった

discuss.elastic.co

みようみ真似でやるとこんな感じ

{
  "source": {
    "index": "my-ja-index",
  },
  "dest": {
    "index": "my-ms-index"
  },
  "script": {
    "lang": "painless",
    "source": """
      def split_path = ctx._source.id.splitOnToken(':');
      int i = 0;
      String parent_folder = '';
      for (item in split_path) {
        i = i + 1;
        if (i != split_path.length) {
          parent_folder += item + ':'
        }
      }
      ctx._id = parent_folder + 'ms';
      ctx._source.id= parent_folder + 'ms';
    """
  }
}

painlessという独自の記法なので、もう少しきれいにかけるかどうかはわからないが、やりたいことはこれでできた