搜索引擎(Elasticsearch索引管理)

学完本课题,你应达成以下目标:

掌握ES的基本使用。
掌握索引的管理操做
掌握映射的相关知识、操做。
掌握索引的别名html

快速入门

查看集群的健康情况node

http://localhost:9200/_cat
http://localhost:9200/_cat/health?v
v是用来要求在结果中返回表头

状态值说明数据库

Green - everything is good (cluster is fully functional)
  Yellow - all data is available but some replicas are not yet allocated (cluster is fully functional)
  Red - some data is not available for whatever reason (cluster is partially functional)

查看集群的节点json

http://localhost:9200/_cat/nodes?v

查看全部索引api

http://localhost:9200/_cat/indices?v

建立一个索引数组

建立一个名为 customer 的索引。pretty要求返回一个漂亮的json 结果缓存

PUT /customer?pretty

再查看一下全部索引app

GET /_cat/indices?v

索引一个文档到customer索引中curl

curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "John Doe"
}
'

1?是文档id

从customer索引中获取指定id的文档elasticsearch

curl -X GET "localhost:9200/customer/_doc/1?pretty"

查询全部文档

GET /customer/_search?q=*&sort=name:asc&pretty

JSON格式方式

GET /customer/_search
{
  "query": { "match_all": {} },
  "sort": [
    {"name": "asc" }
  ]
}
curl -X GET "localhost:9200/customer/_search" -H 'Content-Type: application/json' -d'
{
  "query": { "match_all": {} },
  "sort": [
    {"name": "asc" }
  ]
}
'

 

索引管理

Create Index   建立索引

PUT twitter
{
    "settings" : {
        "index" : {
            "number_of_shards" : 3, 
            "number_of_replicas" : 2 
        }
    }
}
Default for number_of_shards is 5,max is 1024
Default for number_of_replicas is 1 (ie one replica for each primary shard)
索引的名字必须是小写的,不可重名

或简单的写为:

PUT twitter
{
    "settings" : {
        "number_of_shards" : 3,
        "number_of_replicas" : 2
    }
}

Create Index  with mapping    在建立时加入映射定义

PUT test
{
    "settings" : {
        "number_of_shards" : 1
    },
    "mappings" : {
        "type1" : {
            "properties" : {
                "field1" : { "type" : "text" }
            }
        }
    }
}

Create Index  with Aliases    在建立时加入别名定义

PUT test
{
    "aliases" : {
        "alias_1" : {},
        "alias_2" : {
            "filter" : {
                "term" : {"user" : "kimchy" }
            },
            "routing" : "kimchy"
        }
    }
}

返回结果说明

{
    "acknowledged": true,            索引建立成功
    "shards_acknowledged": true,    所需数量的分片+副本启动成功
    "index": "test"
}

acknowledged、shards_acknowledged 这两个值也会返回false,若是没有返回错误信息,则表示等待时间到了超时时间就直接返回了。

Get Index   查看索引的定义信息

GET /twitter
能够一次获取多个索引(以逗号间隔)
获取全部索引   _all 或  用通配符*
GET /twitter/_settings
GET /twitter/_mapping

Delete Index

DELETE /twitter

能够一次删除多个索引(以逗号间隔) 删除全部索引   _all 或 通配符 *

判断索引是否存在

HEAD twitter

HTTP status code 表示结果 404 不存在 , 200 存在

修改索引的settings信息

索引的设置信息分为静态信息和动态信息两部分。静态信息不可更改,如索引的分片数。动态信息能够修改。详细的设置项请参考: https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules.html#index-modules-settings

REST 访问端点: 
 /_settings  更新全部索引的。
 {index}/_settings     更新一个或多个索引的settings。

修改备份数

PUT /twitter/_settings
{
    "index" : {
        "number_of_replicas" : 2
    }
}

设置回默认值,用null

PUT /twitter/_settings
{
    "index" : {
        "refresh_interval" : null
    }
}

