ElasticSearch 入门
ES 作为一个索引以及搜索服务, 对外提供丰富的 REST 接口.
创建索引库
ES 索引库是一个逻辑概念, 包括分词列表和文档列表, 同一个索引库中存储了相同类型的文档. 相当于 MYSQL中的表.
索引 (名词) : ES 是基于 Lucene 构建的一个搜索服务, 他要从索引库搜索符合条件索引数据.
索引(动词) : 索引库刚创建起来是空的, 将数据添加到索引库的过程称为索引.
- 使用 Postman 创建
Put http://localhost:9200/索引库名称
{
"settings":{
"index":{
"number_of_shards":1,
"number_of_replicas":0
}
}
}
number_of_shards: 设置分片数量, 在急群众通常设置多个分片, 表示一个索引库将拆分为多个片分别存储不同的节点, 提高了 ES 处理能力和高可用性, 入门程序使用单机环境, 这里设置为 1.
number_of_replicas: 设置副本的数量, 设置副本是为了提高 ES 的高可用性, 单机环境设置为 0.
- 使用 head 插件
创建映射
在索引中每个文档都包括了一个或者多个 field , 创建映射就是向索引库中创建 field 的过程, 下边是 document 和 field 与关系型数据库的类比 :
文档(Document) ---------- Row 记录
字段(Field) ---------- Columns 列
格式 :
POST http://localhost:9200/索引库名称/类型名称(随便起)/_mapping
例子 :
post 请求 : http://localhost:/video/doc/_mapping
{
"properties": {
"name": {
"type": "text"
},
"description": {
"type": "text"
},
"studymodel": {
"type": "keyword"
}
}
}
查看 :
创建文档
ES 的文档相当于 MYSQL 数据库表中的记录 .
格式:
PUT 或者 POST http://localhost:9200/video/doc/id (如果不指定id值 ES会自动生成 ID)
例子:
http://localhost:9200/video/doc/4028e58161bcf7f40161bcf8b77c0000
{
"name":"Bootstrap开发框架",
"description":"Bootstrap是由Twitter推出的一个前台页面开发框架,在行业之中使用较为广泛",
"studymodel":"201001"
}
通过 head 查询数据
搜索文档
- 根据课程 id 查询文档
get 方式 : http://localhost:9200/video/doc/文档id
- 查询所有文档
get方式 : http://localhost:9200/video/doc/_search
- 查询名称中包括 spring 关键字的记录
get 方式 : http://localhost:9200/video/doc/_search?q=name:bootstrap
查询结果分析
{
#本次操作花费的时间, 单位是 ms
"took": 1,
#本次操作是否超时
"timed_out": false,
#本次操作共搜索了哪些分片
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
#本次操作命中的记录
"hits": {
#符合条件的文档总数
"total": 1,
#文档匹配得分的最高分
"max_score": 1.0,
#匹配度较高的前 N 个文档
"hits": [
{
#索引名称
"_index": "video",
#类型名称
"_type": "doc",
#文档的 id
"_id": "jjnwVmwBjulLaJcn1Ycy",
#匹配度得分 降序
"_score": 1.0,
#原始内容
"_source": {
"name": "Bootstrap开发框架",
"description": "Bootstrap是由Twitter推出的一个前台页面开发框架",
"studymodel": "201001"
}
}
]
}
}
"description": "Bootstrap是由Twitter推出的一个前台页面开发框架",
"studymodel": "201001"
}
}
]
}
}