Setzt Postgres automatisch Indizes auf Foreign Keys und Primary Keys? Wie kann ich das feststellen? Gibt es einen Befehl, der alle Indizes für eine Tabelle zurückgibt?
Antworten
Zu viele Anzeigen?Diese Funktion, die sich auf die Arbeit von Laurenz Albe bei https://www.cybertec-postgresql.com/en/index-your-foreign-key/ alle Fremdschlüssel mit fehlenden Indizes auflisten. Die Größe der Tabelle wird angezeigt, da bei kleinen Tabellen die Scan-Leistung der Index-Leistung überlegen sein könnte.
--
-- function: fkeys_missing_indexes
-- purpose: list all foreing keys in the database without and index in the source table.
-- author: Laurenz Albe
-- see: https://www.cybertec-postgresql.com/en/index-your-foreign-key/
--
create or replace function fkeys_missing_indexes ()
returns table (
src_table regclass,
fk_columns varchar,
table_size varchar,
fk_constraint name,
dst_table regclass
)
as $$
select
-- source table having ta foreign key declaration
tc.conrelid::regclass as src_table,
-- ordered list of foreign key columns
string_agg(ta.attname, ',' order by tx.n) as fk_columns,
-- source table size
pg_catalog.pg_size_pretty (
pg_catalog.pg_relation_size(tc.conrelid)
) as table_size,
-- name of the foreign key constraint
tc.conname as fk_constraint,
-- name of the target or destination table
tc.confrelid::regclass as dst_table
from pg_catalog.pg_constraint tc
-- enumerated key column numbers per foreign key
cross join lateral unnest(tc.conkey) with ordinality as tx(attnum, n)
-- name for each key column
join pg_catalog.pg_attribute ta on ta.attnum = tx.attnum and ta.attrelid = tc.conrelid
where not exists (
-- is there ta matching index for the constraint?
select 1 from pg_catalog.pg_index i
where
i.indrelid = tc.conrelid and
-- the first index columns must be the same as the key columns, but order doesn't matter
(i.indkey::smallint[])[0:cardinality(tc.conkey)-1] @> tc.conkey) and
tc.contype = 'f'
group by
tc.conrelid,
tc.conname,
tc.confrelid
order by
pg_catalog.pg_relation_size(tc.conrelid) desc;
$$ language sql;
Testen Sie es auf diese Weise,
select * from fkeys_missing_indexes();
werden Sie eine Liste wie diese sehen.
fk_columns |table_size|fk_constraint |dst_table |
----------------------|----------|----------------------------------|-----------------|
id_group |0 bytes |fk_customer__group |im_group |
id_product |0 bytes |fk_cart_item__product |im_store_product |
id_tax |0 bytes |fk_order_tax_resume__tax |im_tax |
id_product |0 bytes |fk_order_item__product |im_store_product |
id_tax |0 bytes |fk_invoice_tax_resume__tax |im_tax |
id_product |0 bytes |fk_invoice_item__product |im_store_product |
id_article,locale_code|0 bytes |im_article_comment_id_article_fkey|im_article_locale|
Für eine PRIMARY KEY
wird ein Index mit der folgenden Meldung erstellt:
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "index" for table "table"
Für eine FOREIGN KEY
wird die Einschränkung nicht erstellt, wenn es keinen Index für den Verweis gibt. ed Tisch.
Ein Index zum Thema Referenc ing Tabelle ist nicht erforderlich (obwohl erwünscht) und wird daher nicht implizit erstellt.
Und hier ist ein Bash-Skript, das die SQL generiert, um Indizes für fehlende Indizes für Fremdschlüssel zu erstellen, indem es die SQL von @sergeyB verwendet.
#!/bin/bash
read -r -d '' SQL <<EOM
WITH fk_actions ( code, action ) AS (
VALUES ( 'a', 'error' ),
( 'r', 'restrict' ),
( 'c', 'cascade' ),
( 'n', 'set null' ),
( 'd', 'set default' )
),
fk_list AS (
SELECT pg_constraint.oid as fkoid, conrelid, confrelid as parentid,
conname, relname, nspname,
fk_actions_update.action as update_action,
fk_actions_delete.action as delete_action,
conkey as key_cols
FROM pg_constraint
JOIN pg_class ON conrelid = pg_class.oid
JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
JOIN fk_actions AS fk_actions_update ON confupdtype = fk_actions_update.code
JOIN fk_actions AS fk_actions_delete ON confdeltype = fk_actions_delete.code
WHERE contype = 'f'
),
fk_attributes AS (
SELECT fkoid, conrelid, attname, attnum
FROM fk_list
JOIN pg_attribute
ON conrelid = attrelid
AND attnum = ANY( key_cols )
ORDER BY fkoid, attnum
),
fk_cols_list AS (
SELECT fkoid, array_to_string(array_agg(attname), ':') as cols_list
FROM fk_attributes
GROUP BY fkoid
),
index_list AS (
SELECT indexrelid as indexid,
pg_class.relname as indexname,
indrelid,
indkey,
indpred is not null as has_predicate,
pg_get_indexdef(indexrelid) as indexdef
FROM pg_index
JOIN pg_class ON indexrelid = pg_class.oid
WHERE indisvalid
),
fk_index_match AS (
SELECT fk_list.*,
indexid,
indexname,
indkey::int[] as indexatts,
has_predicate,
indexdef,
array_length(key_cols, 1) as fk_colcount,
array_length(indkey,1) as index_colcount,
round(pg_relation_size(conrelid)/(1024^2)::numeric) as table_mb,
cols_list
FROM fk_list
JOIN fk_cols_list USING (fkoid)
LEFT OUTER JOIN index_list
ON conrelid = indrelid
AND (indkey::int2[])[0:(array_length(key_cols,1) -1)] @> key_cols
),
fk_perfect_match AS (
SELECT fkoid
FROM fk_index_match
WHERE (index_colcount - 1) <= fk_colcount
AND NOT has_predicate
AND indexdef LIKE '%USING btree%'
),
fk_index_check AS (
SELECT 'no index' as issue, *, 1 as issue_sort
FROM fk_index_match
WHERE indexid IS NULL
UNION ALL
SELECT 'questionable index' as issue, *, 2
FROM fk_index_match
WHERE indexid IS NOT NULL
AND fkoid NOT IN (
SELECT fkoid
FROM fk_perfect_match)
),
parent_table_stats AS (
SELECT fkoid, tabstats.relname as parent_name,
(n_tup_ins + n_tup_upd + n_tup_del + n_tup_hot_upd) as parent_writes,
round(pg_relation_size(parentid)/(1024^2)::numeric) as parent_mb
FROM pg_stat_user_tables AS tabstats
JOIN fk_list
ON relid = parentid
),
fk_table_stats AS (
SELECT fkoid,
(n_tup_ins + n_tup_upd + n_tup_del + n_tup_hot_upd) as writes,
seq_scan as table_scans
FROM pg_stat_user_tables AS tabstats
JOIN fk_list
ON relid = conrelid
)
SELECT relname as table_name,
cols_list
FROM fk_index_check
JOIN parent_table_stats USING (fkoid)
JOIN fk_table_stats USING (fkoid)
ORDER BY issue_sort, table_mb DESC, table_name;
EOM
DB_NAME="dbname"
DB_USER="dbuser"
DB_PASSWORD="dbpass"
DB_HOSTNAME="hostname"
DB_PORT=5432
export PGPASSWORD="$DB_PASSWORD"
psql -h $DB_HOSTNAME -p $DB_PORT -U $DB_USER -d $DB_NAME -t -A -F"," -c "$SQL" | while read -r line; do
IFS=','
parts=($line)
unset IFS
tableName=${parts[0]}
colsList=${parts[1]}
indexName="${tableName}_${colsList//:/_}_index"
printf -- "\n--Index: %s\nDROP INDEX IF EXISTS %s;\n
CREATE INDEX %s\n\t\tON %s USING btree\n\t(%s);
" "$indexName" "$indexName" "$indexName" "$tableName" "$colsList"
done
- See previous answers
- Weitere Antworten anzeigen