设置索引的读写

index.blocks.read_only:设为true,则索引以及索引的元数据只可读
index.blocks.read_only_allow_delete:设为true,只读时容许删除。
index.blocks.read:设为true,则不可读。
index.blocks.write:设为true,则不可写。
index.blocks.metadata:设为true,则索引元数据不可读写。

索引模板

在建立索引时,为每一个索引写定义信息多是一件繁琐的事情,ES提供了索引模板功能,让你能够定义一个索引模板,模板中定义好settings、mapping、以及一个模式定义来匹配建立的索引。

注意:模板只在索引建立时被参考,修改模板不会影响已建立的索引

PUT _template/template_1
{
  "index_patterns": ["te*", "bar*"],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "type1": {
      "_source": {
        "enabled": false
      },
      "properties": {
        "host_name": {
          "type": "keyword"
        },
        "created_at": {
          "type": "date",
          "format": "EEE MMM dd HH:mm:ss Z YYYY"
        }
      }
    }
  }
}
新增/修更名为tempae_1的模板,匹配名称为te* 或 bar*的索引建立。

查看索引模板

GET /_template/template_1
GET /_template/temp*
GET /_template/template_1,template_2
GET /_template

删除模板

DELETE /_template/template_1

Open/Close  Index   打开/关闭索引

POST /my_index/_close
POST /my_index/_open

关闭的索引不能进行读写操做,几乎不占集群开销。 关闭的索引能够打开,打开走的是正常的恢复流程。

Shrink Index 收缩索引

索引的分片数是不可更改的,如要减小分片数能够经过收缩方式收缩为一个新的索引。新索引的分片数必须是原分片数的因子值,如原分片数是8,则新索引的分片数能够为四、二、1 。

收缩的流程:

1.先把全部主分片都转移到一台主机上;
2.在这台主机上建立一个新索引,分片数较小,其余设置和原索引一致;
3.把原索引的全部分片,复制(或硬连接)到新索引的目录下;
4.对新索引进行打开操做恢复分片数据;
5.(可选)从新把新索引的分片均衡到其余节点上。

收缩前的准备工做:

将原索引设置为只读; 将原索引各分片的一个副本重分配到同一个节点上,而且要是健康绿色状态。

PUT /my_source_index/_settings
{
  "settings": {
    "index.routing.allocation.require._name": "shrink_node_name", 
    "index.blocks.write": true 
  }
}
shrink_node_name 指定进行收缩的节点的名称
index.blocks.write  阻止写,只读

进行收缩:

POST my_source_index/_shrink/my_target_index
{
  "settings": {
    "index.number_of_replicas": 1,
    "index.number_of_shards": 1, 
    "index.codec": "best_compression" 
  }}

监控收缩过程:

GET _cat/recovery?v
GET _cluster/health

Split Index 拆分索引

当索引的分片容量过大时,能够经过拆分操做将索引拆分为一个倍数分片数的新索引。能拆分为几倍由建立索引时指定的index.number_of_routing_shards 路由分片数决定。这个路由分片数决定了根据一致性hash路由文档到分片的散列空间。

如index.number_of_routing_shards = 30 ,指定的分片数是5,则可按以下倍数方式进行拆分:

  5 → 10 → 30 (split by 2, then by 3) 
  5 → 15 → 30 (split by 3, then by 2) 
  5 → 30 (split by 6) 

注意:只有在建立时指定了index.number_of_routing_shards 的索引才能够进行拆分,ES7开始将再也不有这个限制。

和solr的区别是,solr是对一个分片进行拆分,es中是整个索引进行拆分。

准备一个索引来作拆分:

PUT my_source_index
{
    "settings": {
        "index.number_of_shards" : 1,
        "index.number_of_routing_shards" : 2 //建立时须要指定路由分片数

    }
}

先设置索引只读:

PUT /my_source_index/_settings
{
  "settings": {
    "index.blocks.write": true 
  }
}

