创建索引
1)语法
1 |
PUT /<index> |
2)示例
1 2 3 |
PUT /index curl -XPUT 'http://10.0.0.71:9200/index' |
创建数据
1)数据结构
构成 | 说明 |
---|---|
_index | 索引(数据存储的地方) |
_type | 类型(数据对应类) |
_id | 数据的唯一标识 |
2)语法
1 2 3 4 5 6 7 8 9 |
PUT /<index>/_doc/<_id> POST /<index>/_doc/ PUT /<index>/_create/<_id> POST /<index>/_create/<_id> index:索引的名称,如果索引不存在,会自动创建 _doc:类型 _id:唯一标识,可以手动指定,也可以自动生成 |
3)使用自定义ID插入数据
1 2 3 4 5 6 7 8 9 10 |
PUT /index/_doc/1 { "name":"qiudao", "age":"18" } #该方式企业应用较少 1.需要修改id的值 2.指定ID插入数据时,ES会先拿着指定的id去对比一遍所有数据,看看有没有相同值 |
4)使用随机ID插入数据
1 2 3 4 5 6 |
POST /index/_doc/ { "name":"qiudao", "age":"20" } |
5)添加字段指定ID
1 2 3 4 5 6 |
POST /index/_doc/ { "id":"1", "name":"qiudao", "age":"20" } |
查询数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#查询所有索引的信息 GET /_all GET _all #查看所有索引的数据 GET /_all/_search #查看指定索引的信息 GET /teacher #查看指定索引的数据 GET /teacher/_search #查看索引中指定的数据 GET /teacher/user/2 GET /teacher/user/1m-gGHYB5ia7o7wd9dPk |
2)单条件查询
方法一:
1 2 3 4 5 6 7 8 9 10 11 |
GET /teacher/_search { "query": { "term": { "age": { "value": "18" } } } } |
方法二:
1 2 3 4 5 6 7 8 9 |
GET /teacher/_search { "query": { "term": { "age": "18" } } } |
方法三:
1 2 3 4 5 6 7 8 9 10 11 |
GET /teacher/_search { "query": { "match": { "age": "18" } } } 指定条件可以使用term也可以使用match,term搜索数据时不进行分词,适合进行精确查找,match搜索时进行分词适用于全文检索 |
3)多条件查询
must查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#多个查询条件必须全部满足 & GET /teacher/_search { "query": { "bool": { "must": [ { "term": { "age": { "value": "18" } } }, { "term": { "sex": { "value": "nv" } } } ] } } } |
filter查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#跟must作用一样,但是速度要比must快一点 GET /teacher/_search { "query": { "bool": { "filter": [ { "term": { "age":"18" } }, { "term": { "sex":"nv" } } ] } } } |
should查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#多条件查询时,符合其中一个条件就可以 | GET /teacher/_search { "query": { "bool": { "should": [ { "term": { "age": { "value": "18" } } }, { "term": { "id": { "value": "5" } } } ] } } } |
4)must_not
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
GET /teacher/_search { "query": { "bool": { "must_not": [ { "term": { "age": { "value": "18" } } }, { "term": { "id": { "value": "5" } } } ] } } } |
5)must和should结合使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#查询年龄是21或者年龄是18岁并且名字是lizhenglin的数据 GET /teacher/_search { "query": { "bool": { "should": [ { "term": { "age": { "value": "21" } } }, { "bool": { "must": [ { "term": { "age": { "value": "18" } } }, { "term": { "name": { "value": "lizhenglin" } } } ] } } ] } } } |
修改数据
1 2 3 4 5 6 7 8 9 |
#修改数据通过_id进行修改,修改数据是,除了要修改的字段意外,其他的字段也要全部写上 PUT /teacher/user/9G-FHXYB5ia7o7wdEdOH { "id":"6", "name":"wananfeng", "sex":"nan", "age":"25" } |
删除数据
1 2 3 4 5 |
#删除指定数据,通过_id进行选择删除 DELETE /teacher/user/9G-FHXYB5ia7o7wdEdOH #删除索引 DELETE /teacher |