Currently, I have a Room entity which looks like
@Entity(
tableName = "holiday_country",
indices = {
@Index(value = "code", unique = true)
}
)
public class HolidayCountry
which is equivalent of having index
CREATE UNIQUE INDEX `index_holiday_country_code` ON `holiday_country` (`code`)
However, I also need to have the following 2nd index as I will be performing case insensitive query sometimes.
CREATE UNIQUE INDEX `index_holiday_country_code_nocase` ON `holiday_country` (`code` COLLATE NOCASE)
If that is so, how should such index be declared in Room entity?
The aggregation framework was introduced in mongodb 2.2 . You can use the string operator "$strcasecmp" to make a case-insensitive comparison between strings. It's more recommended and easier than using regex.
To use a case insensitive index on a collection with no default collation, create an index with a collation and set the strength parameter to 1 or 2 (see Collation for a detailed description of the strength parameter). You must specify the same collation at the query level in order to use the index-level collation.
Since MongoDB's previous versions did not support Collation, you were limited to performing a case-sensitive index comparison. In the scenarios that needed case-insensitive behavior, the only option was to convert/store all of your strings to either uppercase or lowercase and then do the comparison.
The default collations used by SQL Server and MySQL do not distinguish between upper and lower case letters—they are case-insensitive by default.
Unfortunately, there are no options to define COLLATE
on a column while creating an Index
. By taking a look at the source code of androidx.room.Index
, we can see that the only possible options are:
Index.java (comments were omitted due to conciseness)
package androidx.room;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({})
@Retention(RetentionPolicy.CLASS)
public @interface Index {
String[] value();
String name() default "";
boolean unique() default false;
}
So, the only possible way in Room
, is to define the COLLATE
in the table creation statement:
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Index;
@Entity(
tableName = "holiday_country",
indices = {
@Index(value = "code", unique = true)
}
)
public class HolidayCountry {
@ColumnInfo(name = "code", collate = ColumnInfo.NOCASE)
public String code;
// Other fields ...
}
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