文章目录
映射关系
- 映射关系
- 创建文档进行测试
- 对text类型的进行查询
- 对keyword类型的字段进行查询
- 对index为false的字段进行查询
创建一个索引叫 user 请求方式为put 请求url: http://127.0.0.1:9200/user
请求结果:
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "user"
}
对user索引进行mapping映射的处理 : 请求方式为put 请求url: http://127.0.0.1:9200/user/_mapping
注意末尾是_mapping
, 请求体:
{
"properties": {
"name": {
"type": "text", //类型为文本
"index": true // 创建索引, 可以被搜索
},
"sex": {
"type": "keyword", //类型为关键词, 不会被分词
"index": true // 创建索引, 可以被搜索
},
"tel": {
"type": "keyword",
"index": false // 不创建索引, 不可以被搜索
}
}
}
对user索引建立三个字段进行映射, 含义已经在注释中. 执行的结果如下:
{
"acknowledged": true
}
代表创建成功. 执行get请求, 对mapping进行查询 url : http://127.0.0.1:9200/user/_mapping
返回结果如下
{
"user": {
"mappings": {
"properties": {
"name": {
"type": "text"
},
"sex": {
"type": "keyword"
},
"tel": {
"type": "keyword",
"index": false
}
}
}
}
}
创建文档进行测试
请求方式put 请求url: http://127.0.0.1:9200/user/_create/1001
请求体:
{
"name": "华为",
"sex": "男性",
"tel": "111"
}
请求结果 :
{
"_index": "user",
"_type": "_doc",
"_id": "1001",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 0,
"_primary_term": 1
}
对text类型的进行查询
对name字段进行查询 请求方式get 请求url : http://127.0.0.1:9200/user/_search
请求体:
{
"query":{
"match":{
"name": "华"
}
}
}
结果如下
{
"took": 403,
"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": "111"
}
}
]
}
}
成功查询到了 数据.
对keyword类型的字段进行查询请求体如下
{
"query":{
"match":{
"sex": "男"
}
}
}
结果如下 :
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
}
}
可以看到没有查询到数据, 原因是因为sex 类型为keyword类型, 是关键字, 不能被分词. 只能全匹配查询 搜索男性 , 则可以搜索出来.
对’tel’字段进行查询 , 该字段在mapping的时候, index设置为false, 代表不建立索引, 不能被查询.
{
"query":{
"match":{
"tel": "111"
}
}
}
结果如下, 报错说无法创建查询, 因为tel字段没有创建索引.
{
"error": {
"root_cause": [
{
"type": "query_shard_exception",
"reason": "failed to create query: Cannot search on field [tel] since it is not indexed.",
"index_uuid": "TcWoHdNRQ-mDNuDsolJySQ",
"index": "user"
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "user",
"node": "IOWrA3RrS5S-pnDHDXQ9QQ",
"reason": {
"type": "query_shard_exception",
"reason": "failed to create query: Cannot search on field [tel] since it is not indexed.",
"index_uuid": "TcWoHdNRQ-mDNuDsolJySQ",
"index": "user",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Cannot search on field [tel] since it is not indexed."
}
}
}
]
},
"status": 400
}
黑发不知勤学早,白首方悔读书迟。