3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【elasticsearch】【python】bulk APIで使うjsonをcsvから動的に生成する

Last updated at Posted at 2019-04-04

##環境
elasticsearch6.6.0
python3.5.1

##今回やりたいこと

今回やりたいことは、bulkAPIで使うjsonファイルの生成をpythonでやる。
※bulkAPIとは、elasticsearchへのたくさんのデータ登録をjsonを使ってコマンド一つでやってしまうものである。

以下のようなcsvを、、、

name.csv
三木夏海,
川原香菜,
大宮梨子,
・・・
・・・
・・・

以下のように整形する。

sample_bulk.json
{"index" : {}}
{"name":"三木夏海"}
{"index" : {}}
{"name":"川原香菜"}
{"index" : {}}
{"name":"大宮梨子"}
・・・
・・・
・・・

indexの名前やtype名はcurlコマンド内に記述する。
idを指定して振りたい場合は、pythonプログラム内に一工夫が必要。

##準備

  • elasticsearchのsettingとmappingを登録。フィールドはnameのみ。
  • サンプルデータを用意

以下のサイトから名前のサンプルデータをcsvで取得した。
https://hogehoge.tk/personal/generator/

##pythonファイル
作成したコードは以下のようになった。

bulk.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pandas as pd
import json

def func():
    # csvから名前をdataframe型で取得。ヘッダーがない場合は、dropメソッドは使わなくて良い。
	name = pd.read_csv("name.csv", header=None).drop(0, axis=0)[0].values.tolist()

    # dict型でnameを定義
	data = {'name' : name}
    # データフレームに変換
	df = pd.DataFrame(data)

    # JSON形式の文字列(str型)に変換。
    # 引数force_ascii=FalseとするとUnicodeエスケープされない。
    # 引数orient='records'で、引数lines=Trueとすると{name:名前}ごとに改行された文字列になる。
	df_str = df.to_json(force_ascii=False, orient='records', lines=True)

    # リスト型に変換
	df_list = df_str.split('\n')

    # 一行毎に、{"index" : {}}を追加
	even_list = ['{"index" : {}}\n' + df_list[i] for i in range(len(df_list))]
	if even_list[-1] == '{"index" : {}}':
        # 最後の行には{"index" : {}}を追加しない
	    even_list.pop(-1)
	else:
        # 最後は改行で終わらせる
	    even_list.append("\n")

    # 文字列に変換
	mojiretsu = '\n'.join(even_list)

    # jsonファイルとして出力
	with open("sample_bulk.json", mode='w') as f:
	    f.write(mojiretsu)

# 関数実行
func()

ターミナルで実行したらsample_bulk.jsonが生成される。

##データインサート
sample_bulk.jsonが出来上がったら、データを登録してみる。
以下のようにcurlコマンドを実行。indexやtypeはここで指定する。

curl -H "Content-Type: application/json" -X POST http://localhost:9200/index名/type名/_bulk?pretty --data-binary @sample_bulk.json

以下でデータを確認


curl -H "Content-Type: application/json" -XGET 'localhost:9200/index名/type名/_search?pretty'

##参考
pandas.DataFrameをJSON文字列・ファイルに変換・保存(to_json)

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?