作拆分:

POST my_source_index/_split/my_target_index
{
  "settings": {
    "index.number_of_shards": 2 //新索引的分片数需符合拆分规则

  }
}

监控拆分过程:

GET _cat/recovery?v
GET _cluster/health

Rollover Index 别名滚动指向新建立的索引

对于有时效性的索引数据,如日志,过必定时间后,老的索引数据就没有用了。咱们能够像数据库中根据时间建立表来存放不一样时段的数据同样,在ES中也可用建多个索引的方式来分开存放不一样时段的数据。比数据库中更方便的是ES中能够经过别名滚动指向最新的索引的方式,让你经过别名来操做时老是操做的最新的索引。

ES的rollover index API 让咱们能够根据知足指定的条件(时间、文档数量、索引大小)建立新的索引,并把别名滚动指向新的索引。

注意:这时的别名只能是一个索引的别名。

Rollover Index 示例

PUT /logs-000001 
{
  "aliases": {
    "logs_write": {}
  }
}

建立一个名字为logs-0000001 、别名为logs_write 的索引


# Add > 1000 documents to logs-000001

POST /logs_write/_rollover 
{
  "conditions": {
    "max_age":   "7d",
    "max_docs":  1000,
    "max_size":  "5gb"
  }
}
若是别名logs_write指向的索引是7天前(含)建立的或索引的文档数>=1000或索引的大小>= 5gb,则会建立一个新索引 logs-000002,并把别名logs_writer指向新建立的logs-000002索引

Rollover Index 新建索引的命名规则

若是索引的名称是-数字结尾,如logs-000001,则新建索引的名称也会是这个模式,数值增1。 若是索引的名称不是-数值结尾,则在请求rollover api时需指定新索引的名称:

POST /my_alias/_rollover/my_new_index_name
{
  "conditions": {
    "max_age":   "7d",
    "max_docs":  1000,
    "max_size": "5gb"
  }
}

在名称中使用Date math(时间表达式)

若是你但愿生成的索引名称中带有日期,如logstash-2016.02.03-1 ,则能够在建立索引时采用时间表达式来命名:

# PUT /<logs-{now/d}-1> with URI encoding:
PUT /%3Clogs-%7Bnow%2Fd%7D-1%3E 
{
  "aliases": {
    "logs_write": {}
  }
}

PUT logs_write/_doc/1
{
  "message": "a dummy log"
}

POST logs_write/_refresh
# Wait for a day to pass

POST /logs_write/_rollover 
{
  "conditions": {
    "max_docs":   "1"
  }
}

Rollover时可对新的索引做定义

PUT /logs-000001
{
  "aliases": {
    "logs_write": {}
  }
}

POST /logs_write/_rollover
{
  "conditions" : {
    "max_age": "7d",
    "max_docs": 1000,
    "max_size": "5gb"
  },
  "settings": {
    "index.number_of_shards": 2
  }
}

Dry run  实际操做前先来个排练

POST /logs_write/_rollover?dry_run
{
  "conditions" : {
    "max_age": "7d",
    "max_docs": 1000,
    "max_size": "5gb"
  }
}

排练不会建立索引,只是检测条件是否知足

注意:rollover是你请求它才会进行操做,并非自动在后台进行的。你能够周期性地去请求它。

 

索引监控

查看索引状态信息

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-stats.html

GET /_stats
GET /index1,index2/_stats

查看索引段信息

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-segments.html

GET /test/_segments
GET /index1,index2/_segments
GET /_segments

查看索引恢复信息

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-recovery.html
GET index1,index2/_recovery?human
GET /_recovery?human

查看索引分片的存储信息

# return information of only index test
GET /test/_shard_stores

# return information of only test1 and test2 indices
GET /test1,test2/_shard_stores

# return information of all indices
GET /_shard_stores
GET /_shard_stores?status=green

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-shards-stores.html

 

索引状态管理

Clear Cache 清理缓存

