Optimize index design and usage
Indexes reduce data scan volume and accelerate queries in ApsaraDB for SelectDB. Learn about each index type, its applicable scenarios, creation methods, and verification approaches to select the right index for your query patterns.
Index type overview
ApsaraDB for SelectDB supports the following index types:
|
Index type |
Auto-created |
Creation method |
Applicable scenario |
|
Short Key Index (prefix index) |
Yes |
Built automatically from key columns |
Equality and range filtering on key column prefix |
|
ZoneMap Index |
Yes |
Maintains min/max per data block per column |
Range filtering on numeric and date columns |
|
Bloom Filter Index |
No |
PROPERTIES in CREATE TABLE or ALTER TABLE |
Equality filtering (=, IN) on high-cardinality columns |
|
Inverted Index |
No |
CREATE INDEX or inline definition in CREATE TABLE |
Full-text search, string matching, multi-condition filtering |
|
NGram Bloom Filter Index |
No |
CREATE INDEX or inline definition in CREATE TABLE |
LIKE '%keyword%' pattern matching acceleration |
Index selection guide
Select the appropriate index type based on your query pattern:
|
Query pattern |
Recommended index |
Notes |
|
|
Short Key Index |
Takes effect automatically. Filter conditions must match the key column prefix order. |
|
|
Bloom Filter Index |
Suitable for device IDs, order numbers, etc. Ineffective on low-cardinality columns (status, gender). |
|
|
Inverted Index |
Supports Chinese and English tokenization. Use MATCH_ALL/MATCH_ANY for search. |
|
|
Inverted Index |
Create inverted indexes on each filtered column. The optimizer combines them automatically. |
|
|
NGram BF Index |
Splits strings into N-gram segments and builds a Bloom Filter to avoid full table scans. |
Case 1: Optimize prefix index hits
The Short Key Index is built automatically from the leading 36 bytes of the key columns. Queries must match the key column prefix order to hit the index.
Problem scenario
The table key columns are defined as (event_time, user_id), but business queries frequently filter by user_id. Since user_id is not the key column prefix, the query cannot hit the prefix index and results in a full table scan:
-- Table with key columns (event_time, user_id)
CREATE TABLE user_events (
event_time DATETIME NOT NULL,
user_id BIGINT NOT NULL,
event_type VARCHAR(32),
device_id VARCHAR(64),
page_url TEXT
)
DUPLICATE KEY(event_time, user_id)
DISTRIBUTED BY HASH(user_id) BUCKETS AUTO;
-- Frequent query: filter by user_id, cannot hit prefix index
SELECT * FROM user_events WHERE user_id = 12345;
Solutions
Option A: Adjust key column order (recommended for new tables)
Place the frequently filtered column at the beginning of the key definition:
-- Recommended: place user_id first in key columns
CREATE TABLE user_events (
user_id BIGINT NOT NULL,
event_time DATETIME NOT NULL,
event_type VARCHAR(32),
device_id VARCHAR(64),
page_url TEXT
)
DUPLICATE KEY(user_id, event_time)
DISTRIBUTED BY HASH(user_id) BUCKETS AUTO;
Option B: Create a Rollup (for existing tables)
When the key column order of an existing table cannot be changed, create a Rollup to build an index view with the target column as prefix:
-- Create a Rollup with event_type as the prefix
ALTER TABLE user_events ADD ROLLUP rollup_event_type(event_type, event_time, user_id, device_id, page_url);
After the Rollup is created, the optimizer automatically selects it for queries filtering by event_type.
Prefix index design principles
-
Place frequently filtered columns first: Put columns that appear most often in WHERE clauses at the beginning of the key column list.
-
Place fixed-length types first: The prefix index uses only the first 36 bytes. VARCHAR columns consume more index space. Placing INT and BIGINT types first covers more columns within the budget.
-
Place equality columns before range columns: Range conditions terminate prefix matching. Placing equality columns first ensures subsequent columns still participate in index filtering.
Case 2: Use Bloom Filter indexes to accelerate equality queries
Bloom Filter indexes accelerate equality queries (=, IN) on high-cardinality non-key columns by quickly eliminating data blocks that cannot contain the target value, reducing disk I/O.
Creation methods
Specify during table creation:
CREATE TABLE user_events (
event_time DATETIME NOT NULL,
user_id BIGINT NOT NULL,
event_type VARCHAR(32),
device_id VARCHAR(64),
page_url TEXT
)
DUPLICATE KEY(event_time, user_id)
DISTRIBUTED BY HASH(user_id) BUCKETS AUTO
PROPERTIES (
"bloom_filter_columns" = "device_id"
);
Add to an existing table:
-- Add Bloom Filter columns (list all columns to keep)
ALTER TABLE user_events SET ("bloom_filter_columns" = "device_id, page_url");
Applicable scenarios
-- Equality query on high-cardinality device_id (Bloom Filter effective)
SELECT * FROM user_events WHERE device_id = 'device_abc_123';
-- IN queries also benefit
SELECT * FROM user_events WHERE device_id IN ('device_001', 'device_002', 'device_003');
Anti-pattern: Low-cardinality columns
Bloom Filter indexes on columns with few distinct values (such as status or gender) provide little benefit because most data blocks contain the target value, so the filter cannot eliminate blocks effectively:
-- Anti-pattern: event_type has only 3 values (click/view/purchase), Bloom Filter ineffective
PROPERTIES ("bloom_filter_columns" = "event_type") -- Not recommended
Constraints
-
Only effective for equality queries (=, IN). Does not accelerate range queries (>, <, BETWEEN).
-
Not supported on TINYINT, FLOAT, or DOUBLE columns.
-
A column cannot have both a Bloom Filter index and an NGram BF index. They are mutually exclusive.
Case 3: Use Inverted indexes for full-text search and multi-condition filtering
The Inverted Index is the most feature-rich index type in SelectDB. It supports full-text search (with Chinese and English tokenization), string matching, and multi-column combined filtering.
Scenario A: Full-text search
Create an inverted index with a tokenizer on text columns. Use MATCH_ALL (all terms must match) or MATCH_ANY (any term matches) for full-text search:
-- Inline inverted index definition with Chinese tokenizer
CREATE TABLE articles (
id BIGINT NOT NULL,
title VARCHAR(256),
content TEXT,
publish_time DATETIME,
INDEX idx_content(content) USING INVERTED PROPERTIES("parser" = "chinese")
)
DUPLICATE KEY(id)
DISTRIBUTED BY HASH(id) BUCKETS AUTO;
-- Full-text search: find articles containing both "SelectDB" and "index"
SELECT * FROM articles WHERE content MATCH_ALL 'SelectDB index';
-- Full-text search: find articles containing "optimization" or "import"
SELECT * FROM articles WHERE content MATCH_ANY 'optimization import';
Tokenizer selection:
-
Chinese text:
parser = "chinese" -
English text:
parser = "unicode"(supports case normalization with"lower_case" = "true") -
Exact matching without tokenization: omit the parser property (default is no tokenization)
Scenario B: Multi-condition filtering
Create inverted indexes on multiple columns. The optimizer automatically combines the index results during query execution:
-- Create inverted indexes on multiple columns
CREATE INDEX idx_title ON articles(title) USING INVERTED;
CREATE INDEX idx_publish_time ON articles(publish_time) USING INVERTED;
-- Multi-condition query: inverted indexes accelerate automatically
SELECT * FROM articles
WHERE title = 'SelectDB Best Practices'
AND publish_time >= '2024-01-01';
Inline definition during table creation
You can also define multiple inverted indexes inline during table creation:
CREATE TABLE articles (
id BIGINT NOT NULL,
title VARCHAR(256),
content TEXT,
publish_time DATETIME,
INDEX idx_title(title) USING INVERTED,
INDEX idx_content(content) USING INVERTED PROPERTIES("parser" = "chinese"),
INDEX idx_pub_time(publish_time) USING INVERTED
)
DUPLICATE KEY(id)
DISTRIBUTED BY HASH(id) BUCKETS AUTO;
Case 4: Use NGram BF indexes to accelerate LIKE pattern matching
Without an index, LIKE '%keyword%' queries require a full table scan. The NGram BF index splits strings into fixed-length N-gram segments and builds a Bloom Filter to quickly determine whether a data block might contain the target substring before reading it.
Creation method
-- Create an NGram BF index on the title column
CREATE INDEX idx_title_ngram ON articles(title) USING NGRAM_BF PROPERTIES("gram_size" = "3", "bf_size" = "1024");
After creation, the following query benefits from the index:
-- LIKE pattern matching, NGram BF index accelerates automatically
SELECT * FROM articles WHERE title LIKE '%Best Practices%';
Choosing gram_size
The gram_size parameter determines the length of each N-gram segment. Set it to the minimum character count of your search patterns:
-
Short patterns (2-3 characters, such as Chinese product names): set
gram_size = "2"or"3". -
Longer patterns (English words, URL fragments): set
gram_size = "4"or"5". -
Smaller
gram_sizeincreases index size and false positive rate. Largergram_sizecannot match short keywords. Match it to the shortest keyword length in your actual queries.
Comparison with Inverted indexes
|
Dimension |
Inverted Index |
NGram BF Index |
|
Matching method |
Token-based matching (MATCH_ALL/MATCH_ANY) |
Substring matching (LIKE '%keyword%') |
|
Chinese support |
Requires parser = "chinese" for tokenization |
Character-level splitting, natively supports Chinese |
|
Typical use case |
Keyword search, log analysis |
URL fragment matching, product name fuzzy search |
Constraints
-
A column cannot have both a Bloom Filter index and an NGram BF index. They are mutually exclusive.
-
Only supported on string type columns (CHAR, VARCHAR, STRING).
Verify index effectiveness
Use EXPLAIN to view the query plan and confirm whether indexes are taking effect.
View EXPLAIN output
EXPLAIN SELECT * FROM user_events WHERE device_id = 'device_abc_123';
-- In the OlapScanNode output, check the following fields:
-- PARTITIONS: 1/1 -- Partition pruning result
-- TABLETS: 10/10 -- Number of tablets scanned
-- tabletList=... -- Specific tablets involved
Use EXPLAIN VERBOSE for more detailed information, including index filter push-down status.
View created indexes
-- View all indexes on a table
SHOW INDEX FROM user_events;
-- View Bloom Filter configuration
SHOW CREATE TABLE user_events;
FAQ
How do I add indexes to an existing table?
Add Bloom Filter indexes using ALTER TABLE:
ALTER TABLE table_name SET ("bloom_filter_columns" = "col1, col2");
Add Inverted and NGram BF indexes using CREATE INDEX:
CREATE INDEX idx_name ON table_name(column_name) USING INVERTED;
CREATE INDEX idx_name ON table_name(column_name) USING NGRAM_BF PROPERTIES("gram_size" = "3", "bf_size" = "1024");
Index creation is an asynchronous operation (Schema Change). Use SHOW ALTER TABLE COLUMN to check progress. A table cannot have multiple Schema Change operations running simultaneously.
Can I have multiple index types on the same column?
Bloom Filter indexes and NGram BF indexes are mutually exclusive on the same column. Inverted indexes can coexist with Bloom Filter or NGram BF indexes. The Short Key Index and ZoneMap Index are created automatically and are not affected.
Do indexes affect write performance?
Indexes add computation and storage overhead during writes. Bloom Filter and NGram BF indexes have relatively minor overhead, while Inverted indexes (especially with tokenizers) have higher overhead but remain acceptable for most scenarios. Create indexes only on columns actually used in query filters.
How do I remove an index?
Remove Inverted and NGram BF indexes using DROP INDEX:
DROP INDEX idx_name ON table_name;
Remove Bloom Filter indexes by clearing the column list:
ALTER TABLE table_name SET ("bloom_filter_columns" = "");