如果未在映射中启用,elasticsearch 不会在字段中 return ttl

elasticsearch not return ttl in fields if not enabled in mappings

我在 中创建了 indexdoc。为文档添加映射。

curl http://localhost:9200/test -X POST
{"acknowledged":true}

curl http://localhost:9200/test/student_doc/_mappings -X PUT -d '{
   "student_doc" : {
     "properties" : {
       "name" : {
         "properties" : {
           "student_id" : {
             "type" : "string"
           },
           "tags": {
             "type" : "string"
           }
         }
       }
     }
   }
 }'
{"acknowledged":true}

当我创建文档时,我为文档提供了 ttl

curl http://localhost:9200/test/student_doc/4?ttl=2500 -X PUT -d '{"student_id": "4", "tags": ["test"]}' -H 'Content-type: application/json'
{"_index":"test","_type":"student_doc","_id":"4","_version":1,"created":true}'

当我尝试在 fields

中获取 ttl
curl http://localhost:9200/test/_search?pretty -X POST -d '{"fields": ["_ttl"]}'
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "test",
      "_type" : "student_doc",
      "_id" : "4",
      "_score" : 1.0
    } ]
  }
}

我使用新映射在索引中启用 ttl

curl http://localhost:9200/test/student_doc/_mappings -X PUT -d '{
  "student_doc" : {
    "_ttl": {"enabled": true},
    "properties" : {
      "name" : {
        "properties" : {
          "student_id" : {
            "type" : "string"
          },
          "tags": {
            "type" : "string"
          }
        }
      }
    }
  }
}'

然后添加新记录。

curl "http://localhost:9200/test/student_doc/5?ttl=2500&pretty" -X PUT -d '{"student_id": "5", "tags": ["test"]}' -H 'Content-type: application/json'
{
  "_index" : "test",
  "_type" : "student_doc",
  "_id" : "5",
  "_version" : 1,
  "created" : true
}

并尝试再次获取 ttl,它 returns 字段中的 ttl

curl http://localhost:9200/test/_search?pretty -X POST -d '{"fields": ["_ttl"]}'
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 2,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "test",
      "_type" : "student_doc",
      "_id" : "4",
      "_score" : 1.0
    }, {
      "_index" : "test",
      "_type" : "student_doc",
      "_id" : "5",
      "_score" : 1.0,
      "fields" : {
        "_ttl" : -420
      }
    } ]
  }
}

必须在映射中启用 ttl 才能在文档中生效?

是的,_ttl 默认情况下未启用,因此您需要启用它才能使 TTL 工作,但它不会影响已创建的文档。

请注意,如果未在您的映射中启用 _ttl,则 ttl 参数将被静默忽略,您不会因此收到任何错误。了解映射以及是否启用 TTL 是您工作的一部分。

您可以随时启用 _ttl,因此鉴于支持它的工作量增加,您应该只在需要时启用它。