Junior — Middle
What are the ways to implement field indexing in a database?
sobes.tech AI
Answer from AI
Indexing a field in a database can be implemented in the following ways:
-
Creating a regular (B-tree) index — the most common type of index, suitable for fast exact match and range searches.
-
Unique index — an index that does not allow duplicate values in the field.
-
Hash index — used for fast exact match searches but does not support range queries (e.g., in PostgreSQL).
-
Expression or computed column index — indexing the result of an expression rather than the field itself.
-
Full-text index — for fast text searches.
-
Index using external tools (e.g., ElasticSearch) — for complex search and analytics.
Example of creating a regular index in SQL:
CREATE INDEX idx_user_email ON users(email);
In Java, using JPA, you can specify an index via annotation:
@Entity
@Table(name = "users", indexes = {
@Index(name = "idx_user_email", columnList = "email")
})
public class User {
@Id
private Long id;
private String email;
// ...
}