上节对ES的安装进行了描述, 这节来具体看下如何对ES进行操作
点击此处查看ES的安装
前言
ES是基于RESTful风格方式来进行操作的, 有关RESTful相关的知识,本人对RESTful只停留在用上, 这里推荐大家查看 大神之作
下面来看我们对ES的实际操作
ES实操
接下来我们操作ES, 在实际操作中对涉及到的概念进行描述
基础操作
这里我们以我的小说项目为例
创建索引库
PUT http://sanq1.com.cn:9200/books
输出:
{
"acknowledged": true,
"shards_acknowledged": true
}
索引是含有相同属性的文档集合, 例如我们的小说信息就会存在这个索引库里面
这里索引库相当于在关系型数据库中的库
,
在实际操作中, 如果该索引库不存在, API会自动创建该索引以及该特定JSON对象的基础映射。
如果需要取消, 可以在elasticsearch.yml
配置文件中进行设置
action.auto_create_index:false
index.mapper.dynamic:false
保存数据
POST http://sanq1.com.cn:9200/books/books/1
{
"id": "1",
"booksName": "斗破苍穹",
"author": "天蚕土豆"
}
输出:
{
"_index": "books",
"_type": "books",
"_id": "1",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
在这里存在一个叫类型
的概念, 这里相当于在关系型数据库中的 表
只有有这个表了, 数据才能够存储到ES中
JSON中key是ES中的文档
文档是可以被索引存储的基本数据单位
相当于表中的 表
中的字段
修改数据
PUT http://sanq1.com.cn:9200/books/books/1
{
"id": "1",
"booksName": "斗破苍穹111",
"author": "天蚕土豆111"
}
输出:
{
"_index": "books",
"_type": "books",
"_id": "1",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": false
}
查询当前数据
GET http://sanq1.com.cn:9200/books/books/1
输出:
{
"_index": "books",
"_type": "books",
"_id": "1",
"_version": 2,
"found": true,
"_source": {
"id": "1",
"booksName": "斗破苍穹111",
"author": "天蚕土豆111"
}
}
如果我们想显示指定的字段, 我们可以这样来查询
GET http://sanq1.com.cn:9200/books/books/1_source=booksName&pretty
输出:
{
"_index": "books",
"_type": "books",
"_id": "1",
"_version": 1,
"found": true,
"_source": {
"booksName": "斗破苍穹"
}
}
查询数据并分页
GET http://sanq1.com.cn:9200/books/books/_search
{
"query": {
"match": {
"author": "辰"
}
},
"from": 1, //从那条数据开始
"size": 2, //返回的条数
"sort": [
{"id.keyword": {"order": "desc"}}
]
}
输出:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.51623213,
"hits": [
{
"_index": "books",
"_type": "books",
"_id": "3",
"_score": 0.51623213,
"_source": {
"id": "3",
"booksName": "完美世界",
"author": "辰东"
}
},
...
]
}
}
问题
本人在排序的时候遇到了以下问题, 所以使用 id.keyword
直接使用text字段问题: Fielddata is disabled on text fields by default. Set fielddata=true on [id] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.
删除数据
DELETE http://sanq1.com.cn:9200/books/books/1
输出:
{
"found": true,
"_index": "books",
"_type": "books",
"_id": "1",
"_version": 3,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
删除索引库
DELETE http://sanq1.com.cn:9200/books
输出:
{
"acknowledged": true
}
这些就是简单的基本操作, 大家可以亲自尝试尝试,
也推荐大家去ES的官网查看更多的操作
ElasticSearch权威指南