Create/Delete Index and CRUD Docs

1. Create and Delete Index

1-1. Delete Index

  • http verb is used
DELETE /{index name}

1-2. Create Index

PUT /{index name}
<!-- setting on request body -->
{
    "settings": {
        "number_of_shards": {n},
        "number_of_replicas": {n}
    }
}

2. CRUD Documents

2-1. Add Documents to index

it is more technically correct to say "index a document"

  • use POST request
PUT /{index name}/_doc
<!-- content on request body -->
{
    "name": "Coffee Maker",
    "price": 64,
    "in_stock": 10
}
  • response body
{
    "_index" : "products",
    "_type" : "_doc",
    "_id" : "oxshUdKes2203",
    "_version" : 1,
    "result" : "created",
    "_shards" : {
        "totla" : 3,
        "successful" : 3,
        "failed" : 0
    },
    "_seq_no" : 0,
    "_primary_term" : 1
}

_shards : size of replication group (pri 1 + replica 2)

_id : identifier for doc

  • _id can be specified in the url
PUT /{index name}/_doc/{doc id}
  • indexing a document also auto-creates index

2-2. Read From Document

  • use GET http verb
GET /products/_doc/{doc id}
  • document content is returned in _source

2-3. Update Document

  • use POST verb
  • doc object is used for content
POST /{index name}/_update/{doc id}
{
    "doc" : {
        "{field name}" : {value}
    }
    
}
  • Elasticsearch documents are immutable
  • Updating document actually creates new doc and replace

2-4. Scripted Update

POST /{index name}/_update/{doc id}
{
    "script" : {
        "source" : "ctx._source.{field name}--"
    }
}
  • above request update value of field to n -1
POST /{index name}/_update/{doc id}
{
    "script" : {
        "source" : "ctx._source.{field name} = 10"
    }
}
  • above request update value of field to 10
POST /{index name}/_update/{doc id}
{
    "script" : {
        "source" : "ctx._source.{field name} -= params.{param name}",
        "params" : {
            "{param name}" : 4
        }
    }
}
  • above request update value of field to n - parameter value

2-5. Upserting

updating based on existence of document

POST /{index name}/_update/{doc id}
{
    "script" : {
        "source" : "ctx._source.{field name}++"
    },
    "upsert": {
        "{field name}" : "{value}"
    }
}
  • script will run if doc exist, else creates new doc with content from upsert

2-6. Replace Document

PUT /{index name}/_doc/{doc id}
{
    "{field name}" : {value}
}

2-7. Delete Document

DELETE /{index name}/_doc/{doc id}

좋은 웹페이지 즐겨찾기