elasticsearch mapping 学习

mapping是es中对索引库的字段名及数据类型的定义,同时可以控制字段是否存储、是否分词等。es和我们常用的关系型数据库很相似,mapping就类似于表结构。通常在首次创建索引数据时,会根据数据结构自动地生成mapping结构,无需手动创建。另外可通过api上传json类型的mapping数据手动创建,而这种方式通过使用mapping配置文件则会更加方便。

我们项目中采用的就是通过配置文件。网上创建mapping的资料很多,不再废话。主要记录一下mapping中关于parent-child结构的使用。要创建父子结构的mapping,首先要配置结构,其大致如下:(music下创建了两个type(song, rock),其中song-rock是父子结构)

{    
    "music" : {
        "mappings": {
            "song" : {
                "properties" : {
                  "name" : {
                    "type": "string",
                    "index" : "not_analyzed"
                  },
                  "author" : {
                      "type" : "string"
                  }
                }
            },
            "rock" : {
               "_parent" : {     
                    "type":"song"  
                },
                "properties": {
                  "lyric": {
                    "type": "string"
                  }
                }
            }
        }
    }
}</span>


parent-child结构在child索引的增加,删除时与普通的不同,需要加上parentId参数。例如增加一条rock:
curl -XPOST 'http://localhost:9200/music/rock?parent=3' -d '{"lyric":"哟哟哟,切克闹"}'

 
 
这里的parent=3对应的是song的id为3的数据。如果此时不带parent参数,又会怎么样呢?当然是报错: 

{
  "error": {
    "root_cause": [
      {
        "type": "null_pointer_exception",
        "reason": "id must not be null"
      }
    ],
    "type": "null_pointer_exception",
    "reason": "id must not be null"
  },
  "status": 500
}

一般情况下,创建父子结构的索引都是为了通过child查询到parent,或者相反。那下面就介绍一下通过child索引内容得到parent的方式。在es的查询api中,有has_child与has_parent可以满足parent-child结构的索引数据查询。

curl -XPOST 'http://localhost:9200/music/song/_search' -d '{
    "query" : {
        "has_child" : {
            "type" : "rock",
            "query" : {
                "match" : {
                    "lyric" : "切克闹"
                }
            }
        } 
    }
}'
结果:

{
  "took": 58,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "music",
        "_type": "song",
        "_id": "4",
        "_score": 1,
        "_source": {
          "name": "最炫民族风",
          "author": "凤凰传奇"
        }
      }
    ]
  }
}
而通过parent查找child则相反,只要把has_child替换成has_parent就可以实现。

注意:在es2.0+的版本中,mapping的创建不再支持创建新mapping时把已经存在的当作自己的parent,必须同时创建才行;而es1.0+则没有此限制。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值