Instant Autocomplete — How We Improved our Search Queries

Painfully slow autocomplete

Search Requirements

select * from tokens where contract_address like ‘0x123%’ or name ilike ‘0x123%’;
select * from tokens where name ilike 'agent%';

Some Issues We Had to Overcome

Some Tokens Have Ridiculous Names (B-tree index was a no-go)

99.9% of tokens have a name length of 100 characters or less
https://bscscan.com/token/0xea064849f58f9C55Abf76Bf6a621CE437EE4a072
create index on token (name);------ERROR:  index row size 3688 exceeds btree version 4 maximum 2704 for index "name_ind" DETAIL:  Index row references tuple (9748,1) in relation "token". HINT:  Values larger than 1/3 of a buffer page cannot be indexed. Consider a function index of an MD5 hash of the value, or use full text indexing. SQL state: 54000

We store our contract addresses as citext

create index on token (contract_address);

Indexes are not used when searching for both contract address and name

Our Solution(s)

Use Generated Columns for performance improvements

alter table tokenADD COLUMN search_address varchar(42) generated always as (lower(contract_address::text)) stored,ADD COLUMN search_name varchar generated always AS (lower(substring(name, 1, 256))) stored;

Fix Index for Search Address

create index on token (search_address COLLATE "C");
select * from token where search_address like '0x234%' limit 10;

Create GIN Index for Search Name

create extension pg_trgm;
create index on token using gin (search_name gin_trgm_ops);
select * from token where search_name like '%agent shiba%' limit 10;

Remove the OR clause when searching for both address and name

select * from token 
where search_address like '0x2345%'
or search_name like '%0x2345%'
limit 10;
select * from token 
where search_address like '0x2345%'
UNION ALL
select * from token
where search_name like '%0x2345%'
limit 10;
1. Retrieve up to 10 tokens where search_address matches the search term
2. If less than 10 tokens retrieved, retrieve (10 - number retrieved) tokens where search_name matches the search term

The Results

Much snappier search

--

--

Agents of I.N.U. Defenders of DeFi. https://agentsinu.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store