1.3 修改
1.3.1 全局修改
在Postman中发起PUT
请求:http://127.0.0.1:9200/index_name/_doc/id
例子:
修改内容:
{ "title": "华为手机", "category": "HuaWei", "images": "http://xxx.com/xm.jpg", "price": 4000.00 }
响应:
{ "_index": "shopping", "_type": "_doc", "_id": "1001", "_version": 4, "result": "updated", // 修改 "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 4, "_primary_term": 2 }
1.3.2 局部修改
不可以使用PUT请求,要使用POST请求。
在Postman中发起POST
请求:http://127.0.0.1:9200/index_name/_update/id
例子:
请求体内容:
{ "doc":{ "price":5000.00 } }
响应:
{ "_index": "shopping", "_type": "_doc", "_id": "1001", "_version": 5, "result": "updated", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 5, "_primary_term": 2 }
1.4 删除
在Postman中发起DELETE
请求:http://127.0.0.1:9200/index_name/_update/id
例子:
响应:
{ "_index": "shopping", "_type": "_doc", "_id": "1001", "_version": 6, "result": "deleted", // 删除成功 "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 6, "_primary_term": 2 }
如果删除一个不存在的文档:
{ "_index": "shopping", "_type": "_doc", "_id": "1001", "_version": 1, "result": "not_found", // 未找到 "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 7, "_primary_term": 2 }
3. 映射关系mapping
创建一个user索引
设置index映射信息:
请求体:
{ "properties":{ "name":{// 字段名称 "type":"text", // 字段类型。text:文本,可以分词 "index":true // index:true 表示这个字段可以通过索引查询。 }, "sex":{ "type":"keyword", // keyword 表示不可以分词,必须完整匹配 "index":true }, "tel":{ "type":"keyword", "index":false // 不可被索引,即不可被查询 } } }
获取index映射信息:
响应:
{ "user": { "mappings": { "properties": { "name": { "type": "text" }, "sex": { "type": "keyword" }, "tel": { "type": "keyword", "index": false } } } } }
验证映射信息:
在user中创建一个文档
请求体:
{ "name": "小米", "sex": "男的", "tel": "1111" }
查询该文档
根据name查询:
请求体:
{ "query":{ "match":{ "name":"小" // 因为name为text类型,是支持分词,也就是全文检索的 } } }
响应:
{ "took": 606, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 0.2876821, "hits": [ { "_index": "user", "_type": "_doc", "_id": "1001", "_score": 0.2876821, "_source": { "name": "小米", "sex": "男的", "tel": "1111" } } ] } }
根据sex查询:
请求体:
{ "query":{ "match":{ "sex":"男" // sex类型为keyword,只支持完全查询,不支持全文检索 } } }
响应:
{ "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 0, "relation": "eq" }, "max_score": null, "hits": [] } }
根据tel查询:
请求体:
{ "query":{ "match":{ "tel":"1111" // tel的index:false 不可被查询 所以会报错 } } }
会报错:
"reason": "failed to create query: Cannot search on field [tel] since it is not indexed.", // "reason": "创建查询失败:无法在[tel]字段上搜索,因为它没有被索引",