Index namespaces traversal_ids in descending order
When we sort groups by descendants we perform a comparison of traversal_ids
by their natural array ordering. Such as:
WHERE next_traversal_ids_sibling("superset"."traversal_ids") > "namespaces"."traversal_ids"
"superset"."traversal_ids" <= "namespaces"."traversal_ids"
We already have a btree index for namespaces traversal_ids:
CREATE INDEX index_btree_namespaces_traversal_ids ON namespaces USING btree (traversal_ids);
However this index does not perform well in some cases. For example, here is a query with the current unordered index and here is the same query with the ordered index.
$ rails db:migrate:down:main VERSION=20220518043259 == 20220518043259 IndexNamespacesTraversalIdsDesc: reverting ==================
-- transaction_open?()
-> 0.0000s
-- index_exists?(:namespaces, :traversal_ids, {:name=>"index_btree_namespaces_traversal_ids_desc", :algorithm=>:concurrently})
-> 0.0212s
-- execute("SET statement_timeout TO 0")
-> 0.0006s
-- remove_index(:namespaces, {:name=>"index_btree_namespaces_traversal_ids_desc", :algorithm=>:concurrently, :column=>:traversal_ids})
-> 0.0202s
-- execute("RESET statement_timeout")
-> 0.0008s
== 20220518043259 IndexNamespacesTraversalIdsDesc: reverted (0.0581s) =========
$ rails db:migrate:up:main VERSION=20220518043259 == 20220518043259 IndexNamespacesTraversalIdsDesc: migrating ==================
-- transaction_open?()
-> 0.0000s
-- index_exists?(:namespaces, :traversal_ids, {:order=>{:traversal_ids=>:desc}, :using=>:btree, :name=>"index_btree_namespaces_traversal_ids_desc", :algorithm=>:concurrently})
-> 0.0186s
-- execute("SET statement_timeout TO 0")
-> 0.0006s
-- add_index(:namespaces, :traversal_ids, {:order=>{:traversal_ids=>:desc}, :using=>:btree, :name=>"index_btree_namespaces_traversal_ids_desc", :algorithm=>:concurrently})
-> 0.0043s
-- execute("RESET statement_timeout")
-> 0.0007s
== 20220518043259 IndexNamespacesTraversalIdsDesc: migrated (0.0325s) =========
Related to #350637 (closed)
Edited by Alex Pooley