RayDB LogoRayDB

Indexing strategies

Effective indexing is crucial for optimizing PostgreSQL query performance in RayDB. This guide covers different indexing strategies to improve data retrieval speed and reduce query execution time.

1. Use B-Tree Indexes for Equality and Range Queries

  • Default and most common index type in PostgreSQL.
  • Best for =, <, <=, >, >=, and BETWEEN operations.
  • Example:
    CREATE INDEX idx_users_email ON users (email);

2. Use Hash Indexes for Exact Matches

  • Useful for queries with only equality conditions (=).
  • Less flexible than B-Tree but can be faster in some cases.
  • Example:
    CREATE INDEX idx_orders_hash ON orders USING hash(order_id);

3. Use GIN Indexes for Full-Text Search and JSONB

  • Ideal for indexing array, JSONB, and full-text search fields.
  • Example (for JSONB search):
    CREATE INDEX idx_products_data ON products USING gin(data);

4. Use BRIN Indexes for Large Tables with Ordered Data

  • Efficient for large datasets with naturally ordered columns.
  • Uses a summarized block range instead of storing all index entries.
  • Example:
    CREATE INDEX idx_logs_brin ON logs USING brin(timestamp);

5. Use Partial Indexes for Specific Query Conditions

  • Saves storage by indexing only relevant rows.
  • Example:
    CREATE INDEX idx_active_users ON users (last_login) WHERE active = true;

6. Use Covering Indexes to Avoid Table Lookups

  • Stores additional columns within the index to speed up reads.
  • Example:
    CREATE INDEX idx_orders_covering ON orders (customer_id) INCLUDE (order_date, total);

7. Remove Unused or Redundant Indexes

  • Excessive indexing slows down writes and increases storage usage.
  • Check index usage with:
    SELECT * FROM pg_stat_user_indexes WHERE idx_scan = 0;

8. Monitor Index Efficiency

  • Use EXPLAIN ANALYZE to verify index usage:
    EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 123;
  • Regularly run REINDEX to maintain index performance:
    REINDEX TABLE orders;

Best Practices

  • Index only necessary columns to avoid overhead.
  • Use GIN or BRIN indexes for specialized data types.
  • Monitor and remove unused indexes to keep queries efficient.

For more query optimization techniques, refer to Query Optimization.

On this page