POST /twitter/_cache/clear

默认会清理全部缓存,可指定清理query, fielddata or request 缓存

POST /kimchy,elasticsearch/_cache/clear 
POST /_cache/clear

Refresh,从新打开读取索引

POST /kimchy,elasticsearch/_refresh

POST /_refresh

Flush,将缓存在内存中的索引数据刷新到持久存储中

POST twitter/_flush

Force merge 强制段合并

POST /kimchy/_forcemerge?only_expunge_deletes=false&max_num_segments=100&flush=true

可选参数说明:

max_num_segments 

合并为几个段,默认1

only_expunge_deletes 

是否只合并含有删除文档的段,默认false

flush 

合并后是否刷新,默认true

POST /kimchy,elasticsearch/_forcemerge

POST /_forcemerge

 

映射详解

Mapping 映射是什么

映射定义索引中有什么字段、字段的类型等结构信息。至关于数据库中表结构定义,或 solr中的schema。由于lucene索引文档时须要知道该如何来索引存储文档的字段。 ES中支持手动定义映射,动态映射两种方式。

Create Index  with mapping

PUT test
{
"mappings" : {          //映射定义
        "type1" : {     //名为type1的映射类别 mapping type
            "properties" : {     //字段定义
                "field1" : { "type" : "text" } //名为field1的字段,它的field datatype 为 text
            }
        }
    }
}

映射定义后续能够修改

映射类别 Mapping type 废除说明

ES最早的设计是用索引类比关系型数据库的数据库,用mapping type 来类比表,一个索引中能够包含多个映射类别。这个类比存在一个严重的问题,就是当多个mapping type中存在同名字段时(特别是同名字段仍是不一样类型的),在一个索引中很差处理,由于搜索引擎中只有 索引-文档的结构,不一样映射类别的数据都是一个一个的文档(只是包含的字段不同而已)

从6.0.0开始限定仅包含一个映射类别定义( "index.mapping.single_type": true ),兼容5.x中的多映射类别。从7.0开始将移除映射类别。 为了与将来的规划匹配,请如今将这个惟一的映射类别名定义为“_doc”,由于索引的请求地址将规范为:PUT {index}/_doc/{id} and POST {index}/_doc

多个映射类别就转变为多个索引。若是你还想要在一个索引中放多类数据,也可像在数据库中定义骷髅表同样,经过定义一个数据类别字段,来区分不一样的数据。

Mapping 映射示例

PUT twitter
{
  "mappings": {
    "_doc": {
      "properties": {
        "type": { "type": "keyword" }, 
        "name": { "type": "text" },
        "user_name": { "type": "keyword" },
        "email": { "type": "keyword" },
        "content": { "type": "text" },
        "tweeted_at": { "type": "date" }
      }
    }
  }
}

多映射类别数据转储到独立的索引中    

ES 提供了reindex API 来作这个事

PUT users
{
  "settings": {
    "index.mapping.single_type": true
  },
  "mappings": {
    "_doc": {
      "properties": {
        "name": {
          "type": "text"
        },
        "user_name": {
          "type": "keyword"
        },
        "email": {
          "type": "keyword"
        }
      } }  }}
POST _reindex
{
  "source": {
    "index": "twitter",
    "type": "user"
  },
  "dest": {
    "index": "users"
  }
}

转储到骷髅索引

POST _reindex
{
  "source": {
    "index": "twitter"
  },
  "dest": {
    "index": "new_twitter"
  },
  "script": {
    "source": """
      ctx._source.type = ctx._type;
      ctx._id = ctx._type + '-' + ctx._id;
      ctx._type = '_doc';
    """
  }
}

字段类型 datatypes

字段类型定义了该如何索引存储字段值。ES中提供了丰富的字段类型定义,请查看官网连接详细了解每种类型的特色:

https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html

Core Datatypes     核心类型

string
    text and keyword 
Numeric datatypes
    long, integer, short, byte, double, float, half_float, scaled_float 
