I have a table Term with a little more than 5 million rows. Each row consists of an ID and a "name". A search with "name" field takes nearly 35 seconds.
MariaDB [WordDS]> select * from Term where name="Google";
+---------+--------+
| id | name |
+---------+--------+
| 1092923 | Google |
+---------+--------+
1 row in set (35.35 sec)
The script from the table generated by Hibernate:
DROP TABLE IF EXISTS `Term`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Term` (
`id` bigint(20) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
Java annotation:
@Id
@Column(unique=true)
private long id;
@NotNull
@Size(min = 1, max = 100)
private String name;
It's so slow to search on the field "name", so I guess there is no index. Does Hibernate automatically create index on id and name in this table? If not, how to let it create index for both?
By default, Hibernate Search will use the fully qualified class name as the index name. With the @Entity annotation from JPA, we map a class to a database table and, its fields to the table columns.
A Unique index will be created automatically when you define a PRIMARY KEY or UNIQUE KEY constraints on the specified columns.
PRIMARY KEY or UNIQUE constraint When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index. The primary key column cannot allow NULL values.
Yes, primary key is automatically indexed in MySQL because primary key, index, etc gets stored into B-trees. All engines including InnoDB as well as MyISAM automatically supports the primary key to be indexed. The primary key is implicitly indexed in InnoDB, MyISAM, and other engines.
Use the @Index
annotation:
@Entity
@Table(name = "Term", indexes = {
@Index(columnList = "name, id", name = "name_idx") })
Hibernate will create the index automatically when it creates the table at startup.
The primary key is indexed automatically, for the name
field, you have to add an @Index
annotation:
@NotNull
@Size(min = 1, max = 100)
@Index(name = "idx_name")
private String name;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With