1. 程式人生 > >elasticsearch基本操作一

elasticsearch基本操作一

1.索引操作

# 建立名為data索引 0備份 3分片
PUT data
{
  "settings": {
    "index": {
      "number_of_replicas": 0,
      "number_of_shards": 3
    }
  }
}

# 查詢data索引配置
GET data/_settings

# 獲取所有索引配置
GET _all/_settings

# 刪除data索引
DELETE data

2.單文件增刪改查操作

# 新增id為1的文件
PUT data/user/1
{
  "name": "tom",
  "age": 15,
  "hobby": ["fb", "google"] 
}

# 新增文件不指定ID
POST data/user
{
  "name": "Jack",
  "age": 25,
  "hobby": ["百度", "google"] 
}

# 查詢ID為1的文件
GET data/user/1

# 查詢ID為1的文件 指定列
GET data/user/1?_source=name,age

# 替換文件
PUT data/user/1
{
  "name": "Jack_new",
  "age": 35,
  "hobby": ["百度", "googl_new"]  
}

# 指定修改欄位
POST data/user/1/_update
{
  "doc": {
    "age": 100
  }
}

#刪除文件
DELETE data/user/1

3.Muti Get批量查詢文件

GET data/user/_mget
{
  "docs": [
    {
      "_id": 2,
      "_source": ["age"]
    },
    {
      "_id": 2
    },
    {
      "_id": 3
    }
  ]
}

GET data/user/_mget
{
  "ids": [1, 2, 3, 4]
}

4.Bulk API批量增刪改

格式
{action: {metadata}}
{requestBody}

action
	create: 文件已存在會報錯
	index:文件替換
	update: 更新
	delete:刪除

metadata
	_index
	 _type
	  _id
	  
# 批量新增
POST res/book/_bulk
{"index":{"_id":1}}
{"title":"java","price":10}
{"index":{"_id":2}}
{"title":"C++","price":20}
{"index":{"_id":3}}
{"title":"PHP","price":5}
{"index":{"_id":4}}
{"title":"Python","price":40}

# 批量操作
POST res/book/_bulk
{"delete":{"_id":1}}
{"create":{"_id":5}}
{"title":"js","price":100}
{"update":{"_id":2}}
{"doc": {"price": 1000}}

注意:Bulk API載入到記憶體中執行,建議文件數1000~5000,大小不要超過100M

5.版本控制(樂觀鎖機制)

# 內部版本控制 (version和es中的值相等及可更新)
PUT data/user/1?version=2
{
  "name": "version",
  "age": 15,
  "hobby": ["fb", "google"] 
}

# 外部版本控制 (version比es中的值大即可更新)
PUT data/user/1?version=10&version_type=external
{
  "name": "version",
  "age": 15,
  "hobby": ["fb", "google"] 
}

6.常用資料型別

字元型:text keyword (keyword不會分詞)
數字型別:long integer short byte double float
日期型別:date
布林型別:boolean
二進位制型:binary
陣列
物件型別
地理位置型別
IPv4型別

7.mapping

PUT custom
{
  "settings": {
    "number_of_replicas": 0,
    "number_of_shards": 1
  },
  "mappings": {
    "person": {
      "properties": {
        "title":{"type": "text"},
        "name":{"type": "text", "analyzer": "standard"},
        "birtyday":{"type": "date", "index": false},
        "money":{"type": "double"},
        "age":{"type": "integer"}
      }
    }
  }
}

GET custom/person/_mapping