Index和Mapping介绍
自动Elasticsearch 7.0版本开始一个Index对应一个type,所以一个index也就类似关系数据库中的一张表,mapping则相当于定义数据表的每一个字段,与关系数据库不同的是,index创建完成后不予许被修改,mapping也同样如此,如果需要修改结构则需要先删除,然后重新创建。
操作辅助工具
本章节是借助Apipost工具通过发送请求直接操作Elasticsearch,大家也可以使用例如Postman等http请求工具,操作过程中需关注请求方式、Json报文、返回报文
创建Index
创建索引需要使用PUT请求,http://127.0.0.1:9200/{indexName} indexName是索引名称,索引名称根据实际要求定义即可,填写完成后直接发送请求,当返回报文中出现 acknowledged字段为trues时,即代表索引创建成功,请求案例如下:
请求方式 | PUT |
请求路径 | http://127.0.0.1:9200/user |
请求报文 | 无 |
返回报文 | { "acknowledged": true, "shards_acknowledged": true, "index": "user" } |
查询Index
索引创建完成后可以通过GET请求完成索引信息查询,http://127.0.0.1:9200/{indexName} indexName填写之前创建的索引名称,然后发送请求,查询成功后会在返回报文中出现索引相关信息:
请求方式 | GET |
请求路径 | http://127.0.0.1:9200/{indexName} |
请求报文 | 无 |
返回报文 | { "user": { "aliases": {}, "mappings": {}, "settings": { "index": { "routing": { "allocation": { "include": { "_tier_preference": "data_content" } } }, "number_of_shards": "1", "provided_name": "user", "creation_date": "1653528462294", "number_of_replicas": "1", "uuid": "PdixjG4-R_qD4x01i7egAQ", "version": { "created": "7170499" } } } } } |
查询所有index
我们也可以通过GET请求访问固定的URL【http://127.0.0.1:9200/_cat/indices?v】来查询当前Elasticsearch中所有的索引,返回报文中index列即为索引名称,health代表Elasticsearch的健康状态,正常因为green,我这里是因为开启了集群,但实际又是单机运行导致健康状态为yellow。
请求方式 | GET |
请求路径 | http://127.0.0.1:9200/_cat/indices?v |
请求报文 | 无 |
返回报文 | ![]() |
删除index
因为Elasticsearch中的index和mapping创建成功后都是不允许被修改的,所以后期使用中发现设计不足时,则需要先删除原有的索引再重新创建,删除索引使用DELETE请求方式,请求路径和创建、查询索引一样,只是请求方式不同。
请求方式 | DELETE |
请求路径 | http://127.0.0.1:9200/_cat/indices?v |
请求报文 | 无 |
返回报文 | { "acknowledged": true } |
创建mapping
Elasticsearch中的mapping相当于关系数据库中的表字段配置,mapping配置中包括字段名称、类型、是否可被索引(是否可作为查询条件)等信息。创建映射需要使用PUT请求方式,请求路径为http://127.0.0.1:9200/{indexName}/_mapping ,indexName为索引名称,表明当前映射是针对哪个索引配置的。
请求方式 | PUT |
请求路径 | http://127.0.0.1:9200/user/_mapping |
请求报文 | { "properties":{ "userId":{ "type":"keyword", "index":true }, "username":{ "type":"text",//类型text:可以分词查询 "index":true }, "sex":{ "type":"keyword",//类型keyword:值是一个整体,查询时必须完整匹配 "index":false//是否索引,不是索引则不能用来做查询条件 }, "age":{ "type":"integer", "index":true } } } |
返回报文 | { "acknowledged": true } |
查询mapping
我们也可以通过GET请求访问http://127.0.0.1:9200/{indexName}/_mapping来查看对应索引的映射。
请求方式 | GET |
请求路径 | http://127.0.0.1:9200/{indexName}/_mapping |
请求报文 | 无 |
返回报文 | { "user": { "mappings": { "properties": { "_class": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "age": { "type": "long" }, "sex": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "userId": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "username": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } } } } |