【问题标题】:How to search FTS3 table so that searched word show top of the list如何搜索 FTS3 表,以便搜索到的单词显示在列表顶部
【发布时间】:2020-09-11 06:41:15
【问题描述】:

我在 Android SQLite 数据库中有一个 FTS3 表。数据库工作正常。现在我想在有单词列的表中搜索。搜索也很好,但问题是当我用一个词搜索时,搜索到的词在底部或列表中的另一个位置。假设我想在这里搜索“GOOD”,我希望唯一的“GOOD”位于列表顶部,其他位于列表底部。

请看我的代码。

cursor = db.query("wordfts", new String[]{"id,word,mean"}, "wordfts" + " MATCH ?", new String[]{"*"+constraint.toUpperCase() + "*"}, null, null, "word", "5");

对不起我的英语不好

【问题讨论】:

    标签: java android sqlite android-sqlite fts3


    【解决方案1】:

    query() 方法的第 7 个参数是语句的 ORDER BY 子句。
    因此,使用您的代码,结果只是按列word 排序。
    但是,如果您希望在顶部显示与您的模式完全匹配的行,则必须将其更改为:

    upper(word) = 'GOOD' desc
    

    所以把你的代码改成这样:

    cursor = db.query(
        "wordfts", 
        new String[] {"id,word,mean"}, 
        "wordfts MATCH ?", 
        new String[] {"*" + constraint.toUpperCase() + "*"}, 
        null, 
        null, 
        "upper(word) = '" + constraint.toUpperCase() + "' desc", 
        "5"
    );
    

    或者更好地使用rawQuery(),这样您就可以使用? 占位符来传递所有参数,包括ORDER BY 子句中的参数,从而使您的代码更安全:

    cursor = db.query(
        "SELECT id, word, mean FROM wordfts WHERE wordfts MATCH ? ORDER BY UPPER(word) = ? DESC LIMIT 5",
        new String[] {"*" + constraint.toUpperCase() + "*", constraint.toUpperCase()}
    );
    

    【讨论】: