## **索引创建**
(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动态映射规则如下:
![](https://box.kancloud.cn/9c3447b38c0b88662da4612e9c154125_853x363.png)
**(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"
}
}
}
}
}
}
```