2
1

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 : upsert の使い方

Posted at

試したのは elasticsearch 6.3.2

purpose

data["host"]["exist"] の値をupdateします。

insertした瞬間 exist = 1

updateすると exist = 0

upsert de insert

# まず消す
DELETE upsert-text

# upsertでinsert
POST upsert-text/_doc/1/_update?refresh     <------ _id=1 指定して登録
{
  "script" : {                     <----------- insert時はこのscript blockは使われません
        "source": "ctx._source.host = params.host",
        "lang": "painless",
        "params" : {
            "host" : {
              "exist" : "0"
            }
        }
  },
  "upsert" : {             <------- insertの場合はこの upsert blockがそのままinsertされます
    "host" : {
      "exist": "1"        <-------- insert時は 1 です
    }
  }
}

insertされたものを探す

# 全検索
GET upsert-text/_search
{
  "query": {
          "match_all": {}
  }
}

insertされたデータ

{
  ...,
  "hits": {
    ...,
    "hits": [
      {
        ...,
        "_source": {
          "host": {
            "exist": "1"                <--------------------- 1 で登録されてる
          }
        }
      }
    ]
  }
}

upsert de update!

さっきと同じupsertを流します。今度はすでにデータがあるのでupdateされます

# upsert で update
POST upsert-text/_doc/1/_update?refresh    <------ _id=1 指定して投げるので、あればupdateされる
{
  "script" : {                                         <------- updateのときは script blockが走ります
        "source": "ctx._source.host = params.host",     <---- ctx._source がupdate後のdataになります
        "lang": "painless",                            <------ painを感じざるを得ない言語を指定
        "params" : {                                <----- paramsの中の値が source で使える様子
            "host" : {
              "exist" : "0"                < ----------- update時は 0 にしています
            }
        }
  },
  "upsert" : {
    "host" : {
      "exist": "1"
    }
  }
}

updateされた結果を探す

# 全検索
GET upsert-text/_search
{
  "query": {
          "match_all": {}
  }
}

updateされた検索結果

{
  ...,
  "hits": {
    ...,
    "hits": [
      {
        ...,
        "_source": {
          "host": {
            "exist": "0"                <--------------------- 0 になりました!!
          }
        }
      }
    ]
  }
}

参考 https://www.elastic.co/guide/en/elasticsearch/reference/6.3/docs-update.html

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?