全文检索

本篇在 SQLite 聊天消息表上接入 SearchPlugin,让新写入的消息在后台自动同步进搜索索引,并提供支持按房间筛选的关键词全文搜索接口。

架构图示

配置数据库与索引自动同步#

直接在业务大表上手写 LIKE '%rust%' 无法按匹配相关度排序,数据量大了还会拖慢数据库。SearchPlugin 默认直接利用你现有的关系数据库完成全文检索(开发和起步阶段无需安装任何外部搜索引擎),日后数据量增长时改一行配置就能切到 Elasticsearch 或 OpenSearch;检索时先从索引拿到匹配的主键 ID,再回数据库查最新行,刚删掉的记录绝不会返回给前端。

首先开启 SQLite、迁移和搜索三个 feature,新建 Cargo.toml:

TOML
[package]
name = "guide-search"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"

[dependencies]
kxed = { version = "0.0.5-alpha", features = ["seaorm-sqlite", "seaorm-migration", "search"] }

指定本地 SQLite 数据库文件(请把运行生成的 chat.sqlite、-wal 与 -shm 加入 .gitignore)。

新建 config/database.toml:

TOML
url = "sqlite://chat.sqlite?mode=rwc"

接着开启索引同步开关,插件会自动建好变更队列表并在后台把新数据同步到搜索引擎。新建 config/search.toml:

TOML
[sync]
enabled = true

声明可搜索字段并编写读写接口#

接下来的 src/archive.rs 把数据表和全文检索串成了完整的三步:

  • 声明搜索与过滤字段(impl Searchable for Message):schema() 指定 text 列做关键词全文搜索、room 列做精确筛选;document() 返回要送进索引的 JSON(如果某条记录归档隐藏、不想再被搜到,返回 None 就会自动从索引中删掉它)。
  • 消息与同步记录同事务保存(archive):开启数据库写事务插入聊天消息后,紧接着在同一事务里调用 search.record::<Message>(&txn, &model) 再提交。这样万一事务回滚,同步记录也会一起回滚;哪怕外部搜索引擎短暂抖动,后台同步协程也会自动重试补齐。
  • 关键词检索叠加房间过滤(find):构造 SearchRequest::new(Scope::global()).text(query.q) 搜索文本,URL 传了 room 参数时再追加 Filter::eq("room", room) 缩小范围。

新建 src/archive.rs:

Rust
use kxed::plugins::search::{Filter, IndexSchema, Scope, SearchRequest, Searchable, Total};
use kxed::plugins::seaorm::async_trait;
use kxed::plugins::seaorm::sea_orm::sea_query::Table;
use kxed::plugins::seaorm::sea_orm::{
    ActiveModelTrait, ActiveValue::Set, DbErr, EntityTrait, Schema, Select,
};
use kxed::plugins::seaorm::sea_orm_migration::{
    MigrationName, MigrationTrait, MigratorTrait, SchemaManager,
};
use kxed::prelude::*;
use kxed::serde_json::{json, Value};

pub(crate) mod entity {
    use kxed::plugins::seaorm::sea_orm::{self, entity::prelude::*};

    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "messages")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        pub room: String,
        pub author: String,
        pub text: String,
    }

    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}

    impl ActiveModelBehavior for ActiveModel {}
}

pub(crate) use entity::Entity as Message;

impl Searchable for Message {
    const INDEX: &'static str = "messages";
    type Doc = Value;

    fn key(model: &entity::Model) -> String {
        model.id.to_string()
    }

    fn document(model: &entity::Model) -> Option<Value> {
        Some(json!({
            "id": model.id,
            "room": model.room,
            "author": model.author,
            "text": model.text,
        }))
    }

    fn schema() -> IndexSchema {
        IndexSchema::of::<Message>(Self::INDEX)
            .searchable(["text"])
            .filterable(["room"])
    }

    fn visible() -> Select<Message> {
        Message::find()
    }
}

pub(crate) struct Migrator;

#[async_trait]
impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        vec![Box::new(CreateMessages)]
    }
}

struct CreateMessages;

impl MigrationName for CreateMessages {
    fn name(&self) -> &str {
        "m20261007_000001_create_messages"
    }
}

#[async_trait]
impl MigrationTrait for CreateMessages {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let schema = Schema::new(manager.get_database_backend());
        manager.create_table(schema.create_table_from_entity(Message)).await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.drop_table(Table::drop().table(Message).to_owned()).await
    }
}

#[derive(Deserialize)]
pub(crate) struct NewMessage {
    room: String,
    author: String,
    text: String,
}

#[derive(Serialize)]
pub(crate) struct Archived {
    id: i64,
}

/// 业务行与同步队列记录在同一笔写事务内提交,避免一边成功一边丢失。
pub(crate) async fn archive(
    ctx: AppCtx,
    Json(input): Json<NewMessage>,
) -> Result<(StatusCode, Json<Archived>), AppErr> {
    let db = ctx.db()?;
    let search = ctx.search()?;
    let txn = db.begin_write().await?;
    let model = entity::ActiveModel {
        room: Set(input.room),
        author: Set(input.author),
        text: Set(input.text),
        ..Default::default()
    }
    .insert(&txn)
    .await?;
    search.record::<Message>(&txn, &model).await?;
    txn.commit().await?;
    Ok((StatusCode::CREATED, Json(Archived { id: model.id })))
}

#[derive(Deserialize)]
pub(crate) struct SearchQuery {
    q: String,
    room: Option<String>,
}

