## **索引創建**
(1) **創建簡單的索引**
注:索引名不能包含大些字母
```
PUT test
```
返回結果:
```
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "test"
}
```
(2) **重復創建**
```
PUT test
```
返回結果:
```
{
"error": {
"root_cause": [
{
"type": "resource_already_exists_exception",
"reason": "index [test/COV8EigST6y3qsLqoyho4Q] already exists",
"index_uuid": "COV8EigST6y3qsLqoyho4Q",
"index": "test"
}
],
"type": "resource_already_exists_exception",
"reason": "index [test/COV8EigST6y3qsLqoyho4Q] already exists",
"index_uuid": "COV8EigST6y3qsLqoyho4Q",
"index": "test"
},
"status": 400
}
```
(3) **創建索引并指定參數**
```
PUT test
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
}
}
```
注:
1. number_of_shards 設置索引的分片數
2. number_of_replicas 設置索引的副本數
返回結果:
```
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "test"
}
```
(4) **查看索引**
```
GET test/_settings
```
返回結果:
```
{
"test": {
"settings": {
"index": {
"creation_date": "1539070428878",
"number_of_shards": "3",
"number_of_replicas": "1",
"uuid": "ra8pa0bkTeKmAq5WDmczTA",
"version": {
"created": "6040099"
},
"provided_name": "test"
}
}
}
}
```
注:要獲取多個索引的時候索引之間用“,”隔開
```
GET test,book/_settings
```
(5) **刪除索引**
```
DELETE test
```
返回結果:
```
{
"acknowledged": true
}
```
## **設置mapping(表結構)**
(Mapping)用來定義一個文檔,可以定義所包含的字段以及字段的類型、分詞器及屬性等等。映射可以分為動態映射和靜態映射。
* 動態映射
我們知道,在關系數據庫中,需要事先創建數據庫,然后在該數據庫實例下創建數據表,然后才能在該數據表中插入數據。而ElasticSearch中不需要事先定義映射(Mapping),文檔寫入ElasticSearch時,會根據文檔字段自動識別類型,這種機制稱之為動態映射。
* 靜態映射
當然,在ElasticSearch中也可以事先定義好映射,包含文檔的各個字段及其類型等,這種方式稱之為靜態映射。
**(1) 動態映射實例**
查看空mapping
```
GET test/_mapping
```
返回結果:
```
{
"test": {
"mappings": {}
}
}
```
插入文檔
```
PUT test/it/1
{
"testid" : 1 ,
"testname" : "test動態索引",
"date" : "2018-10-09"
}
```
再次查看索引
```
GET test/_mapping
```
返回結果:
```
{
"test": {
"mappings": {
"it": {
"properties": {
"date": {
"type": "date"
},
"testid": {
"type": "long"
},
"testname": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}
```
說明:動態索引是指創建索引時不設置字段以及字段屬性,當插入文檔時elasticsearch自動識別創建對應的字段以及字段類型
ElasticSearch動態映射規則如下:

**(2) 靜態映射**
動態映射的自動類型推測功能并不是100%正確的,這就需要靜態映射機制。靜態映射與關系數據庫中創建表語句類型,需要事先指定字段類型。相對于動態映射,靜態映射可以添加更加詳細字段類型、更精準的配置信息等。
* 新建映射
```
PUT test
{
"mappings": {
"it":{
"properties":{
"id" : {
"type" : "long"
},
"name" : {
"type" : "text"
},
"date" : {
"type" : "date"
}
}
}
}
}
```
* 查看mapping
```
GET test/_mapping
```
返回結果:
```
{
"test": {
"mappings": {
"it": {
"properties": {
"date": {
"type": "date"
},
"id": {
"type": "long"
},
"name": {
"type": "text"
}
}
}
}
}
}
```