这篇 ElasticSearch 详细使用教程,内部分享时被老大表扬了
一、快速入门
1.查看集群的健康状况
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),即数据和集群都不可用
- 查看集群的节点
http://localhost:9200/_cat/?v
2. 查看所有索引
http://localhost:9200/_cat/indices?v
3. 创建一个索引
创建一个名为 customer 的索引。pretty要求返回一个漂亮的json 结果
PUT /customer?pretty
再查看一下所有索引(超详细 116 页 Elasticsearch 实战文档!高清可下载)
http://localhost:9200/_cat/indices?v
GET /_cat/indices?v
4. 索引一个文档到customer索引中
curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "John Doe"
}
'
5. 从customer索引中获取指定id的文档
curl -X GET "localhost:9200/customer/_doc/1?pretty"
6. 查询所有文档
GET /customer/_search?q=*&sort=name:asc&pretty
JSON格式方式(ElasticSearch 亿级数据检索案例实战!)
GET /customer/_search
{
"query": { "match_all": {} },
"sort": [
{"name": "asc" }
]
}
二、索引管理
1. 创建索引
创建一个名为twitter的索引,设置索引的分片数为3,备份数为2。注意:在ES中创建一个索引类似于在数据库中建立一个数据库(ES6.0之后类似于创建一个表)
PUT twitter
{
"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}
}
}
说明:
- 默认的分片数是5到1024
- 默认的备份数是1
- 索引的名称必须是小写的,不可重名
创建结果:
创建的命令还可以简写为
PUT twitter
{
"settings" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}
}
2. 创建mapping映射
注意:在ES中创建一个mapping映射类似于在数据库中定义表结构,即表里面有哪些字段、字段是什么类型、字段的默认值等;也类似于solr里面的模式schema的定义
PUT twitter
{
"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}
},
"mappings" : {
"type1" : {
"properties" : {
"field1" : { "type" : "text" }
}
}
}
}
3. 创建索引时加入别名定义
PUT twitter
{
"aliases" : {
"alias_1" : {},
"alias_2" : {
"filter" : {
"term" : {"user" : "kimchy" }
},
"routing" : "kimchy"
}
}
}
4. 创建索引时返回的结果说明
5. Get Index 查看索引的定义信息
GET /twitter,可以一次获取多个索引(以逗号间隔)获取所有索引_all或用通配符*
GET /twitter/_settings
GET /twitter/_mapping