In the server load status monitoring, in order to avoid the load spikes caused by the useless alarm problem, I used to take the last 10 times the average load. This requirement was solved directly in Django, but the speed was not ideal after a period of running. The idea now is to have the database load the payload in another field when inserting new data, and then delete the code that calculates the average load for each server in Django, and the load value is changed to read the average directly. Because the database server is currently under a little pressure, the effect of increasing the performance after the trigger is not considered.
Calculate average
PostgreSQL calculates the average of SQL similar to the following:
With S as (select cast (load_15 as float) from Asset_serverstatus where sid_id=10 order by id DESC limit) Select AVG (loa D_15) from S
Trigger function
CREATE OR REPLACE FUNCTION fn_status_loadavg_insert () RETURNS trigger as$body$begin update asset_serverstatus set Load_av G= (with S as (select cast (load_15 as float) from Asset_serverstatus where sid_id=new.sid_id order by id desc limit) se Lect avg (load_15) from S) where Id=new.id;return new; END; $BODY $ LANGUAGE plpgsql VOLATILE cost 100;
Using Pgsql to write a trigger function, the basic idea is actually update.
Add a trigger to a table
CREATE TRIGGER Trg_status_loadavg_insert After insert in asset_serverstatus for each ROW EXECUTE PROCEDURE Fn_status_loada Vg_insert ();
In this way, the implementation of a field is averaged in the PostgreSQL database and then inserted into another field, depending on the condition.
Recorded.
Original address: http://www.sijitao.net/2030.html
PostgreSQL inserts another field to implement an example after averaging a field