Date datatype
    date 
Boolean datatype
    boolean 
Binary datatype
    binary 
Range datatypes     范围
    integer_range, float_range, long_range, double_range, date_range

 

Complex datatypes  复合类型

Array datatype
    数组就是多值,不须要专门的类型
Object datatype
    object :表示值为一个JSON 对象 
Nested datatype
    nested:for arrays of JSON objects(表示值为JSON对象数组 )

 

Geo datatypes  地理数据类型

Geo-point datatype
    geo_point: for lat/lon points  (经纬坐标点)
Geo-Shape datatype
    geo_shape: for complex shapes like polygons (形状表示)

Specialised datatypes  特别的类型

IP datatype
    ip: for IPv4 and IPv6 addresses 
Completion datatype
    completion: to provide auto-complete suggestions 
Token count datatype
    token_count: to count the number of tokens in a string 
mapper-murmur3
    murmur3: to compute hashes of values at index-time and store them in the index 
Percolator type
    Accepts queries from the query-dsl 
join datatype
    Defines parent/child relation for documents within the same index

字段定义属性介绍

字段的type (Datatype)定义了如何索引存储字段值,还有一些属性可让咱们根据须要来覆盖默认的值或进行特别定义。请参考官网介绍详细了解: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-params.html

字段定义属性—示例

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "date": {
          "type":   "date",
          "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
        }
      }
    }
  }
}

请详细查看每一个字段类型对应的可设置属性。

Multi Field 多重字段

当咱们须要对一个字段进行多种不一样方式的索引时,可使用fields多重字段定义。如一个字符串字段即须要进行text分词索引,也须要进行keyword 关键字索引来支持排序、聚合;或须要用不一样的分词器进行分词索引。

Multi Field 多重字段—示例

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "city": {
          "type": "text",
          "fields": {
            "raw": { 
              "type":  "keyword"
            }
          }
        }
      }
    }
  }
}
raw是一个多重版本名(自定义)
PUT my_index/_doc/1
{
  "city": "New York"
}

PUT my_index/_doc/2
{
  "city": "York"
}
GET my_index/_search
{
  "query": {
    "match": {
      "city": "york" 
    }
  },
  "sort": {
    "city.raw": "asc" 
  },
  "aggs": {
    "Cities": {
      "terms": {
        "field": "city.raw" 
      }
    }
  }
}

元字段

元字段是ES中定义的文档字段,有如下几类:

详细了解: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-fields.html

动态映射

动态映射:ES中提供的重要特性,让咱们能够快速使用ES,而不须要先建立索引、定义映射。 如咱们直接向ES提交文档进行索引:

PUT data/_doc/1 
{ "count": 5 }

ES将自动为咱们建立data索引、_doc 映射、类型为 long 的字段 count

索引文档时,当有新字段时, ES将根据咱们字段的json的数据类型为咱们自动加人字段定义到mapping中。

字段动态映射规则

Date detection  时间侦测

date_detection 默认是开启的,默认的格式dynamic_date_formats为:

[ "strict_date_optional_time","yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z"]
PUT my_index/_doc/1
{
  "create_date": "2015/09/02"
}

GET my_index/_mapping
PUT my_index
{
  "mappings": {
    "_doc": {
      "dynamic_date_formats": ["MM/dd/yyyy"]
    }
  }
}
自定义时间格式
PUT my_index
{
  "mappings": {
    "_doc": {
      "date_detection": false
    }
  }
}
禁用时间侦测:

Numeric detection  数值侦测

PUT my_index
{
  "mappings": {
    "_doc": {
      "numeric_detection": true   //开启数值侦测(默认是禁用的)
    }
  }
}

PUT my_index/_doc/1
{
  "my_float":   "1.0", 
  "my_integer": "1" 
}

 

索引别名

别名的用途

若是但愿一次查询可查询多个索引。 若是但愿经过索引的视图来操做索引,就像数据库库中的视图同样。

