三、映射操作
映射类似于数据库(database)中的表结构(table)。创建数据库表需要设置字段名称,类型,长度,约束等;索引库也一样,需要知道这个类型下有哪些字段,每个字段有哪些约束信息,这就叫做映射(mapping)。
{
"properties":{
"name":{ //属性 :姓名
"type":"text", //类型为text 可以分词
"index":true //可以被索引
},
"sex":{
"type": "keyword", //表示不能被分词 需要完整匹配
"index": true
},
"age":{
"type": "keyword",
"index": false
}
}
}
1) 创建映射
在 Postman中,向ES服务器发PUT请求 :http://127.0.0.1:9200/user/_mapping
{
"properties":{
"name":{
"type":"text",
"index":true
},
"sex":{
"type": "keyword",
"index": true
},
"age":{
"type": "keyword",
"index": false
}
}
}
2) 查看索引
在 Postman中,向ES服务器发get请求 :http://127.0.0.1:9200/user/_mapping
//响应结果
{
"user": {
"mappings": {
"properties": {
"age": {
"type": "keyword",
"index": false
},
"name": {
"type": "text"
},
"sex": {
"type": "keyword"
}
}
}
}
}
3)放入部分文档数据
1. put 方式 create http://127.0.0.1:9200/user/_create/1
{
"name":"华为手机",
"sex":"女",
"age":"12"
}
2.put 方式 doc http://127.0.0.1:9200/user/_doc/2
{
"name":"小米",
"sex":"男",
"age":"18"
}
3.先用 http://127.0.0.1:9200/user/_search 查看文档数据
{
"took": 1197,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "user",
"_type": "_doc",
"_id": "1",
"_score": 1,
"_source": {
"name": "华为手机",
"sex": "女",
"age": "12"
}
},
{
"_index": "user",
"_type": "_doc",
"_id": "2",
"_score": 1,
"_source": {
"name": "小米",
"sex": "男",
"age": "18"
}
}
]
}
}
4)在body中
{
"query":{
"match":{
"age":"18"
}
}
}
//响应结果 age 在映射中是不能被索引的,无法查看
{
"error": {
"root_cause": [
{
"type": "query_shard_exception",
"reason": "failed to create query: Cannot search on field [age] since it is not indexed.",
"index_uuid": "ax4BLR7hQx2OFEPmn11rHw",
"index": "user"
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "user",
"node": "3FhxLS28TNqD0cRRYLH80g",
"reason": {
"type": "query_shard_exception",
"reason": "failed to create query: Cannot search on field [age] since it is not indexed.",
"index_uuid": "ax4BLR7hQx2OFEPmn11rHw",
"index": "user",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Cannot search on field [age] since it is not indexed."
}
}
}
]
},
"status": 400
}