使用Room自带的FTS模块实现全文搜索(FTS)可以大大简化搜索功能的开发过程。具体步骤如下:
在您的项目中添加以下依赖:
implementation 'android.arch.persistence.room:runtime:2.3.0'
implementation 'android.arch.persistence.room:rxjava2:2.3.0'
implementation 'android.arch.persistence.room:room-rxjava2:2.3.0'
implementation 'android.arch.persistence.room:room-compiler:2.3.0'
implementation "android.arch.persistence.room:room-fts:2.3.0"
在需要进行全文搜索的实体类上添加@Fts3注解,并在其内部类中定义用于搜索的表和列。例如,假设您的实体类为Book,您可以这样配置:
@Entity(tableName = "books")
@Fts3
data class Book(
@ColumnInfo(name = "id") @PrimaryKey val id: Long,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "author") val author: String,
@ColumnInfo(name = "summary") val summary: String
) {
@ColumnInfo(name = "content")
inner class BookContent(
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "author") val author: String,
@ColumnInfo(name = "summary") val summary: String
)
}
注意:您需要为搜索表设置一个表名,例如 "books_content",而不是在实体类上使用@Entity注解。
创建一个视图,以使Room跟踪从表中动态生成的内容表的更改。在此示例中,您可以这样定义:
@Dao
interface BookDao {
@Query("""
CREATE VIRTUAL TABLE IF NOT EXISTS books_content
USING FTS4(content=`books`, contentColumn=`content`)
""