#[derive(Serialize)]
pub(crate) struct Hit {
    id: i64,
    room: String,
    author: String,
    text: String,
}

#[derive(Serialize)]
pub(crate) struct Hits {
    total: Option<u64>,
    items: Vec<Hit>,
}

pub(crate) async fn find(
    ctx: AppCtx,
    Query(query): Query<SearchQuery>,
) -> Result<Json<Hits>, AppErr> {
    let search = ctx.search()?;
    let mut request = SearchRequest::new(Scope::global()).text(query.q);
    if let Some(room) = query.room {
        request = request.filter(Filter::eq("room", room));
    }
    let page = search.search::<Message>(request).await?;
    let total = match page.total {
        Total::Exact(count) => Some(count),
        Total::AtLeast(_) | Total::Unknown => None,
    };
    let items = page
        .models
        .into_iter()
        .map(|model| Hit {
            id: model.id,
            room: model.room,
            author: model.author,
            text: model.text,
        })
        .collect();
    Ok(Json(Hits { total, items }))
}

注册同步实体并启动服务#

在入口先挂载 SeaOrmPlugin 建好 messages 表(锁机制说明见 SeaORM plugin 的业务表迁移),再把 archive::Message 注册进 SearchPlugin 的 SyncRegistry,启动时就会自动准备好对应的搜索索引并开启后台同步协程。新建 src/main.rs:

Rust
mod archive;

use kxed::plugins::search::sync::SyncRegistry;
use kxed::plugins::search::SearchPlugin;
use kxed::plugins::seaorm::{MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new()
        .plugin(SeaOrmPlugin::new().migrate::<archive::Migrator>(MigrationLock::new("chat.migrations")))
        .plugin(SearchPlugin::new().with_sync(SyncRegistry::new().register::<archive::Message>()))
        .routes(|router| {
            router
                .route("/archive", post(archive::archive))
                .route("/archive/search", get(archive::find));
        })
        .run()
        .await
}

验证#

在空库状态下启动 cargo run(操作约定见 怎么读),另开一个终端先写入三条不同房间和内容的聊天记录:

Shell
curl --fail -H 'content-type: application/json' -d '{"room":"lobby","author":"alice","text":"Rust async runtime"}' http://127.0.0.1:8080/archive; echo
curl --fail -H 'content-type: application/json' -d '{"room":"dev","author":"bob","text":"rust error handling"}' http://127.0.0.1:8080/archive; echo
curl --fail -H 'content-type: application/json' -d '{"room":"lobby","author":"carol","text":"lunch at noon"}' http://127.0.0.1:8080/archive; echo

预期输出:

输出
{"id":1}
{"id":2}
{"id":3}

接着分别测试全房间搜关键词 rust,以及加上 room=lobby 房间过滤条件:

Shell
curl --fail 'http://127.0.0.1:8080/archive/search?q=rust'; echo
curl --fail 'http://127.0.0.1:8080/archive/search?q=rust&room=lobby'; echo

预期输出(SQLite 搜索后端默认按主键升序返回命中记录):

输出
{"total":2,"items":[{"id":1,"room":"lobby","author":"alice","text":"Rust async runtime"},{"id":2,"room":"dev","author":"bob","text":"rust error handling"}]}
{"total":1,"items":[{"id":1,"room":"lobby","author":"alice","text":"Rust async runtime"}]}

对比两次搜索结果:

  • 第一次搜索不区分大小写命中了 id 为 1 和 2 的两条含 rust 的消息,第 3 条无关消息被排除。
  • 第二次加上 room=lobby 后,只保留在 lobby 房间发言的第 1 条记录,total 同步变为 1。

扩容多实例与切换外部搜索引擎#

  • 跑多实例集群:默认的 database 搜索后端直接查询共享关系数据库(PostgreSQL 下会自动使用 to_tsvector 计算词频相关度排序),多个实例只要连接同一个数据库就能协同工作(见 多实例集群);如果配置成了纯内存搜索后端,多实例启动会直接报错拦截。
  • 切换到独立搜索引擎:开启 Elasticsearch 或 OpenSearch 对应 feature 并修改 search.engine 即可,上面的 archive 和 find 业务代码一行不用改。切换后调用一次 Search::import 导入历史存量数据(未用 with_sync 的实体可调 Search::prepare::<M>() 建索引)。
  • 变更已上线索引字段:修改线上已有索引的字段类型时,平滑重建步骤见 改字段类型,完整示例见 search 示例 与 search 示例测试。

常见排错#

现象原因解决方法
新写入的记录一直搜不到忘了开 search.sync.enabled = true,或写库后漏调了 search.record::<M>(&txn, &model)核对 config/search.toml 同步开关,运行 cargo run -- search status 查看待同步积压与死信
加 Filter::eq 筛选时报字段不支持过滤该字段未在 Searchable::schema() 的 .filterable([..]) 列表中声明把需要精确过滤的列名加入 .filterable(["room"]) 并重建索引
SQLite 并发归档偶发锁冲突用 db.begin() 开启了延迟事务,同时写业务表与 Outbox 时锁升级冲突统一使用 db.begin_write().await? 开启立即写事务
多实例启动拒绝内存搜索后端集群模式下单机内存索引无法跨实例共享保持默认的 database 后端,或切换为共享的 Elasticsearch / OpenSearch

参考#

  • Search README:各搜索引擎后端与全部配置键说明
  • search 示例:连接外部搜索引擎、删除同步与存量全量导入
  • SeaORM plugin:数据库连接池与启动建表迁移