LoginSignup
32
23

More than 5 years have passed since last update.

よく使うElasticSearchのクエリ(インデックス操作)

Last updated at Posted at 2017-10-28

ElasticSearchは、マニュアル(英語)がしっかりしてるので、そっちを参考にしてください。
マニュアル(本家):https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html

とりあえず、理解しやすく、MySQLのSQL文と比較しながら、まとめます。

環境

  • CentOS 7.1
  • ElasticSearch 5.6.2
    ※ElasticSearch 6.xでは、curlに「 -H 'Content-Type: application/json'」を付ける必要があります。

目次

インデックス(マッピング)操作

■ インデックス作成

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
※ただ、わざわざ、インデックスを作らなくても、データを登録すると勝手に作られる。

elasticsearch
curl -XPUT http://localhost:9200/hoge_index?pretty
MySQL
CREATE DATABASE hoge_index

■ インデックス作成&マッピングの定義

hoge_mapping.json
{
    "mappings" : {
        "hoge_type" : {
            "properties" : {
                "id" : { "type" : "long", "store" : "yes" },
                "hoge_field_1" : { "type" : "string", "store" : "yes", "index" : "analyzed" },
                "hoge_field_2" : { "type" : "string", "store" : "yes", "index" : "analyzed" },
                "hoge_field_3" : { "type" : "string", "store" : "yes", "index" : "analyzed" }
            }
        }
    }
}
elasticsearch
curl -XPUT 'http://localhost:9200/hoge_index?pretty' -d @hoge_mapping.json

■ インデックスの削除

elasticsearch
curl -XDELETE http://localhost:9200/hoge_index?pretty
MySQL
DROP DATABASE hoge_index

■ 全インデックスの削除

elasticsearch
curl -XDELETE http://localhost:9200/*?pretty

■ インデックスの一覧

elasticsearch
curl -XGET http://localhost:9200/_aliases?pretty
MySQL
SHOW TABLES

■ インデックスの存在チェック

elasticsearch
curl -IHEAD 'http://localhost:9200/hoge_index'
bashでチェックする方法
ret=`curl -s -IHEAD 'http://localhost:9200/hoge_index'`
if [ "`echo $ret | grep '200 OK'`" ]; then
  echo "200 OK"
fi

■ エイリアス

・エイリアスの追加

elasticsearch
curl -XPOST 'http://localhost:9200/_aliases?pretty' -d '{
  "actions" : [
    { "add" : { "index" : "hoge_index", "alias" : "hoge" } }
  ]
}'

・エイリアスの削除

elasticsearch
curl -XPOST 'http://localhost:9200/_aliases?pretty' -d '{
  "actions" : [
    { "remove" : { "index" : "hoge_index", "alias" : "hoge" } }
  ]
}'

参考

32
23
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
32
23