索引的别名机制,就是让咱们能够以视图的方式来操做集群中的索引,这个视图但是多个索引,也但是一个索引或索引的一部分。

新建索引时定义别名

PUT /logs_20162801
{
    "mappings" : {
        "type" : {
            "properties" : {
                "year" : {"type" : "integer"}
            }
        }
    },
    "aliases" : {
        "current_day" : {},
        "2016" : {
            "filter" : {
                "term" : {"year" : 2016 }
            }
        }
    }
}
定义了两个别名

建立别名     /_aliases

POST /_aliases
{
    "actions" : [
        { "add" : { "index" : "test1", "alias" : "alias1" } }
    ]
}

删除别名

POST /_aliases
{
    "actions" : [
        { "remove" : { "index" : "test1", "alias" : "alias1" } }
    ]
}
DELETE /{index}/_alias/{name}

批量操做

POST /_aliases
{
    "actions" : [
        { "remove" : { "index" : "test1", "alias" : "alias1" } },
        { "add" : { "index" : "test2", "alias" : "alias1" } }
    ]
}

为多个索引定义别名方式一

POST /_aliases
{
    "actions" : [
        { "add" : { "index" : "test1", "alias" : "alias1" } },
        { "add" : { "index" : "test2", "alias" : "alias1" } }
    ]
}

为多个索引定义别名方式二

注意:只可经过多索引别名进行搜索,不可进行文档索引和根据id获取文档。

POST /_aliases
{
    "actions" : [
        { "add" : { "indices" : ["test1", "test2"], "alias" : "alias1" } }
    ]
}

方式三:经过统配符*模式来指定要别名的索引

POST /_aliases
{
    "actions" : [
        { "add" : { "index" : "test*", "alias" : "all_test_indices" } }
    ]
}

注意:在这种状况下,别名是一个点时间别名,它将对全部匹配的当前索引进行别名,当添加/删除与此模式匹配的新索引时,它不会自动更新。

带过滤器的别名

索引中须要有字段

PUT /test1
{
  "mappings": {
    "type1": {
      "properties": {
        "user" : {
          "type": "keyword"
        }
      }
    }
  }
}

过滤器经过Query DSL来定义,将做用于经过该别名来进行的全部Search, Count, Delete By Query and More Like This 操做。

POST /_aliases
{
    "actions" : [
        {
            "add" : {
                 "index" : "test1",
                 "alias" : "alias2",
                 "filter" : { "term" : { "user" : "kimchy" } }
            }
        }
    ]
}

带routing的别名

可在别名定义中指定路由值,可和filter一块儿使用,用来限定操做的分片,避免不须要的其余分片操做。

POST /_aliases
{
    "actions" : [
        {
            "add" : {
                 "index" : "test",
                 "alias" : "alias1",
                 "routing" : "1"
            }
        }
    ]
}
POST /_aliases
{
    "actions" : [
        {
            "add" : {
                 "index" : "test",          //为搜索、索引指定不一样的路由值
                 "alias" : "alias2",
                 "search_routing" : "1,2",
                 "index_routing" : "2"
            }
        }
    ]
}

下面的查询自己指定了路由值,请问它最终使用的路由值是多少?

GET /alias2/_search?q=user:kimchy&routing=2,3

以PUT方式来定义一个索引

PUT /{index}/_alias/{name}

PUT /logs_201305/_alias/2013

带filter 和 routing

PUT /users
{
    "mappings" : {
        "user" : {
            "properties" : {
                "user_id" : {"type" : "integer"}
            }
        }
    }
}
PUT /users/_alias/user_12
{
    "routing" : "12",
    "filter" : {
        "term" : {
            "user_id" : 12
        }
    }
}

查看别名定义信息

GET /{index}/_alias/{alias}
GET /logs_20162801/_alias/*
GET /_alias/2016
GET /_alias/20*
相关文章
相关标签/搜索