An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve hierarchical path search matching and sorting https://github.com/siyuan-note/siyuan/issues/18305
Daniele0e3c15486d3
diff --git a/kernel/model/search.go b/kernel/model/search.goindex 000e1c8efd..0e4c62eeea 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -1350,7 +1350,7 @@ func FullTextSearchBlockInBoxWithHPath(query string, boxes, paths []string, type}} else {docMode = true // 文档全文搜索模式 https://github.com/siyuan-note/siyuan/issues/10584- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID, searchHPath)+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, boxID, searchHPath)}}}@@ -2034,7 +2034,7 @@ func fullTextSearchByFTSInBox(query, boxFilter, pathFilter string, boxArgs, pathfunc fullTextSearchByFTSAndHPathInBox(rawQuery, query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string, orderBy, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {cte, args := buildFTSAndHPathMatchesCTE(rawQuery, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter)- stmt := cte + " SELECT b.*, matches.match_source FROM matches JOIN blocks b ON b.rowid = matches.block_rowid"+ stmt := cte + " SELECT b.rowid AS block_rowid, matches.match_source FROM matches JOIN blocks b ON b.rowid = matches.block_rowid"stmt += " " + buildHPathSearchOrderBy(rawQuery, orderBy)stmt += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)result, err := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)@@ -2044,8 +2044,19 @@ func fullTextSearchByFTSAndHPathInBox(rawQuery, query, boxFilter, pathFilter strreturn}- sqlBlocks := sql.ToBlocks(result)- ret = fromSQLBlocks(&sqlBlocks, rawQuery, beforeLen)+ matches := make([]ftsAndHPathMatch, 0, len(result))+ for _, row := range result {+ matches = append(matches, ftsAndHPathMatch{+ rowID: row["block_rowid"].(int64),+ source: int(row["match_source"].(int64)),+ })+ }+ ret, err = loadFTSAndHPathMatchBlocks(matches, rawQuery, query, beforeLen, boxID)+ if err != nil {+ logging.LogErrorf("load blocks by FTS and hpath failed: %s", err)+ ret = []*Block{}+ return+ }if 1 > len(ret) {ret = []*Block{}}@@ -2064,6 +2075,113 @@ func fullTextSearchByFTSAndHPathInBox(rawQuery, query, boxFilter, pathFilter strreturn}+type ftsAndHPathMatch struct {+ rowID int64+ source int+}++func loadFTSAndHPathMatchBlocks(matches []ftsAndHPathMatch, rawQuery, query string, beforeLen int, boxID string) (ret []*Block, err error) {+ var ftsRowIDs, hPathRowIDs []int64+ for _, match := range matches {+ if 0 == match.source {+ ftsRowIDs = append(ftsRowIDs, match.rowID)+ } else {+ hPathRowIDs = append(hPathRowIDs, match.rowID)+ }+ }++ ftsBlocks, err := queryFTSSnippetBlocksByRowID(query, ftsRowIDs, boxID)+ if err != nil {+ return nil, err+ }+ hPathBlocks, err := queryRawBlocksByRowID(hPathRowIDs, boxID)+ if err != nil {+ return nil, err+ }+ for _, match := range matches {+ sqlBlock := ftsBlocks[match.rowID]+ terms := ""+ if 0 != match.source {+ sqlBlock = hPathBlocks[match.rowID]+ terms = rawQuery+ }+ if nil == sqlBlock {+ continue+ }+ block := fromSQLBlock(sqlBlock, terms, beforeLen)+ if 0 == match.source {+ markBlockHPath(block, sqlBlock.HPath, rawQuery, -1)+ }+ ret = append(ret, block)+ }+ return+}++func queryFTSSnippetBlocksByRowID(query string, rowIDs []int64, boxID string) (ret map[int64]*sql.Block, err error) {+ ret = map[int64]*sql.Block{}+ if 1 > len(rowIDs) {+ return+ }++ stmt, args := buildFTSSnippetBlocksByRowIDQuery(query, rowIDs)+ result, err := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)+ if err != nil {+ return nil, err+ }+ ret = mapSQLBlocksByRowID(result)+ return+}++func buildFTSSnippetBlocksByRowIDQuery(query string, rowIDs []int64) (stmt string, args []any) {+ table := "blocks_fts"+ projections := "rowid AS block_rowid, id, parent_id, root_id, hash, box, path, hpath, " ++ "snippet(" + table + ", 7, '" + search.SearchMarkLeft + "', '" + search.SearchMarkRight + "', '...', 512) AS name, " ++ "snippet(" + table + ", 8, '" + search.SearchMarkLeft + "', '" + search.SearchMarkRight + "', '...', 512) AS alias, " ++ "snippet(" + table + ", 9, '" + search.SearchMarkLeft + "', '" + search.SearchMarkRight + "', '...', 512) AS memo, " ++ "snippet(" + table + ", 10, '" + search.SearchMarkLeft + "', '" + search.SearchMarkRight + "', '...', 64) AS tag, " ++ "snippet(" + table + ", 11, '" + search.SearchMarkLeft + "', '" + search.SearchMarkRight + "', '...', 512) AS content, " ++ "fcontent, markdown, length, type, subtype, ial, sort, created, updated"+ stmt = "SELECT " + projections + " FROM " + table ++ " WHERE (`" + table + "` MATCH '" + columnFilter() + ":(" + query + ")')" ++ " AND rowid IN (" + strings.TrimSuffix(strings.Repeat("?,", len(rowIDs)), ",") + ")"+ args = make([]any, len(rowIDs))+ for i, rowID := range rowIDs {+ args[i] = rowID+ }+ return+}++func queryRawBlocksByRowID(rowIDs []int64, boxID string) (ret map[int64]*sql.Block, err error) {+ ret = map[int64]*sql.Block{}+ if 1 > len(rowIDs) {+ return+ }+ stmt := "SELECT rowid AS block_rowid, * FROM blocks WHERE rowid IN (" ++ strings.TrimSuffix(strings.Repeat("?,", len(rowIDs)), ",") + ")"+ args := make([]any, len(rowIDs))+ for i, rowID := range rowIDs {+ args[i] = rowID+ }+ result, err := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)+ if err != nil {+ return nil, err+ }+ ret = mapSQLBlocksByRowID(result)+ return+}++func mapSQLBlocksByRowID(result []map[string]any) (ret map[int64]*sql.Block) {+ ret = map[int64]*sql.Block{}+ for _, row := range result {+ rowID := row["block_rowid"].(int64)+ blocks := sql.ToBlocks([]map[string]any{row})+ if 0 < len(blocks) {+ ret[rowID] = blocks[0]+ }+ }+ return+}+func buildFTSAndHPathMatchesCTE(rawQuery, query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string) (cte string, args []any) {table := "blocks_fts"hPathCondition, hPathArg := buildHPathContainsCondition(rawQuery)@@ -2087,10 +2205,28 @@ func buildFTSAndHPathMatchesCTE(rawQuery, query, boxFilter, pathFilter string, b}func buildHPathContainsCondition(query string) (condition, arg string) {- if Conf.Search.CaseSensitive {+ if Conf.Search.CaseSensitive && Conf.Search.HanSensitiveVal() {return "instr(hpath, ?) > 0", query}- return "hpath LIKE ? ESCAPE '\\'", "%" + escapeSearchDocLikePattern(query) + "%"+ caseSensitive, hanSensitive := searchNormalizationFlags()+ condition = "instr(search_normalize(hpath, " + strconv.Itoa(caseSensitive) + ", " + strconv.Itoa(hanSensitive) + "), ?) > 0"+ arg = search.NormalizeSearchText(query, Conf.Search.CaseSensitive, Conf.Search.HanSensitiveVal())+ return+}++func searchNormalizationFlags() (caseSensitive, hanSensitive int) {+ if Conf.Search.CaseSensitive {+ caseSensitive = 1+ }+ if Conf.Search.HanSensitiveVal() {+ hanSensitive = 1+ }+ return+}++func normalizedHPathSearchField(field string) string {+ caseSensitive, hanSensitive := searchNormalizationFlags()+ return "search_normalize(" + field + ", " + strconv.Itoa(caseSensitive) + ", " + strconv.Itoa(hanSensitive) + ")"}func buildHPathSearchOrderBy(query string, orderBy int) string {@@ -2160,19 +2296,21 @@ func fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter string, boxArgs,return}-func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {+func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string, orderBy, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {return fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, "", true)}-func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount int) {+func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string, orderBy, beforeLen, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount int) {+ rawQuery := queryquery = strings.ReplaceAll(query, "'", "''") // 不需要转义双引号,因为条件都是通过单引号包裹的,只需要转义单引号即可keywords := strings.Split(query, " ")contentField := columnConcat()- documentSearchField := contentField+ contentDocumentLikeFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+contentField+")", keywords)+ documentLikeFilter := contentDocumentLikeFilterif searchHPath {- documentSearchField += "||(CASE WHEN type = 'd' THEN hpath ELSE '' END)"+ hPathField := "MAX(CASE WHEN type = 'd' THEN " + normalizedHPathSearchField("hpath") + " ELSE '' END)"+ documentLikeFilter = buildSearchDocumentLikeFilterWithHPath("GROUP_CONCAT("+contentField+")", hPathField, keywords)}- documentLikeFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+documentSearchField+")", keywords)blockLikeFilter := buildSearchDocumentLikeFilter(contentField, keywords)var orderByLike strings.BuilderorderByLike.WriteString("(")@@ -2186,31 +2324,24 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxA// box/path 过滤子句在下方 dMatchStmt 与 selectStmt 中各出现一次,绑定参数需按出现顺序收集两份。// 第一份对应 CTE 内的 WHEREargs := append(append([]any{}, boxArgs...), pathArgs...)- dMatchStmt := "SELECT root_id, MAX(CASE WHEN type = 'd' THEN (" + contentField + ") END) AS docContent" ++ dMatchStmt := "SELECT root_id, MAX(CASE WHEN type = 'd' THEN (" + contentField + ") END) AS docContent, " ++ "CASE WHEN " + contentDocumentLikeFilter + " THEN 0 ELSE 1 END AS matchSource" +" FROM blocks WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter +- " GROUP BY root_id HAVING " + documentLikeFilter + "ORDER BY " + orderByLike.String() + " DESC, MAX(updated) DESC"+ " GROUP BY root_id HAVING " + documentLikeFilter ++ buildDocumentMatchOrderBy(orderByLike.String(), orderBy)cteStmt := "WITH docBlocks AS (" + dMatchStmt + ")"limit := " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)selectStmt := cteStmt + "\nSELECT *, " +"(" + contentField + ") AS concatContent, " +"(SELECT COUNT(root_id) FROM docBlocks) AS docs, " +- "(CASE WHEN (root_id IN (SELECT root_id FROM docBlocks) AND (" + blockLikeFilter + ")) THEN 1 ELSE 0 END) AS blockSort" ++ "(CASE WHEN (root_id IN (SELECT root_id FROM docBlocks) AND (" + blockLikeFilter + ")) THEN 1 ELSE 0 END) AS blockSort, " ++ "(SELECT matchSource FROM docBlocks WHERE docBlocks.root_id = blocks.root_id) AS matchSource" +" FROM blocks WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter +" AND (id IN (SELECT root_id FROM docBlocks " + limit + ") OR" +" (root_id IN (SELECT root_id FROM docBlocks" + limit + ") AND (" + blockLikeFilter + ")))"// 第二份对应外层 SELECT 的 WHEREargs = append(args, append(append([]any{}, boxArgs...), pathArgs...)...)- if strings.Contains(orderBy, "ORDER BY rank DESC") {- orderBy = buildOrderBy(query, 0, 0)- selectStmt += " " + strings.Replace(orderBy, "END ASC, ", "END ASC, blockSort ASC, ", 1)- } else if strings.Contains(orderBy, "ORDER BY rank") {- orderBy = buildOrderBy(query, 0, 0)- selectStmt += " " + strings.Replace(orderBy, "END ASC, ", "END ASC, blockSort DESC, ", 1)- } else if strings.Contains(orderBy, "sort ASC") {- selectStmt += " " + strings.Replace(orderBy, "END ASC, ", "END ASC, blockSort DESC, ", 1)- } else {- selectStmt += " " + orderBy- }+ selectStmt += " " + buildDocumentSearchOrderBy(rawQuery, orderBy)result, _ := sql.QueryNoLimitArgsInBox(selectStmt, boxID, args...)resultBlocks := sql.ToBlocks(result)if 0 < len(resultBlocks) {@@ -2228,6 +2359,40 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxAreturn}+func buildDocumentMatchOrderBy(matchScore string, orderBy int) string {+ stableOrder := ", root_id ASC"+ switch orderBy {+ case 1:+ return " ORDER BY MAX(created) ASC, matchSource ASC" + stableOrder+ case 2:+ return " ORDER BY MAX(created) DESC, matchSource ASC" + stableOrder+ case 3:+ return " ORDER BY MAX(updated) ASC, matchSource ASC" + stableOrder+ case 4:+ return " ORDER BY MAX(updated) DESC, matchSource ASC" + stableOrder+ case 6:+ return " ORDER BY matchSource ASC, " + matchScore + " ASC, MAX(updated) DESC" + stableOrder+ default:+ return " ORDER BY matchSource ASC, " + matchScore + " DESC, MAX(updated) DESC" + stableOrder+ }+}++func buildDocumentSearchOrderBy(query string, orderBy int) string {+ switch orderBy {+ case 1, 2, 3, 4:+ return buildOrderBy(query, 0, orderBy) + ", matchSource ASC, id ASC"+ }++ blockSort := "blockSort DESC"+ if 6 == orderBy {+ blockSort = "blockSort ASC"+ }+ ret := buildOrderBy(query, 0, 0)+ ret = strings.Replace(ret, "ORDER BY ", "ORDER BY matchSource ASC, ", 1)+ ret = strings.Replace(ret, "END ASC, ", "END ASC, "+blockSort+", ", 1)+ return ret + ", id ASC"+}+func buildSearchDocumentLikeFilter(field string, keywords []string) string {var ret strings.Builderfor i, keyword := range keywords {@@ -2242,6 +2407,26 @@ func buildSearchDocumentLikeFilter(field string, keywords []string) string {return ret.String()}+func buildSearchDocumentLikeFilterWithHPath(contentField, hPathField string, keywords []string) string {+ var ret strings.Builder+ for i, keyword := range keywords {+ normalizedKeyword := search.NormalizeSearchText(keyword, Conf.Search.CaseSensitive, Conf.Search.HanSensitiveVal())+ ret.WriteString("(")+ ret.WriteString(contentField)+ ret.WriteString(" LIKE '%")+ ret.WriteString(keyword)+ ret.WriteString("%' OR instr(")+ ret.WriteString(hPathField)+ ret.WriteString(", '")+ ret.WriteString(normalizedKeyword)+ ret.WriteString("') > 0)")+ if i < len(keywords)-1 {+ ret.WriteString(" AND ")+ }+ }+ return ret.String()+}+func highlightByFTS(query, typeFilter, id string) (ret []string) {return highlightByFTSInBox(query, typeFilter, id, "")}@@ -2440,12 +2625,7 @@ func fromSQLBlock(sqlBlock *sql.Block, terms string, beforeLen int) (block *Blocif "" != terms {hPathBeforeLen = -1}- hPath, _ := markSearch(sqlBlock.HPath, terms, hPathBeforeLen)- if !strings.HasPrefix(hPath, "/") {- hPath = "/" + hPath- }- block.HPath = hPath-+ markBlockHPath(block, sqlBlock.HPath, terms, hPathBeforeLen)if "" != block.Name {block.Name, _ = markSearch(block.Name, terms, 256)}@@ -2458,6 +2638,14 @@ func fromSQLBlock(sqlBlock *sql.Block, terms string, beforeLen int) (block *Blocreturn}+func markBlockHPath(block *Block, hPath, terms string, beforeLen int) {+ hPath, _ = markSearch(hPath, terms, beforeLen)+ if !strings.HasPrefix(hPath, "/") {+ hPath = "/" + hPath+ }+ block.HPath = hPath+}+func maxContent(content string, maxLen int) string {idx := strings.Index(content, "<mark>")if 128 < maxLen && maxLen <= idx {diff --git a/kernel/model/search_hpath_fts_test.go b/kernel/model/search_hpath_fts_test.goindex 131e499b23..a0170b6645 100644--- a/kernel/model/search_hpath_fts_test.go+++ b/kernel/model/search_hpath_fts_test.go@@ -21,6 +21,7 @@ package modelimport (gosql "database/sql""slices"+ "strings""testing")@@ -86,4 +87,19 @@ func TestFTSAndHPathMatchesIntegration(t *testing.T) {if 3 != matched || 2 != docs {t.Fatalf("FTS 与路径联合搜索统计错误:matches=%d, docs=%d", matched, docs)}++ snippetStmt, snippetArgs := buildFTSSnippetBlocksByRowIDQuery("\"Parent\"", []int64{1, 3})+ if !strings.Contains(snippetStmt, "snippet(blocks_fts") || strings.Contains(snippetStmt, "SELECT *") {+ t.Fatalf("FTS 结果应使用摘要投影:%s", snippetStmt)+ }+ snippetRows, err := testDB.Query(snippetStmt, snippetArgs...)+ if err != nil {+ t.Fatal(err)+ }+ if !snippetRows.Next() {+ t.Fatal("FTS 摘要查询应返回结果")+ }+ if err = snippetRows.Close(); err != nil {+ t.Fatal(err)+ }}diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex 232e55b72f..f2c5bb01a5 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -357,9 +357,15 @@ func TestBuildHPathContainsCondition(t *testing.T) {Conf.Search.CaseSensitive = falsecondition, arg = buildHPathContainsCondition("Parent%_\\")- if "hpath LIKE ? ESCAPE '\\'" != condition || "%Parent\\%\\_\\\\%" != arg {+ if "instr(search_normalize(hpath, 0, 1), ?) > 0" != condition || "parent%_\\" != arg {t.Fatalf("忽略大小写的路径条件错误:%q,%q", condition, arg)}++ Conf.Search.SetHanSensitive(false)+ condition, arg = buildHPathContainsCondition("詩經")+ if "instr(search_normalize(hpath, 0, 0), ?) > 0" != condition || "诗经" != arg {+ t.Fatalf("忽略繁简的路径条件错误:%q,%q", condition, arg)+ }}func TestBuildHPathSearchOrderBy(t *testing.T) {@@ -386,16 +392,44 @@ func TestBuildHPathSearchOrderBy(t *testing.T) {)}+func TestBuildDocumentSearchOrderBy(t *testing.T) {+ setSearchCaseSensitive(t, true)+ assertOrderBySequence(t, buildDocumentSearchOrderBy("Parent Child", 0),+ "matchSource ASC",+ "CASE",+ "blockSort DESC",+ "sort ASC",+ "updated DESC",+ "id ASC",+ )+ assertOrderBySequence(t, buildDocumentSearchOrderBy("Parent Child", 6),+ "matchSource ASC",+ "CASE",+ "blockSort ASC",+ "sort ASC",+ "updated DESC",+ "id ASC",+ )+ assertOrderBySequence(t, buildDocumentSearchOrderBy("Parent Child", 2),+ "created DESC",+ "matchSource ASC",+ "id ASC",+ )+}+func TestDocumentSearchFieldMatchesMultipleHPathLevels(t *testing.T) {setSearchCaseSensitive(t, true)testDB := newSearchHPathTestDB(t)insertSearchHPathTestBlock(t, testDB, "20260729121000-child01", "20260729121000-child01", "/Project/Parent/Child", "Child", "d")insertSearchHPathTestBlock(t, testDB, "20260729121001-block01", "20260729121000-child01", "/Project/Parent/Child", "Body keyword", "p")+ insertSearchHPathTestBlock(t, testDB, "20260729121002-content", "20260729121002-content", "/Other", "Project Parent keyword", "d")contentField := columnConcat()- documentSearchField := contentField + "||(CASE WHEN type = 'd' THEN hpath ELSE '' END)"- filter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+documentSearchField+")", []string{"Project", "Parent", "keyword"})- rows, err := testDB.Query("SELECT root_id FROM blocks WHERE type IN ('d', 'p') GROUP BY root_id HAVING " + filter)+ keywords := []string{"Project", "Parent", "keyword"}+ hPathField := "MAX(CASE WHEN type = 'd' THEN " + normalizedHPathSearchField("hpath") + " ELSE '' END)"+ contentFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+contentField+")", keywords)+ filter := buildSearchDocumentLikeFilterWithHPath("GROUP_CONCAT("+contentField+")", hPathField, keywords)+ rows, err := testDB.Query("SELECT root_id FROM blocks WHERE type IN ('d', 'p') AND root_id = '20260729121000-child01' GROUP BY root_id HAVING " + filter)if err != nil {t.Fatal(err)}@@ -408,19 +442,57 @@ func TestDocumentSearchFieldMatchesMultipleHPathLevels(t *testing.T) {t.Fatal(err)}if "20260729121000-child01" != rootID {- t.Fatalf("命中的文档错误:%q", rootID)+ t.Fatalf("路径辅助命中的文档错误:%q", rootID)}if err = rows.Close(); err != nil {t.Fatal(err)}- contentOnlyFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+contentField+")", []string{"Project", "Parent", "keyword"})+ matchScore := "((docContent LIKE '%Project%') + (docContent LIKE '%Parent%') + (docContent LIKE '%keyword%'))"+ sourceStmt := "SELECT root_id, CASE WHEN " + contentFilter + " THEN 0 ELSE 1 END AS matchSource, " ++ "MAX(CASE WHEN type = 'd' THEN (" + contentField + ") END) AS docContent FROM blocks " ++ "WHERE type IN ('d', 'p') GROUP BY root_id HAVING " + filter + buildDocumentMatchOrderBy(matchScore, 0)+ rows, err = testDB.Query(sourceStmt)+ if err != nil {+ t.Fatal(err)+ }+ var sources []int+ var sourceRootIDs []string+ for rows.Next() {+ var source int+ var docContent string+ if err = rows.Scan(&rootID, &source, &docContent); err != nil {+ t.Fatal(err)+ }+ sourceRootIDs = append(sourceRootIDs, rootID)+ sources = append(sources, source)+ }+ if err = rows.Close(); err != nil {+ t.Fatal(err)+ }+ if !slices.Equal(sources, []int{0, 1}) ||+ !slices.Equal(sourceRootIDs, []string{"20260729121002-content", "20260729121000-child01"}) {+ t.Fatalf("正文与路径辅助文档排序错误:roots=%v, sources=%v", sourceRootIDs, sources)+ }++ contentOnlyFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+contentField+")", keywords)var count intif err = testDB.QueryRow("SELECT COUNT(*) FROM (SELECT root_id FROM blocks WHERE type IN ('d', 'p') GROUP BY root_id HAVING " + contentOnlyFilter + ")").Scan(&count); err != nil {t.Fatal(err)}- if 0 != count {- t.Fatalf("关闭路径搜索后不应命中父文档关键词:%d", count)+ if 1 != count {+ t.Fatalf("关闭路径搜索后只能命中正文文档:%d", count)+ }++ Conf.Search.SetHanSensitive(false)+ insertSearchHPathTestBlock(t, testDB, "20260729121003-child02", "20260729121003-child02", "/詩經/Child", "Child", "d")+ hPathField = "MAX(CASE WHEN type = 'd' THEN " + normalizedHPathSearchField("hpath") + " ELSE '' END)"+ filter = buildSearchDocumentLikeFilterWithHPath("GROUP_CONCAT("+contentField+")", hPathField, []string{"诗经", "Child"})+ if err = testDB.QueryRow("SELECT COUNT(*) FROM (SELECT root_id FROM blocks WHERE type = 'd' GROUP BY root_id HAVING " + filter + ")").Scan(&count); err != nil {+ t.Fatal(err)+ }+ if 1 != count {+ t.Fatalf("多关键词路径搜索应支持繁简等价匹配:%d", count)}}diff --git a/kernel/search/hanconv.go b/kernel/search/hanconv.goindex 97dd86dfb1..df8455f682 100644--- a/kernel/search/hanconv.go+++ b/kernel/search/hanconv.go@@ -64,3 +64,19 @@ func hanInsensitiveRegexp(k string) string {}return b.String()}++// NormalizeSearchText 按搜索设置归一化文本,用于全文索引之外的文本匹配。+func NormalizeSearchText(text string, caseSensitive, hanSensitive bool) string {+ if !hanSensitive {+ text = strings.Map(func(r rune) rune {+ if simplified, ok := hanTradToSimp[r]; ok {+ return simplified+ }+ return r+ }, text)+ }+ if !caseSensitive {+ text = strings.ToLower(text)+ }+ return text+}diff --git a/kernel/search/hanconv_test.go b/kernel/search/hanconv_test.goindex d270e370eb..72b3e92cec 100644--- a/kernel/search/hanconv_test.go+++ b/kernel/search/hanconv_test.go@@ -51,6 +51,21 @@ func TestHanInsensitiveRegexp(t *testing.T) {}}+func TestNormalizeSearchText(t *testing.T) {+ if result := NormalizeSearchText("詩經 ABC", true, true); "詩經 ABC" != result {+ t.Fatalf("区分大小写和繁简时不应转换文本:%q", result)+ }+ if result := NormalizeSearchText("詩經 ABC", false, true); "詩經 abc" != result {+ t.Fatalf("忽略大小写时转换错误:%q", result)+ }+ if result := NormalizeSearchText("詩經 ABC", true, false); "诗经 ABC" != result {+ t.Fatalf("忽略繁简时转换错误:%q", result)+ }+ if result := NormalizeSearchText("詩經 ABC", false, false); "诗经 abc" != result {+ t.Fatalf("同时忽略大小写和繁简时转换错误:%q", result)+ }+}+func TestEncloseHighlightingHanInsensitive(t *testing.T) {old := util.SearchHanSensitivedefer func() { util.SearchHanSensitive = old }()diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex a910898d18..49154eb2e3 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -44,6 +44,7 @@ import (_ "github.com/mattn/go-sqlite3""github.com/siyuan-note/eventbus""github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/search""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -73,7 +74,13 @@ func init() {sql.Register("sqlite3_extended", &sqlite3.SQLiteDriver{ConnectHook: func(conn *sqlite3.SQLiteConn) error {- return conn.RegisterFunc("regexp", regex, true)+ if err := conn.RegisterFunc("regexp", regex, true); err != nil {+ return err+ }+ normalizeSearchText := func(text string, caseSensitive, hanSensitive int) string {+ return search.NormalizeSearchText(text, 0 != caseSensitive, 0 != hanSensitive)+ }+ return conn.RegisterFunc("search_normalize", normalizeSearchText, true)},})}