Skip to content

Instantly share code, notes, and snippets.

@sienatime
Last active September 25, 2020 12:31
Show Gist options
  • Save sienatime/b019ce924bd07922925c7b144b8f9097 to your computer and use it in GitHub Desktop.
Save sienatime/b019ce924bd07922925c7b144b8f9097 to your computer and use it in GitHub Desktop.
Code snippets for adding FTS support to Room (Android architecture components)
@Database(entities = {
Entry.class, Sense.class, CrossReference.class, EntryFts.class
}, version = 4, exportSchema = false) public abstract class AppDatabase extends RoomDatabase
public LiveData<PagedList<SearchResultEntry>> search(String term) {
String wildcardQuery = String.format("*%s*", term);
return new LivePagedListBuilder<>(entryDao.searchByJapaneseTerm(wildcardQuery), PAGE_SIZE).build();
}
@Transaction @Query(
"SELECT entries.id, entries.primary_kanji, entries.primary_reading FROM entries "
+ "JOIN entriesFts ON (entries.id = entriesFts.docid) WHERE entriesFts MATCH :term")
DataSource.Factory<Integer, SearchResultEntry> searchByJapaneseTerm(String term);
@Fts4(contentEntity = Entry.class)
@Entity(tableName = "entriesFts")
public class EntryFts {
@ColumnInfo(name = "primary_kanji")
private String primaryKanji;
@NonNull
@ColumnInfo(name = "primary_reading")
private String primaryReading;
@ColumnInfo(name = "other_kanji")
private String otherKanji;
@ColumnInfo(name = "other_readings")
private String otherReadings;
public EntryFts(String primaryKanji, @NonNull String primaryReading, String otherKanji,
String otherReadings) {
this.primaryKanji = primaryKanji;
this.primaryReading = primaryReading;
this.otherKanji = otherKanji;
this.otherReadings = otherReadings;
}
public String getPrimaryKanji() {
return primaryKanji;
}
@NonNull public String getPrimaryReading() {
return primaryReading;
}
public String getOtherKanji() {
return otherKanji;
}
public String getOtherReadings() {
return otherReadings;
}
}
Room.databaseBuilder(...)
.addMigrations(new Migration(3, 4) {
@Override public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("CREATE VIRTUAL TABLE IF NOT EXISTS `entriesFts` USING FTS4(`primary_kanji`, `primary_reading`, `other_kanji`, `other_readings`, content=`entries`)");
database.execSQL("INSERT INTO entriesFts(entriesFts) VALUES ('rebuild')");
}
})
.build();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment