Elasticsearch の CRUD (Node.js)

```json:package.json
{
  "type": "module"
}
```

## Create ##

```js:elastic_create.js
#! /usr/bin/node
// ---------------------------------------------------------------
//	elastic_create.js
//
//						Mar/23/2022
//
// ---------------------------------------------------------------
'use strict'

import * as http from "http"
// ---------------------------------------------------------------
function dict_append_proc (dict_aa,id_in,name_in,population_in,date_mod_in)
{
	var unit_aa = {}
	unit_aa['name'] = name_in
	unit_aa['population'] = population_in
	unit_aa['date_mod'] = date_mod_in

	dict_aa[id_in] = unit_aa

	return  dict_aa
}

// ---------------------------------------------------------------
function data_prepare_proc ()
{
	var dict_aa = new Object ()

	dict_aa = dict_append_proc (dict_aa,'t0921','宇都宮',63729,'1950-3-21')
	dict_aa = dict_append_proc (dict_aa,'t0922','小山',29157,'1950-9-15')
	dict_aa = dict_append_proc (dict_aa,'t0923','佐野',64781,'1950-11-7')
	dict_aa = dict_append_proc (dict_aa,'t0924','足利',38124,'1950-6-22')
	dict_aa = dict_append_proc (dict_aa,'t0925','日光',49675,'1950-8-28')
	dict_aa = dict_append_proc (dict_aa,'t0926','下野',65813,'1950-9-12')
	dict_aa = dict_append_proc (dict_aa,'t0927','さくら',37251,'1950-3-21')
	dict_aa = dict_append_proc (dict_aa,'t0928','矢板',52416,'1950-7-26')
	dict_aa = dict_append_proc (dict_aa,'t0929','真岡',26857,'1950-10-2')
	dict_aa = dict_append_proc (dict_aa,'t0930','栃木',48923,'1950-12-20')
	dict_aa = dict_append_proc (dict_aa,'t0931','大田原',75284,'1950-2-7')
	dict_aa = dict_append_proc (dict_aa,'t0932','鹿沼',96351,'1950-5-17')
	dict_aa = dict_append_proc (dict_aa,'t0933','那須塩原',82937,'1950-6-19')
	dict_aa = dict_append_proc (dict_aa,'t0934','那須烏山',73152,'1950-8-24')

	return  dict_aa
}

// ---------------------------------------------------------------
console.error ("*** 開始 ***")

const dict_aa = data_prepare_proc ()

const url_base = "http://localhost:9200/cities/tochigi"

for (var key in dict_aa)
	{
	const unit_aa = dict_aa[key]

	const data = JSON.stringify(unit_aa)
	const options = {
		method: "PUT",
		headers: {
			"Content-Type": "application/json",
			'Content-Length': Buffer.byteLength(data)
			}
		}

	const url = url_base + "/" + key

	const request = http.request(url, options, response => {
		console.log(`statusCode: ${response.statusCode}`)
		})

	request.write(data)
	request.end()
	}

console.error ("*** 終了 ***")

// ---------------------------------------------------------------
```

## Read ##

```js:elastic_read.js
#! /usr/bin/node
// ---------------------------------------------------------------
//	elastic_read.js
//
//						Mar/23/2022
//
// ---------------------------------------------------------------
'use strict'

import * as http from "http"

// ---------------------------------------------------------------
function sort_key_proc (dict_aa)
{
	var array = new Array()

	for(var it in dict_aa)
		{
		array.push({'key':String (it), 'value':dict_aa[it]})
		}

	array.sort (compare_by_key_proc)

	return array
}

// ---------------------------------------------------------------
function compare_by_key_proc (left,right)
{
	var aa = left.key
	var bb = right.key

	var rvalue = 0

	if (aa < bb)
		{
		rvalue = -1
		}
	else if (aa > bb)
		{
		rvalue = 1
		}

	return  rvalue
}
// ---------------------------------------------------------------
function dict_display_proc (dict_aa)
{
	const array_aa = sort_key_proc (dict_aa)

	array_aa.forEach (function(unit_aa,index)
		{
		const key = unit_aa.key
		const value = unit_aa.value

		var out_str = key + "\t"
		out_str += value["name"] + "\t"
		out_str += value["population"] + "\t"
		out_str += value["date_mod"]
		console.log (out_str)
		})  
}

// ---------------------------------------------------------------
console.error ("*** 開始 ***")

const url = "http://localhost:9200/cities/tochigi/_search?q=*&size=100"

const options = {
	method: 'GET'
}

const req = http.request(url,options, res => {
	console.log(`statusCode: ${res.statusCode}`)

	res.on('data', dd => {
//	process.stdout.write(dd)
	const data_aa = JSON.parse (dd)
	const llx = data_aa['hits']['hits'].length
//	console.error ("llx = " + llx)

	var dict_aa = {}
	for (var it =0; it< llx; it+=1)
		{
		const key = data_aa['hits']['hits'][it]['_id']
		const value = data_aa['hits']['hits'][it]['_source']
		dict_aa[key] = value
		}

	dict_display_proc(dict_aa)
	console.error ("*** 終了 ***")
	})
})

req.on('error', error => {
	console.error(error)
})

req.end()

// ---------------------------------------------------------------
```

## Update ##

```js:elastic_update.js
#! /usr/bin/node
// ---------------------------------------------------------------
//	elastic_update.js
//
//					Mar/23/2022
//
// ---------------------------------------------------------------
'use strict'

import * as http from "http"
// ---------------------------------------------------------------
function get_current_date_proc ()
{
	const today = new Date ()
	var ddx = (today.getFullYear ()) + "-" + (today.getMonth () +1)
	ddx += "-" + today.getDate ()

	return ddx
}

// ---------------------------------------------------------------
console.error ("*** 開始 ***")
const key_in=process.argv[2]
const population_in=process.argv[3]

console.log (key_in + "\t" + population_in)

const str_date_mod = get_current_date_proc ()

const data_in = {"script" : {
	"source": "ctx._source.population = params.population; ctx._source.date_mod = params.date_mod",
		"lang": "painless",
		"params" : {
			"population" : population_in,
			"date_mod" : str_date_mod
			}
		}
	}


	const data = JSON.stringify(data_in)

	const options = {
		method: "POST",
		headers: {
			"Content-Type": "application/json",
			'Content-Length': Buffer.byteLength(data)
			}
		}

const url = "http://localhost:9200/cities/tochigi/" + key_in + "/_update"

	const request = http.request(url, options, response => {
		console.log(`statusCode: ${response.statusCode}`)
		})

	request.write(data)
	request.end()

	console.error ("*** 終了 ***")

// ---------------------------------------------------------------
```

実行スクリプト

```bash
./elastic_update.js t0926 1894700
```

## Delete ##

```js:elastic_delete.js
#! /usr/bin/node
// ---------------------------------------------------------------
//	elastic_delete.js
//
//					Mar/23/2022
//
// ---------------------------------------------------------------
'use strict'

import * as http from "http"
// ---------------------------------------------------------------
console.error ("*** 開始 ***")
const key_in=process.argv[2]

console.log (key_in)

const url = "http://localhost:9200/cities/tochigi/" + key_in

const options = {
	method: "DELETE"
	}

const request = http.request(url, options, response => {
		console.log(`statusCode: ${response.statusCode}`)
		})

request.end()
console.error ("*** 終了 ***")

// ---------------------------------------------------------------
```

実行スクリプト

```bash
./elastic_delete.js t0922
```