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>
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+则没有此限制。