Preserve value history/statistics on entity change


I have already found a few solutions to my problem by searching around and googling, but none of them seems to be really promising, or works for one but not for the other.

Currently I receive the values of my electricity meter (IR reading head) as JSON via RESTful. However, I would like to receive this via MQTT in the future for standardisation. This is also not the problem, as I can receive them via MQTT.

What I don’t want, of course, is that, by switching, my entire value history/statistics are gone afterwards.

The approaches I have found are simplified, either it is enough to change the entity ID or it must be adjusted directly in the database via SQL command. All approaches assume that the affected entities have been created by installed integrations.
However, this is not the case with me, I have created both manually in the configuration.yaml.

Any ideas?

It’s my understanding that if the new entity has the same entity_id and unique_id as the old entity, then there will be no loss of history. EDIT see below

Renaming the entity to match worked before April, but since 2023.4 (I think), HA stores data under a metadata_id which does not change. You can see this in the example for the SQL Sensor. Compare this to before the change where retrieving history was purely based on entity_id.

Therefore you can change an entity_id and it will keep the history. However, a new entity will get a new metadata_id and there is currently no way of pointing the history of one entity to another, without manually tinkering with the database.

However, I don’t know how HA decides an entity is new. If you remove the RESTful entity and restart and then create the MQTT one with the same name and entity_id, you might get lucky and have HA think it’s still the old one. I don’t like your chances though.

I will have the opportunity to experiment with this in the near future. I currently have a sensor whose underlying integration I want to replace with another one, without losing its history.

I’m beginning to believe that there’s no way to create a new entity without Home Assistant automatically assigning it a new metadata_id. However the new entity must use the old entity’s metadata_id in order to inherit its history. Therefore you may very well be right about the need for “manually tinkering with the database”.

Hmm, then I can’t avoid intervening in the database. I’ll check this with a few non-critical entities to see if it’s enough to reconfigure the corresponding metadata_id.