Index
索引可以理解为数据表。
常用操作有:新增、删除、判定存在与否。
新增索引
PUT /my_index
删除索引
DELETE /my_index
查找索引
判定是否存在
HEAD /my_index
获取索引具体信息
GET /my_index
获取的结果可以查看到如下信息
{"my_index" : {"aliases" : { },"mappings" : { },"settings" : {"index" : {"routing" : {"allocation" : {"include" : {"_tier_preference" : "data_content"}}},"number_of_shards" : "1","provided_name" : "my_index","creation_date" : "1611050751273","number_of_replicas" : "1","uuid" : "xOgkSJdsQFyL1EtQAJGz0w","version" : {"created" : "7100199"}}}}}
同时查询多个索引的信息
GET /my_index,nba
查找当前所有索引
GET /_cat/indices
Mapping
索引创建好后,还需要定义这个数据表的结构,那么Mapping 就是这个作用。Mapping 可以不用手动创建,ES支持新增字段动态映射,会根据文档内容自动生成。但是不推荐这么做。
ES中 **mapping** 一旦创建,就不能修改,只能 ReIndex(删除后重建)
新增 Mapping
以下是新增mapping的 2 个方式:全局全新设置和为新字段新增
全局全新设置
PUT /nba/_mapping{"properties": {"name": {"type": "text"},"team_name": {"type": "text"},"position": {"type": "keyword"},"play_year": {"type": "long"},"jerse_no": {"type": "keyword"}}}
新字段新增
PUT /forum{"mappings": {"properties": {"articleID": {"type": "keyword"}}}}
修改 Maping
ES 是禁止修改已有字段的 Mapping ,就是说对于字段已经存在索引,需要删除后索引后重新建立。
但是如果是新增一个不存在的字段,那么可以作为新增一个字段的索引来进行操作。
删除 Mapping
删除 mapping,其实就是删除整个索引。
DELETE /nba
获取 mapping
GET /nba/_mapping{"nba" : {"mappings" : {"properties" : {"allstar" : {"type" : "long"},"country" : {"type" : "keyword"},"name" : {"type" : "text"}...}}}}
也支持指定字段进行获取
GET nba/_mapping/field/country{"nba" : {"mappings" : {"country" : {"full_name" : "country","mapping" : {"country" : {"type" : "keyword"}}}}}}
Document
文档可以理解为传统的关系型数据库中的每一行的数据。Docuemnt具有新增、修改、删除、查询操作
新增文档可以指定 Id 或者选择其自动生成 id,个人感觉使用自定义 Id更好,方便同原始数据关联。
插入操作
插入的时候,可以选择自己定义 id,也可以交给 ES让其帮助生成 id。
自定义id
PUT /nba/_doc/1{"name": "哈登","team_name": "⽕箭","position": "得分后卫","play_year": "10","jerse_no": "13"}
ES生成id
POST /nba/_doc{"name": "库⾥","team_name": "勇⼠","position": "组织后卫","play_year": "10","jerse_no": "30"}
上述有 2 个区别
- 使用自动生成的 id 是
POST,自己定义 id 是PUT - 自己定义 id 需要给出具体的值
批量插入文档
POST /article/_bulk{ "index": { "_id": 1 }}{ "articleID" : "XHDK-A-1293-#fJ3", "userID" : 1, "hidden": false, "postDate": "2017-01-01" }{ "index": { "_id": 2 }}{ "articleID" : "KDKE-B-9947-#kL5", "userID" : 1, "hidden": false, "postDate": "2017-01-02" }{ "index": { "_id": 3 }}{ "articleID" : "JODL-X-1937-#pV7", "userID" : 2, "hidden": false, "postDate": "2017-01-01" }{ "index": { "_id": 4 }}{ "articleID" : "QQPX-R-3956-#aD8", "userID" : 2, "hidden": true, "postDate": "2017-01-02" }
删除文档
DELETE nba/_doc/3
修改文档
基本的修改
POST /nba/_update/1{"doc":{"name":"哈登2"}}
基于原数值的修改
POST /nba/_update/1{"script": {"source": "ctx._source.age += params.age","params": {"age": 4}}}
新增字段
下面的other就是新增的字段PUT /nba/_mapping{"properties":{"other":{"type":"long"}}}
