PUT _ilm/policy/policy_cktest_sc_system_log
{
  "policy": {
    "phases": {
      "delete": {
        "min_age": "7d",
        "actions": {
          "delete": {}
        }
      }
    }
  }
}

elasticsearch索引按日期拆分-LMLPHP

创建索引模板

创建索引模板,索引模板主要是用来创建索引默认属性


PUT _template/sc_all_system_log
{
    "order":0,
    "index_patterns":[
        // 创建索引时,索引名称以这个为前缀时,默认使用此模板
        "sc_all_system_log*"
    ],
    "settings":{
        "index":{
			"refresh_interval": "10s",
            "number_of_shards":"5",
            "number_of_replicas":"1",
			"lifecycle":{
				// 前面创建的索引定时清理策略,创建的索引会使用此清理策略
				"name":"policy_cktest_sc_system_log"
			}
        }
    },
    "mappings":{
        "_doc":{
            "properties":{
                "version":{
					"type":"keyword",
					"index":"false"
                },
				"timestamp":{
					"type" : "date",
					"format" : "8uuuu-MM-dd HH:mm:ss.SSS"
                },
				"message":{
					"type":"text",
					"analyzer":"ik_smart",
					"search_analyzer":"ik_smart"
                },
				"level":{
					"type":"keyword"
                },
				"namespace":{
					"type":"keyword"
                },
				"appName":{
					"type":"keyword"
                },
				"traceId":{
					"type":"keyword"
                },
				"spanId":{
					"type":"keyword"
                },
				"ip":{
					"type":"keyword"
                },
				"tags":{
					"type":"object"
                }
            }
        }
    },
    "aliases":{
    	// 创建索引时指定的别名,很重要
        "sc_all_system_log":{}
    }
}

插入数据自动创建索引

这里我们指定的索引名称sc_all_system_log20220903,无此索引时会自动创建索引,创建索引时发现是以sc_all_system_log为前缀会默认使用上面的模板创建。所以索引sc_all_system_log20220903指向的别名是sc_all_system_log

// 2022.09.03插入一条记录,创建sc_all_system_log20220903索引
POST /sc_all_system_log20220903/_doc
{
  "version":"1",
  "timestamp":"2022-09-03 17:50:00.000",
  "message":"程序异常请联系管理员处理",
  "level":"info",
  "namespace":"sc-test",
  "appName":"sc-test",
  "traceId":"123456789",
  "spanId":"123456789",
  "ip":"127.0.0.1",
  "tags":{
    "key1":"value1",
    "key2":"value2",
    "key3":"value3"
  }
}
// 2022.09.04插入一条记录,创建sc_all_system_log20220904索引
POST /sc_all_system_log20220904/_doc
{
  "version":"1",
  "timestamp":"2022-09-03 17:50:00.000",
  "message":"程序异常请联系管理员处理,测试4",
  "level":"info",
  "namespace":"sc-test",
  "appName":"sc-test",
  "traceId":"123456789",
  "spanId":"123456789",
  "ip":"127.0.0.1",
  "tags":{
    "key1":"value1",
    "key2":"value2",
    "key3":"value3"
  }
}

搜索时,我们只需要指向别名(sc_all_system_log)搜索即可,如下图
elasticsearch索引按日期拆分-LMLPHP

11-04 09:34