鸿蒙应用内搜索实战:从全文检索到智能联想,构建一套高效的搜索系统
一、引言:搜索,是应用的"第二入口"
"用户找不到想要的内容,就会卸载应用。"
搜索是很多应用的核心功能——电商搜商品、内容平台搜文章、社交应用搜用户。但很多应用的搜索体验很差:搜不到、搜不准、搜得慢。
HarmonyOS 提供了多种搜索能力——全文检索(RDB)、自然语言处理(分词、相似度)、搜索联想。今天这篇,我们从搜索架构 → 全文检索 → 智能联想 → 搜索优化,系统拆解鸿蒙应用内搜索的完整方案。
二、先搞清楚:应用内搜索的三种方案
| 方案 | 说明 | 适用场景 |
|---|---|---|
| 简单 LIKE 查询 | RDB 的 LIKE 查询 | 小数据量(<1万条) |
| 全文检索(FTS) | RDB 的 FTS5 引擎 | 中等数据量(1-10万条) |
| 端侧 NLP | Natural Language Kit 相似度 | 语义搜索 |
选型建议:小数据用 LIKE,中等数据用 FTS5,需要语义理解用 NLP。
三、Step 1:全文检索——用 FTS5 实现高效搜索
FTS5 是 SQLite 的全文检索引擎,支持分词、倒排索引、相关性排序。
3.1 创建 FTS5 虚拟表
typescript
import { relationalStore } from '@kit.ArkData';
// 创建全文检索表
async function createFtsTable(store: relationalStore.RdbStore): Promise<void> {
// 创建 FTS5 虚拟表
await store.executeSql(`
CREATE VIRTUAL TABLE IF NOT EXISTS article_fts USING fts5(
title,
content,
category,
tokenize = 'unicode61'
)
`);
console.log('✅ 全文检索表创建成功');
}tokenize 参数说明:
| 分词器 | 说明 |
|---|---|
unicode61 | Unicode 分词(支持中文) |
porter | 英文词干提取 |
trigram | 三元组(适合模糊搜索) |
3.2 插入数据
typescript
// 插入文章到 FTS 表
async function insertArticle(store: relationalStore.RdbStore, article: Article): Promise<void> {
await store.executeSql(
`INSERT INTO article_fts (title, content, category) VALUES (?, ?, ?)`,
[article.title, article.content, article.category]
);
}3.3 全文检索查询
typescript
// 全文检索
async function searchArticles(store: relationalStore.RdbStore, keyword: string): Promise<Article[]> {
// FTS5 查询语法
const resultSet = await store.querySql(
`SELECT title, content, category, bm25(article_fts) as rank
FROM article_fts
WHERE article_fts MATCH ?
ORDER BY rank
LIMIT 20`,
[`${keyword}*`] // 前缀匹配
);
const results: Article[] = [];
while (resultSet.goToNextRow()) {
results.push({
title: resultSet.getString(0),
content: resultSet.getString(1),
category: resultSet.getString(2),
rank: resultSet.getDouble(3)
});
}
resultSet.close();
console.log(`✅ 搜索到 ${results.length} 条结果`);
return results;
}FTS5 查询语法:
| 语法 | 说明 | 示例 |
|---|---|---|
keyword | 包含关键词 | 鸿蒙 |
keyword* | 前缀匹配 | 鸿蒙* |
keyword1 keyword2 | 同时包含 | 鸿蒙 开发 |
keyword1 OR keyword2 | 包含任一 | 鸿蒙 OR 安卓 |
"phrase" | 短语匹配 | "鸿蒙开发" |
NOT keyword | 不包含 | 鸿蒙 NOT 安卓 |
四、Step 2:搜索联想——用户输入时实时提示
搜索联想让用户输入时就看到候选词,提升搜索效率。
typescript
// 搜索联想
async function getSuggestions(store: relationalStore.RdbStore, prefix: string): Promise<string[]> {
if (!prefix.trim()) return [];
const resultSet = await store.querySql(
`SELECT title FROM article_fts
WHERE article_fts MATCH ?
LIMIT 10`,
[`${prefix}*`]
);
const suggestions: string[] = [];
while (resultSet.goToNextRow()) {
suggestions.push(resultSet.getString(0));
}
resultSet.close();
return suggestions;
}在页面中实现联想:
typescript
@Entry
@Component
struct SearchPage {
@State keyword: string = '';
@State suggestions: string[] = [];
@State results: Article[] = [];
@State isSearching: boolean = false;
private store: relationalStore.RdbStore | null = null;
private debounceTimer: number = -1;
async aboutToAppear() {
const context = getContext(this) as common.UIAbilityContext;
this.store = await relationalStore.getRdbStore(context, {
name: 'app.db',
securityLevel: relationalStore.SecurityLevel.S1
});
}
// 输入时触发联想(防抖)
onKeywordChange(value: string) {
this.keyword = value;
if (this.debounceTimer !== -1) {
clearTimeout(this.debounceTimer);
}
this.debounceTimer = setTimeout(async () => {
if (this.store && value.trim()) {
this.suggestions = await getSuggestions(this.store, value);
} else {
this.suggestions = [];
}
}, 300); // 300ms 防抖
}
// 执行搜索
async doSearch() {
if (!this.store || !this.keyword.trim()) return;
this.isSearching = true;
this.suggestions = [];
try {
this.results = await searchArticles(this.store, this.keyword);
} finally {
this.isSearching = false;
}
}
build() {
Column() {
// 搜索框
Row() {
TextInput({ text: this.keyword, placeholder: '搜索文章...' })
.layoutWeight(1)
.onChange((v) => this.onKeywordChange(v))
.onSubmit(() => this.doSearch())
Button('搜索').onClick(() => this.doSearch())
}
.width('100%')
.padding(16)
// 联想列表
if (this.suggestions.length > 0) {
List() {
ForEach(this.suggestions, (suggestion: string) => {
ListItem() {
Row() {
Text('🔍').fontSize(16)
Text(suggestion)
.fontSize(14)
.margin({ left: 8 })
.layoutWeight(1)
}
.width('100%')
.padding(12)
}
.onClick(() => {
this.keyword = suggestion;
this.doSearch();
})
})
}
.height(200)
.backgroundColor('#FFFFFF')
}
// 搜索结果
if (this.isSearching) {
LoadingProgress().width(40).height(40).margin({ top: 20 })
} else if (this.results.length > 0) {
List() {
ForEach(this.results, (article: Article) => {
ListItem() {
Column() {
Text(article.title)
.fontSize(16)
.fontWeight(FontWeight.Medium)
Text(article.content)
.fontSize(14)
.fontColor('#666')
.maxLines(2)
.margin({ top: 4 })
Text(article.category)
.fontSize(12)
.fontColor('#007AFF')
.margin({ top: 4 })
}
.alignItems(HorizontalAlign.Start)
.width('100%')
.padding(16)
}
})
}
.layoutWeight(1)
} else if (this.keyword && !this.isSearching) {
Text('没有找到相关内容').fontSize(14).fontColor('#999').margin({ top: 40 })
}
}
.width('100%')
.height('100%')
}
}
interface Article {
title: string;
content: string;
category: string;
rank?: number;
}五、Step 3:语义搜索——用 NLP 做相似度匹配
FTS5 只能做字面匹配,如果用户搜"苹果手机壳",FTS5 搜不到"iPhone 保护套"。语义搜索用 NLP 的文本相似度能力解决这个问题。
typescript
import { naturalLanguage } from '@kit.NaturalLanguageKit';
// 语义搜索
async function semanticSearch(articles: Article[], query: string): Promise<Article[]> {
const calculator = await naturalLanguage.createTextSimilarity();
const scored: (Article & { score: number })[] = [];
for (const article of articles) {
const similarity = await calculator.calculate(
query,
article.title + ' ' + article.content
);
if (similarity > 0.3) { // 阈值
scored.push({ ...article, score: similarity });
}
}
// 按相似度排序
scored.sort((a, b) => b.score - a.score);
return scored.slice(0, 20);
}语义搜索 + 全文检索结合:
typescript
// 混合搜索:FTS5 + NLP
async function hybridSearch(store: relationalStore.RdbStore,
query: string): Promise<Article[]> {
// 1. 先用 FTS5 做字面匹配
const ftsResults = await searchArticles(store, query);
// 2. 如果结果少于 5 条,补充语义搜索
if (ftsResults.length < 5) {
const semanticResults = await semanticSearch(ftsResults, query);
// 3. 合并去重
const merged = new Map<string, Article>();
[...ftsResults, ...semanticResults].forEach(article => {
merged.set(article.title, article);
});
return Array.from(merged.values()).slice(0, 20);
}
return ftsResults;
}六、Step 4:搜索优化——索引与缓存
6.1 建立索引
typescript
// 为常用搜索字段建立索引
async function createIndexes(store: relationalStore.RdbStore): Promise<void> {
await store.executeSql(`
CREATE INDEX IF NOT EXISTS idx_article_category ON article(category)
`);
await store.executeSql(`
CREATE INDEX IF NOT EXISTS idx_article_time ON article(create_time)
`);
console.log('✅ 索引创建成功');
}6.2 搜索历史缓存
typescript
// 保存搜索历史
async function saveSearchHistory(context: common.UIAbilityContext, keyword: string): Promise<void> {
const prefs = await preferences.getPreferences(context, 'search_prefs');
const history = await prefs.get('history', '[]') as string;
const list = JSON.parse(history) as string[];
// 去重 + 限制数量
const newList = [keyword, ...list.filter(k => k !== keyword)].slice(0, 10);
await prefs.put('history', JSON.stringify(newList));
await prefs.flush();
}
// 读取搜索历史
async function getSearchHistory(context: common.UIAbilityContext): Promise<string[]> {
const prefs = await preferences.getPreferences(context, 'search_prefs');
const history = await prefs.get('history', '[]') as string;
return JSON.parse(history) as string[];
}七、完整示例:搜索页面(带历史记录)
typescript
@Entry
@Component
struct FullSearchPage {
@State keyword: string = '';
@State suggestions: string[] = [];
@State results: Article[] = [];
@State history: string[] = [];
@State isSearching: boolean = false;
@State showHistory: boolean = true;
private store: relationalStore.RdbStore | null = null;
private debounceTimer: number = -1;
async aboutToAppear() {
const context = getContext(this) as common.UIAbilityContext;
this.store = await relationalStore.getRdbStore(context, {
name: 'app.db',
securityLevel: relationalStore.SecurityLevel.S1
});
this.history = await getSearchHistory(context);
}
onKeywordChange(value: string) {
this.keyword = value;
this.showHistory = !value;
if (this.debounceTimer !== -1) clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(async () => {
if (this.store && value.trim()) {
this.suggestions = await getSuggestions(this.store, value);
} else {
this.suggestions = [];
}
}, 300);
}
async doSearch(keyword?: string) {
const q = keyword || this.keyword;
if (!this.store || !q.trim()) return;
this.keyword = q;
this.isSearching = true;
this.showHistory = false;
this.suggestions = [];
// 保存搜索历史
const context = getContext(this) as common.UIAbilityContext;
await saveSearchHistory(context, q);
this.history = await getSearchHistory(context);
try {
this.results = await hybridSearch(this.store, q);
} finally {
this.isSearching = false;
}
}
build() {
Column() {
// 搜索框
Row() {
TextInput({ text: this.keyword, placeholder: '搜索文章...' })
.layoutWeight(1)
.onChange((v) => this.onKeywordChange(v))
.onSubmit(() => this.doSearch())
Button('搜索').onClick(() => this.doSearch())
}
.width('100%')
.padding(16)
// 搜索历史
if (this.showHistory && this.history.length > 0) {
Column() {
Row() {
Text('搜索历史').fontSize(16).fontWeight(FontWeight.Bold)
Blank()
Text('清除').fontSize(14).fontColor('#999')
.onClick(async () => {
const context = getContext(this) as common.UIAbilityContext;
const prefs = await preferences.getPreferences(context, 'search_prefs');
await prefs.put('history', '[]');
await prefs.flush();
this.history = [];
})
}
.width('100%')
.padding(16)
Flex({ wrap: FlexWrap.Wrap }) {
ForEach(this.history, (item: string) => {
Text(item)
.fontSize(14)
.padding({ left: 12, right: 12, top: 6, bottom: 6 })
.backgroundColor('#F5F5F5')
.borderRadius(16)
.margin({ right: 8, bottom: 8 })
.onClick(() => this.doSearch(item))
})
}
.padding({ left: 16, right: 16 })
}
}
// 联想列表
if (this.suggestions.length > 0) {
List() {
ForEach(this.suggestions, (suggestion: string) => {
ListItem() {
Row() {
Text('🔍').fontSize(16)
Text(suggestion)
.fontSize(14)
.margin({ left: 8 })
.layoutWeight(1)
}
.width('100%')
.padding(12)
}
.onClick(() => this.doSearch(suggestion))
})
}
.height(200)
}
// 搜索结果
if (this.isSearching) {
LoadingProgress().width(40).height(40).margin({ top: 20 })
} else if (this.results.length > 0) {
List() {
ForEach(this.results, (article: Article) => {
ListItem() {
Column() {
Text(article.title).fontSize(16).fontWeight(FontWeight.Medium)
Text(article.content).fontSize(14).fontColor('#666').maxLines(2).margin({ top: 4 })
}
.alignItems(HorizontalAlign.Start)
.width('100%')
.padding(16)
}
})
}
.layoutWeight(1)
} else if (this.keyword && !this.isSearching && !this.showHistory) {
Text('没有找到相关内容').fontSize(14).fontColor('#999').margin({ top: 40 })
}
}
.width('100%')
.height('100%')
}
}八、常见踩坑点
坑1:用 LIKE 做全文搜索
数据量大时 LIKE '%keyword%' 无法使用索引,查询极慢。
✅ 解法:用 FTS5 全文检索,建立倒排索引。
坑2:搜索联想没有防抖
用户每输入一个字符就查询一次,请求频繁。
✅ 解法:加 300ms 防抖,用户停止输入后再查询。
坑3:FTS5 中文分词不准
unicode61 分词器对中文分词效果一般。
✅ 解法:中文场景可以用 trigram 分词器,或结合 NLP 分词预处理。
坑4:搜索结果没有排序
结果按插入顺序返回,相关的结果排在后面。
✅ 解法:用 bm25() 按相关性排序。
坑5:搜索历史无限增长
搜索历史越存越多,占用空间。
✅ 解法:限制最多 10 条,去重保存。
九、结语
应用内搜索是用户找到内容的"第二入口"——搜索体验差,用户就会流失。
从全文检索(FTS5)→ 搜索联想 → 语义搜索(NLP)→ 搜索优化,这套方案覆盖了电商、内容、社交等应用的搜索需求。核心原则:FTS5 做字面匹配、NLP 做语义补充、联想要防抖、结果要排序。
记住三个核心原则:
-
全文检索用 FTS5——别用 LIKE
-
联想加防抖——300ms 起步
-
结果按相关性排序——
bm25()不能少
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要发帖子






































苏公安网备 32011402010933号