Elasticsearch 数据是以 JSON 格式存储的,而JSON中是并没有 date 数据类型,因此 Elasticsearch 中虽然有 date 类型,但在展示时却要转化成另外的格式。
date 类型在 Elasticsearch 展示的格式有下面几种:
1970-01-01 00:00:00 UTC
以来经过的毫秒数。1970-01-01 00:00:00 UTC
以来经过的秒数。不论 date 是什么展示格式,在 Elasticsearch 内部存储时都是转换成 UTC,并且把时区也会计算进去,从而得到 milliseconds-since-the-epoch 并作为存储的格式:
上一节,我们创建了/reviews
索引,并添加了create_at
字段。我们将使用它来做Date类型的测试, 往里面插入三条记录:
PUT /reviews/_doc/2
{
"rating": 4.5,
"content": "Not so bad a movie!",
"product_id": 123,
"create_at":"2022-03-27",
"author": {
"first_name": "John",
"last_name": "Doe",
"email": "johndoe@gmail.com"
}
}
PUT /reviews/_doc/3
{
"rating": 4.5,
"content": "Not so bad a movie!",
"product_id": 123,
"create_at":"2022-03-27T13:04:05Z",
"author": {
"first_name": "John",
"last_name": "Doe",
"email": "johndoe@gmail.com"
}
}
PUT /reviews/_doc/4
{
"rating": 4.5,
"content": "Not so bad a movie!",
"product_id": 123,
"create_at": 1657985321000,
"author": {
"first_name": "John",
"last_name": "Doe",
"email": "johndoe@gmail.com"
}
}
执行后,每种形式的Date都可成功插入。查询插入的数据: