元字段是ES为每个文档配置的内置字段, 主要用于ES内部相关操作.
1 标识元字段
1.1 _index - 文档所属的索引
_index
标注document属于哪个index, 是一个虚拟字段, 不会被添加到Lucene索引中.
将类似的文档 (也就是具有相同field的文档) 存放到同一个index中, 是一种良好的数据建模思想.
提供大量查询的index, 最好不要同时提供大量的统计、聚合等操作——通过把特定的index路由到指定的shard上, 便于系统的优化.
注意: 索引名称必须是小写的字母, 不能以下划线"_"开头, 不能包含逗号 ",".
在term或者terms查询, 聚合、脚本以及排序时, 可以访问_index
字段的值.
在多个索引中执行查询时, 可以通过添加查询子句来关联特定的索引文档, 使用示例——同时查询多种index:
GET website,book_shop/_search
{
"query": {
"terms": { // 查询_index是website和book_shop的文档
"_index": [ "website", "book_shop"] }
},
"aggs": {
"indices": { // 对_index字段进行聚合操作
"terms": { "field": "_index", "size": 10 }
}
},
"sort": { // 对_index字段进行排序操作
"_index": { "order": "asc" }
},
"script_fields": { // 使用脚本, 显示_index字段
"index_name": {
"script": {
"lang": "painless",
"source": "doc['_index']"
}
}
}
}
1.2 _uid - 包含_type和_id的复合字段
_uid
是_type
和_id
的组合, 形式为{type}#{id}
. 可以用于查询、聚合、脚本和排序.
(1) 添加文档:
PUT website/blog/4
{
"text": "blog with ID 4"
}
PUT website/blog/5?refresh=true
{
"text": "blog with ID 5"
}
(2) 检索文档:
说明: 对
_uid
字段的访问API已经过期, 需要使用_id
替换.#! Deprecation: Fielddata access on the _uid field is deprecated, use _id instead
GET website/_search
{
"query": {
"terms": { // 通过_uid查询_type和_id的复合字段
"_uid": ["blog#4", "blog#5"]
}
},
"aggs": {
"uid_aggs": {
"terms": { // 这里通过_uid聚合的操作已经过期
"field": "_id", "size": 10
}
}
},
"sort": { // 这里通过_uid排序的操作已经过期
"_id": { "order": "desc"}
},
"script_fields": {
"uid_script": {
"script": { // 这里对_uid的脚本操作已经过期
"lang": "painless",
"source": "doc['_id']"
}
}
}
}
1.3 _type - 文档的类型
_type
元字段用来标注document属于哪个类型, 也被称作映射类型.
注意: type的名称可以是大写或小写字母, 但不能以下划线"_"开头, 不能包含逗号",".
在Elasticsearch 6.0之前的版本中, 一个index可能会被划分为多个type, 例如: 商品中有电子商品, 服装商品, 生鲜商品...
但在Elasticsearch 6.0之后, 一个index只能包含一个type, 否则将出现错误.
每一个索引文档都包含_type
和_id
字段, _type
字段的目的是通过类型名加快搜索速度.
_type
字段可以在查询、聚合、排序以及脚本中访问到.
关于type的底层数据结构, 可参见ES XX - Elasticsearch对索引类型(_type)的处理方式.
1.4 _id - 文档的id
_id
代表document的唯一标识, 与_index
和_type
一起, 唯一标识和定位一个document.
注意: 可以手动指定document的id(
PUT index/type/id
), 也可以不指定, Elasticsearch在添加文档时会自动为其创建id.
可以在查询、脚本中访问, 查询示例:
GET website/_search
{
"query": {
"terms": {"_id" : ["1", "2"]}
},
"aggs": {
"id_aggs": {
"terms": {
"field": "_id", "size": 10
}
}
},
"script_fields": {
"id_script": {
"script&qu