新增文档
ElasticSearch会自动建立index和type,不需要提前创建
基本格式
PUT /index/type/id
{
"数据"
}
操作
测试代码
PUT article/poems/1
{
"title":"静夜思",
"author":"李白",
"dynasty":"唐",
"words":20,
"tags":[
"月亮","思乡","五言绝句"
],
"content":"床前明月光,疑是地上霜。举头望明月,低头思故乡。"
}
PUT article/poems/2
{
"title":"悯农",
"author":"李绅",
"dynasty":"唐",
"words":20,
"tags":[
"农耕","五言绝句"
],
"content":"春种一粒粟,秋收万颗子。四海无闲田,农夫犹饿死。"
}
PUT article/poems/3
{
"title":"春夜喜雨",
"author":"杜甫",
"dynasty":"唐",
"words":40,
"tags":[
"春雨","五言律诗"
],
"content":"好雨知时节,当春乃发生。随风潜入夜,润物细无声。野径云俱黑,江船火独明。晓看红湿处,花重锦官城。"
}
PUT article/poems/4
{
"title":"望庐山瀑布",
"author":"李白",
"dynasty":"唐",
"words":20,
"tags":[
"瀑布","七言绝句"
],
"content":"日照香炉生紫烟,遥看瀑布挂前川。飞流直下三千尺,疑是银河落九天。"
}
PUT article/poems/5
{
"title":"早发白帝城",
"author":"李白",
"dynasty":"唐",
"words":28,
"tags":[
"船","七言绝句","白帝城"
],
"content":"朝辞白帝彩云间,千里江陵一日还。两岸猿声啼不住,轻舟已过万重山。"
}
检索文档
测试代码
查找全部(GET index/type/_search)
GET article/poems/_search
根据id查找(GET index/type/id)
GET article/poems/1
分页查找:from=从第几条开始查,size=共查几条(GET index/type/_search?from=0&size=10)
GET article/poems/_search?from=0&size=2
根据某个field排序查找(GET index/type/_search?sort=field)
正序
GET article/poems/_search?sort=_id
倒序
GET article/poems/_search?sort=_id:desc
替换文档
基本格式
跟新增格式一样,注意要带上所有field
PUT /index/type/id
{
"数据"
}
测试代码
PUT article/poems/2
{
"title":"咏柳",
"author":"贺知章",
"dynasty":"唐",
"words":20,
"tags":[
"农耕","七言绝句"
],
"content":"碧玉妆成一树高,万条垂下绿丝绦。不知细叶谁裁出,二月春风似剪刀。"
}
更新文档
基本格式
POST index/type/id/_update
{
"doc": {
"field":"value"
]
}
}
测试代码
POST article/poems/2/_update
{
"doc": {
"tags":[
"春天","七言绝句","春风","柳树"
]
}
}
删除文档
根据id删除
DELETE article/poems/5
Q&A
- Q:介绍下_index元数据
- 代表一个document存放在哪个index中
- 类似的数据放在一个索引,非类似的数据放在不同索引
- ndex中包含了很多类似的document。这些document的fields很大一部分是相同的
- 索引名必须是小写,不能用下划线开头,不能包含逗号
- Q:介绍下_type元数据
- 代表document属于index中的哪个类别(type)
- 一个索引通常会划分为多个type,逻辑上对index中有些许不同的几类数据进行分类
- type名称可以是大写或小写,不能用下划线开头,不能包含逗号
- Q:介绍下_id元数据,添加数据的时候可以自动生成id吗?
- 代表document的唯一标识,与index和type一起,可以唯一标识和定位一个document
- 可以手动指定document的id,也可以不指定,由ElasticSearch自动为我们创建
手动指定document id
自动生成document idPUT /index/type/id { "数据" }
采用GUID的算法生成长度为20个字符的id,URL安全,base64编码,分布式系统并行生成时不可能会发生冲突POST /index/type { "数据" }
- Q:介绍下_source元数据
指定返回的字段GET article/poems/_search?_source=title,content
- Q:如何进行大批量查询
https://www.elastic.co/guide/cn/elasticsearch/guide/current/scroll.html