An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support searching documents by hierarchical paths https://github.com/siyuan-note/siyuan/issues/18305
Danielfa44649fa731
diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex 2ed090c51f..08d6c842c7 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -1408,6 +1408,7 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCoorderBy: config.sort,page: config.page || 1,pageSize: 32,+ searchHPath: !config.hasReplace,};// 限定在单个加密 box 内搜索时带 notebook,让内核走加密 db;跨 box 或全局搜索走原函数const idPaths = config.idPath || [];diff --git a/kernel/api/search.go b/kernel/api/search.goindex 2403de0aca..6dcc226e93 100644--- a/kernel/api/search.go+++ b/kernel/api/search.go@@ -546,6 +546,10 @@ func fullTextSearchBlock(c *gin.Context) {var blocks []*model.Blockvar matchedBlockCount, matchedRootCount, pageCount intvar docMode bool+ searchHPath := true+ if value, ok := arg["searchHPath"].(bool); ok {+ searchHPath = value+ }// 加密笔记本的全文搜索走 InBox 版(查加密 content db + blocks_fts)if notebook != "" && model.IsEncryptedBox(notebook) {if !model.IsBoxUnlocked(notebook) {@@ -553,9 +557,9 @@ func fullTextSearchBlock(c *gin.Context) {ret.Msg = "encrypted notebook locked"return}- blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBox(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, notebook)+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBoxWithHPath(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, notebook, searchHPath)} else {- blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlock(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize)+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockWithHPath(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, searchHPath)}if model.IsReadOnlyRoleContext(c) {publishAccess := model.GetPublishAccess()diff --git a/kernel/model/search.go b/kernel/model/search.goindex 8d107c6078..000e1c8efd 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -629,7 +629,7 @@ func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,// `Replace All` is no longer affected by pagination https://github.com/siyuan-note/siyuan/issues/8265// 替换目标始终使用未分组的块级结果,分组仅影响搜索结果展示// https://github.com/siyuan-note/siyuan/issues/10825- blocks, _, _, _, _ := FullTextSearchBlockInBox(keyword, boxes, paths, types, subTypes, method, 0, 0, 1, math.MaxInt, boxID)+ blocks, _, _, _, _ := FullTextSearchBlockInBoxWithHPath(keyword, boxes, paths, types, subTypes, method, 0, 0, 1, math.MaxInt, boxID, false)for _, block := range blocks {ids = append(ids, block.ID)}@@ -1268,12 +1268,22 @@ func mergeSamePreNext(n *ast.Node) {// orderBy: 0:按块类型(默认),1:按创建时间升序,2:按创建时间降序,3:按更新时间升序,4:按更新时间降序,5:按内容顺序(仅在按文档分组时),6:按相关度升序,7:按相关度降序// groupBy:0:不分组,1:按文档分组func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {- return FullTextSearchBlockInBox(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, "")+ return FullTextSearchBlockWithHPath(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, true)+}++// FullTextSearchBlockWithHPath 搜索内容块,并可控制是否搜索文档层级路径。+func FullTextSearchBlockWithHPath(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {+ return FullTextSearchBlockInBoxWithHPath(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, "", searchHPath)}// FullTextSearchBlockInBox 与 FullTextSearchBlock 一致,但按 boxID 路由到加密 db 或全局 db。// 加密笔记本内搜索时传入 boxID,所有 sql/treenode 查询走加密 db;boxID 为空时 fall-through 全局 db。func FullTextSearchBlockInBox(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {+ return FullTextSearchBlockInBoxWithHPath(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, boxID, true)+}++// FullTextSearchBlockInBoxWithHPath 与 FullTextSearchBlockInBox 一致,并可控制是否搜索文档层级路径。+func FullTextSearchBlockInBoxWithHPath(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {ret = []*Block{}if "" == query {return@@ -1331,11 +1341,16 @@ func FullTextSearchBlockInBox(query string, boxes, paths []string, types, subTypblocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize, boxID)} else {if 2 > len(strings.Split(strings.TrimSpace(query), " ")) {- query = stringQuery(query)- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)+ rawQuery := strings.TrimSpace(query)+ query = stringQuery(rawQuery)+ if "" != rawQuery && searchHPath && isDocumentSearchEnabled(types) {+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSAndHPathInBox(rawQuery, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, boxID)+ } else {+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)+ }} 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)+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID, searchHPath)}}}@@ -1743,6 +1758,13 @@ func buildTypeFilter(types, subTypes map[string]bool, alias ...string) string {return "(" + strings.Join(clauses, " OR ") + ")"}+func isDocumentSearchEnabled(types map[string]bool) bool {+ if nil != types {+ return types["document"]+ }+ return Conf.Search.Document+}+func sqlQuoteJoin(items []string) string {quoted := make([]string, len(items))for i, item := range items {@@ -2010,6 +2032,114 @@ func fullTextSearchByFTSInBox(query, boxFilter, pathFilter string, boxArgs, pathreturn}+func 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 += " " + buildHPathSearchOrderBy(rawQuery, orderBy)+ stmt += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)+ result, err := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)+ if err != nil {+ logging.LogErrorf("query blocks by FTS and hpath failed: %s", err)+ ret = []*Block{}+ return+ }++ sqlBlocks := sql.ToBlocks(result)+ ret = fromSQLBlocks(&sqlBlocks, rawQuery, beforeLen)+ if 1 > len(ret) {+ ret = []*Block{}+ }++ countStmt := cte + " SELECT COUNT(*) AS matches, COUNT(DISTINCT b.root_id) AS docs" ++ " FROM matches JOIN blocks b ON b.rowid = matches.block_rowid"+ countResult, err := sql.QueryNoLimitArgsInBox(countStmt, boxID, args...)+ if err != nil {+ logging.LogErrorf("count blocks by FTS and hpath failed: %s", err)+ return+ }+ if 0 < len(countResult) {+ matchedBlockCount = int(countResult[0]["matches"].(int64))+ matchedRootCount = int(countResult[0]["docs"].(int64))+ }+ 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)+ ftsMatches := "SELECT rowid AS block_rowid, rank AS fts_rank FROM " + table ++ " WHERE (`" + table + "` MATCH '" + columnFilter() + ":(" + query + ")') AND " + typeFilter ++ boxFilter + pathFilter + ignoreFilter+ pathMatches := "SELECT rowid AS block_rowid, NULL AS fts_rank, 1 AS match_source, " ++ "length(hpath) - length(replace(hpath, '/', '')) AS path_level FROM blocks" ++ " WHERE type = 'd' AND " + hPathCondition + boxFilter + pathFilter + ignoreFilter ++ " AND NOT EXISTS (SELECT 1 FROM fts_matches WHERE fts_matches.block_rowid = blocks.rowid)"+ cte = "WITH fts_matches AS MATERIALIZED (" + ftsMatches + "), matches AS (" ++ "SELECT block_rowid, fts_rank, 0 AS match_source, 0 AS path_level FROM fts_matches UNION ALL " ++ pathMatches + ")"++ args = append(args, boxArgs...)+ args = append(args, pathArgs...)+ args = append(args, hPathArg)+ args = append(args, boxArgs...)+ args = append(args, pathArgs...)+ return+}++func buildHPathContainsCondition(query string) (condition, arg string) {+ if Conf.Search.CaseSensitive {+ return "instr(hpath, ?) > 0", query+ }+ return "hpath LIKE ? ESCAPE '\\'", "%" + escapeSearchDocLikePattern(query) + "%"+}++func buildHPathSearchOrderBy(query string, orderBy int) string {+ stableOrder := ", b.id ASC"+ switch orderBy {+ case 1:+ return "ORDER BY b.created ASC, matches.match_source ASC" + stableOrder+ case 2:+ return "ORDER BY b.created DESC, matches.match_source ASC" + stableOrder+ case 3:+ return "ORDER BY b.updated ASC, matches.match_source ASC" + stableOrder+ case 4:+ return "ORDER BY b.updated DESC, matches.match_source ASC" + stableOrder+ case 5:+ return "ORDER BY b.sort ASC, matches.match_source ASC" + stableOrder+ case 6:+ return "ORDER BY matches.match_source ASC, matches.fts_rank DESC, " + hPathOnlyOrderBy() + stableOrder+ case 7:+ exactContent := buildExactSearchOrderCondition("b.content", query)+ clause := "ORDER BY matches.match_source ASC, CASE " ++ "WHEN " + exactContent + " AND b.type = 'd' THEN 10 " ++ "WHEN " + exactContent + " AND b.type = 'h' THEN 20 " ++ "ELSE 65535 END ASC, matches.fts_rank, " + hPathOnlyOrderBy()+ return clause + stableOrder+ default:+ exactName := buildExactSearchOrderCondition("b.name", query)+ exactAlias := buildExactSearchOrderCondition("b.alias", query)+ exactContent := buildExactSearchOrderCondition("b.content", query)+ escapedQuery := strings.ReplaceAll(query, "'", "''")+ clause := "ORDER BY matches.match_source ASC, CASE " ++ "WHEN " + exactName + " THEN 10 " ++ "WHEN " + exactAlias + " THEN 20 " ++ "WHEN " + exactContent + " AND b.type = 'd' THEN 30 " ++ "WHEN b.content LIKE '%${keyword}%' AND b.type = 'd' THEN 40 " ++ "WHEN b.name LIKE '%${keyword}%' THEN 50 " ++ "WHEN b.alias LIKE '%${keyword}%' THEN 60 " ++ "WHEN " + exactContent + " AND b.type = 'h' THEN 70 " ++ "WHEN b.content LIKE '%${keyword}%' AND b.type = 'h' THEN 80 " ++ "ELSE 65535 END ASC, " + hPathOnlyOrderBy() + ", b.sort ASC, b.updated DESC"+ clause = strings.ReplaceAll(clause, "${keyword}", escapedQuery)+ return clause + stableOrder+ }+}++func hPathOnlyOrderBy() string {+ return "CASE WHEN matches.match_source = 1 THEN matches.path_level END ASC, " ++ "CASE WHEN matches.match_source = 1 THEN b.hpath END ASC"+}+func fullTextSearchCountByFTS(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string) (matchedBlockCount, matchedRootCount int) {return fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, "")}@@ -2031,21 +2161,24 @@ func fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter string, boxArgs,}func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {- return fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, "")+ 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) (ret []*Block, matchedBlockCount, matchedRootCount int) {+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) {query = strings.ReplaceAll(query, "'", "''") // 不需要转义双引号,因为条件都是通过单引号包裹的,只需要转义单引号即可keywords := strings.Split(query, " ")contentField := columnConcat()- var likeFilter string+ documentSearchField := contentField+ if searchHPath {+ documentSearchField += "||(CASE WHEN type = 'd' THEN hpath ELSE '' END)"+ }+ documentLikeFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+documentSearchField+")", keywords)+ blockLikeFilter := buildSearchDocumentLikeFilter(contentField, keywords)var orderByLike strings.BuilderorderByLike.WriteString("(")for i, keyword := range keywords {- likeFilter += "GROUP_CONCAT(" + contentField + ") LIKE '%" + keyword + "%'"orderByLike.WriteString("(docContent LIKE '%" + keyword + "%')")if i < len(keywords)-1 {- likeFilter += " AND "orderByLike.WriteString(" + ")}}@@ -2055,17 +2188,16 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxAargs := append(append([]any{}, boxArgs...), pathArgs...)dMatchStmt := "SELECT root_id, MAX(CASE WHEN type = 'd' THEN (" + contentField + ") END) AS docContent" +" FROM blocks WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter +- " GROUP BY root_id HAVING " + likeFilter + "ORDER BY " + orderByLike.String() + " DESC, MAX(updated) DESC"+ " GROUP BY root_id HAVING " + documentLikeFilter + "ORDER BY " + orderByLike.String() + " DESC, MAX(updated) DESC"cteStmt := "WITH docBlocks AS (" + dMatchStmt + ")"- likeFilter = strings.ReplaceAll(likeFilter, "GROUP_CONCAT("+contentField+")", "concatContent")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 (" + strings.ReplaceAll(likeFilter, "concatContent", contentField) + ")) 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" +" 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 (" + likeFilter + ")))"+ " (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") {@@ -2096,6 +2228,20 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxAreturn}+func buildSearchDocumentLikeFilter(field string, keywords []string) string {+ var ret strings.Builder+ for i, keyword := range keywords {+ ret.WriteString(field)+ ret.WriteString(" LIKE '%")+ ret.WriteString(keyword)+ ret.WriteString("%'")+ if i < len(keywords)-1 {+ ret.WriteString(" AND ")+ }+ }+ return ret.String()+}+func highlightByFTS(query, typeFilter, id string) (ret []string) {return highlightByFTSInBox(query, typeFilter, id, "")}@@ -2290,7 +2436,11 @@ func fromSQLBlock(sqlBlock *sql.Block, terms string, beforeLen int) (block *Bloc}}- hPath, _ := markSearch(sqlBlock.HPath, "", 18)+ hPathBeforeLen := 18+ if "" != terms {+ hPathBeforeLen = -1+ }+ hPath, _ := markSearch(sqlBlock.HPath, terms, hPathBeforeLen)if !strings.HasPrefix(hPath, "/") {hPath = "/" + hPath}diff --git a/kernel/model/search_hpath_fts_test.go b/kernel/model/search_hpath_fts_test.gonew file mode 100644index 0000000000..131e499b23--- /dev/null+++ b/kernel/model/search_hpath_fts_test.go@@ -0,0 +1,89 @@+//go:build fts5++// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ gosql "database/sql"+ "slices"+ "testing"+)++func TestFTSAndHPathMatchesIntegration(t *testing.T) {+ setSearchCaseSensitive(t, true)+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")+ if err != nil {+ t.Fatal(err)+ }+ testDB.SetMaxOpenConns(1)+ t.Cleanup(func() {+ testDB.Close()+ })+ if _, err = testDB.Exec("CREATE TABLE blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated)"); err != nil {+ t.Fatal(err)+ }+ if _, err = testDB.Exec("CREATE VIRTUAL TABLE blocks_fts USING fts5(id UNINDEXED, parent_id UNINDEXED, root_id UNINDEXED, hash UNINDEXED, box UNINDEXED, path UNINDEXED, hpath UNINDEXED, name, alias, memo, tag, content, fcontent, markdown UNINDEXED, length UNINDEXED, type UNINDEXED, subtype UNINDEXED, ial, sort UNINDEXED, created UNINDEXED, updated UNINDEXED, content='blocks', content_rowid='rowid')"); err != nil {+ t.Fatal(err)+ }+ insertSearchHPathTestBlock(t, testDB, "20260729122000-parent1", "20260729122000-parent1", "/Parent", "Parent", "d")+ insertSearchHPathTestBlock(t, testDB, "20260729122001-child01", "20260729122001-child01", "/Parent/Child", "Child", "d")+ insertSearchHPathTestBlock(t, testDB, "20260729122002-block01", "20260729122001-child01", "/Parent/Child", "Parent body", "p")+ if _, err = testDB.Exec("INSERT INTO blocks_fts(blocks_fts) VALUES('rebuild')"); err != nil {+ t.Fatal(err)+ }++ cte, args := buildFTSAndHPathMatchesCTE("Parent", "\"Parent\"", "", "", nil, nil, "(type IN ('d', 'p'))", "")+ stmt := cte + " SELECT b.id, matches.match_source FROM matches JOIN blocks b ON b.rowid = matches.block_rowid " ++ buildHPathSearchOrderBy("Parent", 0)+ rows, err := testDB.Query(stmt, args...)+ if err != nil {+ t.Fatal(err)+ }+ var ids []string+ var sources []int+ for rows.Next() {+ var id string+ var source int+ if err = rows.Scan(&id, &source); err != nil {+ t.Fatal(err)+ }+ ids = append(ids, id)+ sources = append(sources, source)+ }+ if err = rows.Close(); err != nil {+ t.Fatal(err)+ }++ expectedIDs := []string{"20260729122000-parent1", "20260729122002-block01", "20260729122001-child01"}+ if !slices.Equal(ids, expectedIDs) {+ t.Fatalf("FTS 与路径联合搜索结果错误:got %v, want %v", ids, expectedIDs)+ }+ if !slices.Equal(sources, []int{0, 0, 1}) {+ t.Fatalf("FTS 与路径联合搜索来源错误:%v", sources)+ }++ countStmt := cte + " SELECT COUNT(*) AS matches, COUNT(DISTINCT b.root_id) AS docs" ++ " FROM matches JOIN blocks b ON b.rowid = matches.block_rowid"+ var matched, docs int+ if err = testDB.QueryRow(countStmt, args...).Scan(&matched, &docs); err != nil {+ t.Fatal(err)+ }+ if 3 != matched || 2 != docs {+ t.Fatalf("FTS 与路径联合搜索统计错误:matches=%d, docs=%d", matched, docs)+ }+}diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex 19babf76d0..232e55b72f 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -298,6 +298,157 @@ func TestBuildExactSearchOrderConditionEscapesKeyword(t *testing.T) {}}+func TestFTSAndHPathMatchesDeduplicateAndSort(t *testing.T) {+ setSearchCaseSensitive(t, true)+ testDB := newSearchHPathTestDB(t)+ insertSearchHPathTestBlock(t, testDB, "20260729120000-parent1", "20260729120000-parent1", "/Parent", "Parent", "d")+ insertSearchHPathTestBlock(t, testDB, "20260729120001-child01", "20260729120001-child01", "/Parent/Child", "Child", "d")+ insertSearchHPathTestBlock(t, testDB, "20260729120002-block01", "20260729120001-child01", "/Parent/Child", "Parent body", "p")++ cte, args := buildFTSAndHPathMatchesCTE("Parent", "\"Parent\"", "", "", nil, nil, "(type IN ('d', 'p'))", "")+ if countPlaceholder(cte) != len(args) {+ t.Fatalf("候选查询占位符数量错误:%q,参数:%v", cte, args)+ }+ if len(args) != 1 || "Parent" != args[0] {+ t.Fatalf("路径搜索参数错误:%v", args)+ }+ assertOrderBySequence(t, cte,+ "fts_matches AS MATERIALIZED",+ "instr(hpath, ?) > 0",+ "NOT EXISTS (SELECT 1 FROM fts_matches",+ )++ stmt := "WITH matches(block_rowid, fts_rank, match_source, path_level) AS (" ++ "VALUES (1, -10.0, 0, 0), (3, -1.0, 0, 0), (2, NULL, 1, 2)) " ++ "SELECT b.id, matches.match_source FROM matches JOIN blocks b ON b.rowid = matches.block_rowid " ++ buildHPathSearchOrderBy("Parent", 0)+ rows, err := testDB.Query(stmt)+ if err != nil {+ t.Fatal(err)+ }+ defer rows.Close()++ var ids []string+ var sources []int+ for rows.Next() {+ var id string+ var source int+ if err = rows.Scan(&id, &source); err != nil {+ t.Fatal(err)+ }+ ids = append(ids, id)+ sources = append(sources, source)+ }+ expectedIDs := []string{"20260729120000-parent1", "20260729120002-block01", "20260729120001-child01"}+ if !slices.Equal(ids, expectedIDs) {+ t.Fatalf("单关键词路径搜索排序错误:got %v, want %v", ids, expectedIDs)+ }+ if !slices.Equal(sources, []int{0, 0, 1}) {+ t.Fatalf("单关键词路径搜索来源错误:%v", sources)+ }+}++func TestBuildHPathContainsCondition(t *testing.T) {+ setSearchCaseSensitive(t, true)+ condition, arg := buildHPathContainsCondition("Parent%_\\")+ if "instr(hpath, ?) > 0" != condition || "Parent%_\\" != arg {+ t.Fatalf("区分大小写的路径条件错误:%q,%q", condition, arg)+ }++ Conf.Search.CaseSensitive = false+ condition, arg = buildHPathContainsCondition("Parent%_\\")+ if "hpath LIKE ? ESCAPE '\\'" != condition || "%Parent\\%\\_\\\\%" != arg {+ t.Fatalf("忽略大小写的路径条件错误:%q,%q", condition, arg)+ }+}++func TestBuildHPathSearchOrderBy(t *testing.T) {+ setSearchCaseSensitive(t, true)+ assertOrderBySequence(t, buildHPathSearchOrderBy("Parent", 0),+ "matches.match_source ASC",+ "CASE",+ "matches.path_level",+ "b.sort ASC",+ "b.updated DESC",+ "b.id ASC",+ )+ assertOrderBySequence(t, buildHPathSearchOrderBy("Parent", 2),+ "b.created DESC",+ "matches.match_source ASC",+ "b.id ASC",+ )+ assertOrderBySequence(t, buildHPathSearchOrderBy("Parent", 7),+ "matches.match_source ASC",+ "CASE",+ "matches.fts_rank",+ "matches.path_level",+ "b.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")++ 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)+ if err != nil {+ t.Fatal(err)+ }+ defer rows.Close()+ if !rows.Next() {+ t.Fatal("多关键词应能跨多层路径和正文命中文档")+ }+ var rootID string+ if err = rows.Scan(&rootID); err != nil {+ t.Fatal(err)+ }+ if "20260729121000-child01" != rootID {+ t.Fatalf("命中的文档错误:%q", rootID)+ }+ if err = rows.Close(); err != nil {+ t.Fatal(err)+ }++ contentOnlyFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+contentField+")", []string{"Project", "Parent", "keyword"})+ var count int+ if 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)+ }+}++func newSearchHPathTestDB(t *testing.T) *gosql.DB {+ t.Helper()+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")+ if err != nil {+ t.Fatal(err)+ }+ testDB.SetMaxOpenConns(1)+ t.Cleanup(func() {+ testDB.Close()+ })+ if _, err = testDB.Exec("CREATE TABLE blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated)"); err != nil {+ t.Fatal(err)+ }+ return testDB+}++func insertSearchHPathTestBlock(t *testing.T, testDB *gosql.DB, id, rootID, hPath, content, blockType string) {+ t.Helper()+ _, err := testDB.Exec("INSERT INTO blocks VALUES (?, '', ?, '', '20260729120000-box000', '/"+rootID+".sy', ?, '', '', '', '', ?, '', '', 0, ?, '', '', 0, '20260729120000', '20260729120000')",+ id, rootID, hPath, content, blockType)+ if err != nil {+ t.Fatal(err)+ }+}+func setSearchCaseSensitive(t *testing.T, caseSensitive bool) {t.Helper()previousConf := Confdiff --git a/kernel/sql/database.go b/kernel/sql/database.goindex fdfbdf4b9b..a910898d18 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -107,6 +107,9 @@ func initDatabase(forceRebuild bool) {if util.DatabaseVer == getDatabaseVer() {// 老库版本一致但缺少新加的列时,做幂等迁移(不升 DatabaseVer,避免全库重建丢失已嵌入向量)migrateBlockEmbeddingsSchema()+ if err := ensureBlocksDocHPathIndex(db); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create document hpath index failed: %s", err)+ }recoverIndexQueue()return}@@ -167,6 +170,10 @@ func initDBTables() {logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create index [idx_blocks_root_id_id_hash] failed: %s", err)}+ if err = ensureBlocksDocHPathIndex(db); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create document hpath index failed: %s", err)+ }+if err = initFTSBlocks(); err != nil {if isRecoverableDBFileError(err) {logging.LogWarnf("create fts tables failed: %s, retrying with clean database...", err)@@ -1379,6 +1386,11 @@ func batchUpdateHPath(tx *sql.Tx, tree *parse.Tree, context map[string]any) (errreturn}+func ensureBlocksDocHPathIndex(database *sql.DB) (err error) {+ _, err = database.Exec("CREATE INDEX IF NOT EXISTS idx_blocks_doc_hpath ON blocks(hpath) WHERE type = 'd'")+ return+}+func CloseDatabase() {closeIndexQueue()// 退出时删除所有已打开的加密 db 文件:加密索引可由 box.Index() 全量重建,@@ -1967,6 +1979,9 @@ func initEncryptedDBTables(boxDB *sql.DB) (err error) {return}}+ if err = ensureBlocksDocHPathIndex(boxDB); err != nil {+ return+ }// FTS5 external-content 虚拟表,tokenize 与全局保持一致(siyuan 分词器)ftsStmt := "CREATE VIRTUAL TABLE IF NOT EXISTS blocks_fts USING fts5(id UNINDEXED, parent_id UNINDEXED, root_id UNINDEXED, hash UNINDEXED, box UNINDEXED, path UNINDEXED, hpath UNINDEXED, name, alias, memo, tag, content, fcontent, markdown UNINDEXED, length UNINDEXED, type UNINDEXED, subtype UNINDEXED, ial, sort UNINDEXED, created UNINDEXED, updated UNINDEXED, content='blocks', content_rowid='rowid', tokenize=\"" + ftsTokenize() + "\")"if _, err = boxDB.Exec(ftsStmt); err != nil {