backend: Improve sql query performances #323
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Improve ignore fake instance condition
Performance improvement in Simple queries.
select * from instance where instance.id SIMILAR TO '\{[a-fA-F0-9-]{36}\}';
select * from instance where id LIKE '{________-____-____-____-____________}'
Performance improvement in Complex queries.
SELECT a.name AS app_name, count(*) as fail_count FROM application a, event e, event_type et WHERE a.team_id = 'd89342dc-9214-441d-a4af-bdd837a3b239' AND a.id = e.application_id AND e.event_type_id = et.id AND et.result = 0 AND et.type = 3 AND (e.instance_id IS NULL OR e.instance_id NOT SIMILAR TO '\{[a-fA-F0-9-]{36}\}') GROUP BY app_name ORDER BY app_name;
Overall time: 499ms
SELECT a.name AS app_name, count(*) as fail_count FROM application a, event e, event_type et WHERE a.team_id = 'd89342dc-9214-441d-a4af-bdd837a3b239' AND a.id = e.application_id AND e.event_type_id = et.id AND et.result = 0 AND et.type = 3 AND (e.instance_id IS NULL OR e.instance_id NOT LIKE '{________-____-____-____-____________}') GROUP BY app_name ORDER BY app_name;
Overall time: 224ms
Add composite index for stats query on instance_application table
query:
SELECT COUNT (*) FROM "instance_application" WHERE (("application_id" = 'e96281a6-d1af-4bde-9a0a-97b76e56dc57') AND ("group_id" = '9a2deb70-37be-4026-853f-bfdd6b347bbe') AND last_check_for_updates > now() at time zone 'utc' - interval '1days' AND (instance_id IS NULL OR instance_id NOT SIMILAR TO '\{[a-fA-F0-9-]{36}\}'))
index:
create index concurrently if not exists instance_application_application_id_group_id_last_check_for_idx on instance_application(application_id,group_id,last_check_for_updates,instance_id);
Before:
After:
Drop unused indexes.
There are few indexes that are not used, they can affect the insert performance.
![image](https://user-images.githubusercontent.com/22731013/105222761-ef14ee80-5b80-11eb-8f11-eeb2d1d9106d.png)
Refer: