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: Prioritize direct matches in document path search https://github.com/siyuan-note/siyuan/issues/18305
Danieledfc6f5fee32
diff --git a/kernel/model/search.go b/kernel/model/search.goindex bbe49dc64e..40dd006b67 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -2648,44 +2648,10 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxArawQuery := queryquery = strings.ReplaceAll(query, "'", "''") // 不需要转义双引号,因为条件都是通过单引号包裹的,只需要转义单引号即可keywords := strings.Split(query, " ")- contentField := columnConcat()- contentDocumentLikeFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+contentField+")", keywords)- documentLikeFilter := contentDocumentLikeFilter- if searchHPath {- hPathField := "MAX(CASE WHEN type = 'd' THEN " + normalizedHPathSearchField("hpath") + " ELSE '' END)"- documentLikeFilter = buildSearchDocumentLikeFilterWithHPath("GROUP_CONCAT("+contentField+")", hPathField, keywords)- }- blockLikeFilter := buildSearchDocumentLikeFilter(contentField, keywords)- var orderByLike strings.Builder- orderByLike.WriteString("(")- for i, keyword := range keywords {- orderByLike.WriteString("(docContent LIKE '%" + keyword + "%')")- if i < len(keywords)-1 {- orderByLike.WriteString(" + ")- }- }- orderByLike.WriteString(")")- // box/path 过滤子句在下方 dMatchStmt 与 selectStmt 中各出现一次,绑定参数需按出现顺序收集两份。- // 第一份对应 CTE 内的 WHERE+ // box/path 过滤子句在文档匹配与最终块查询中各出现一次,绑定参数需按出现顺序收集两份。args := append(append([]any{}, boxArgs...), pathArgs...)- 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 +- 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, " +- "(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...)...)- selectStmt += " " + buildDocumentSearchOrderBy(rawQuery, orderBy)+ selectStmt := buildDocumentSearchStatement(rawQuery, keywords, typeFilter, boxFilter, pathFilter, ignoreFilter, orderBy, page, pageSize, searchHPath)result, _ := sql.QueryNoLimitArgsInBox(selectStmt, boxID, args...)resultBlocks := sql.ToBlocks(result)if 0 < len(resultBlocks) {@@ -2698,7 +2664,9 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxAterms = strings.ReplaceAll(terms, "''", "'")for i, resultBlock := range resultBlocks {if 1 == result[i]["matchSource"].(int64) {- ret = append(ret, fromHPathSearchSQLBlock(resultBlock, terms, beforeLen))+ docContent, _ := result[i]["docContent"].(string)+ contentTerms := matchedSearchTerms(docContent, terms)+ ret = append(ret, fromHPathSearchSQLBlockWithContentTerms(resultBlock, terms, contentTerms, beforeLen))} else {ret = append(ret, fromSQLBlock(resultBlock, terms, beforeLen))}@@ -2709,40 +2677,91 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxAreturn}+func buildDocumentSearchStatement(rawQuery string, keywords []string, typeFilter, boxFilter, pathFilter, ignoreFilter string, orderBy, page, pageSize int, searchHPath bool) string {+ contentField := columnConcat()+ contentDocumentLikeFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+contentField+")", keywords)+ documentLikeFilter := contentDocumentLikeFilter+ if searchHPath {+ hPathField := "MAX(CASE WHEN type = 'd' THEN " + normalizedHPathSearchField("hpath") + " ELSE '' END)"+ documentLikeFilter = buildSearchDocumentLikeFilterWithHPath("GROUP_CONCAT("+contentField+")", hPathField, keywords)+ }+ blockLikeFilter := buildSearchDocumentLikeFilter(contentField, keywords)+ docContentField := "MAX(CASE WHEN type = 'd' THEN (" + contentField + ") END)"+ docMatchScore := buildDocumentMatchScore(docContentField, keywords)+ dMatchStmt := "SELECT root_id, " + docContentField + " AS docContent, " ++ "CASE WHEN " + contentDocumentLikeFilter + " THEN 0 ELSE 1 END AS matchSource, " ++ docMatchScore + " AS docMatchScore, MAX(created) AS docCreated, MAX(updated) AS docUpdated" ++ " FROM blocks WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter ++ " GROUP BY root_id HAVING " + documentLikeFilter+ limit := " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)+ pagedDocsStmt := "SELECT root_id AS docRootID, docContent, matchSource, docMatchScore, docCreated, docUpdated FROM docBlocks" ++ buildDocumentMatchOrderBy("docMatchScore", orderBy) + limit+ cteStmt := "WITH docBlocks AS (" + dMatchStmt + "), pagedDocs AS (" + pagedDocsStmt + ")"+ selectStmt := cteStmt + "\nSELECT blocks.*, " ++ "(" + contentField + ") AS concatContent, " ++ "(SELECT COUNT(root_id) FROM docBlocks) AS docs, " ++ "(CASE WHEN (" + blockLikeFilter + ") THEN 1 ELSE 0 END) AS blockSort, " ++ "pagedDocs.docContent AS docContent, pagedDocs.matchSource AS matchSource, pagedDocs.docMatchScore AS docMatchScore" ++ " FROM blocks JOIN pagedDocs ON pagedDocs.docRootID = blocks.root_id" ++ " WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter ++ " AND (id = root_id OR (" + blockLikeFilter + "))"+ selectStmt += " " + buildDocumentSearchOrderBy(rawQuery, orderBy)+ return selectStmt+}+func buildDocumentMatchOrderBy(matchScore string, orderBy int) string {- stableOrder := ", root_id ASC"+ stableOrder := ", docRootID ASC"switch orderBy {case 1:- return " ORDER BY MAX(created) ASC, matchSource ASC" + stableOrder+ return " ORDER BY docCreated ASC, matchSource ASC, " + matchScore + " DESC" + stableOrdercase 2:- return " ORDER BY MAX(created) DESC, matchSource ASC" + stableOrder+ return " ORDER BY docCreated DESC, matchSource ASC, " + matchScore + " DESC" + stableOrdercase 3:- return " ORDER BY MAX(updated) ASC, matchSource ASC" + stableOrder+ return " ORDER BY docUpdated ASC, matchSource ASC, " + matchScore + " DESC" + stableOrdercase 4:- return " ORDER BY MAX(updated) DESC, matchSource ASC" + stableOrder+ return " ORDER BY docUpdated DESC, matchSource ASC, " + matchScore + " DESC" + stableOrdercase 6:- return " ORDER BY matchSource ASC, " + matchScore + " ASC, MAX(updated) DESC" + stableOrder+ return " ORDER BY matchSource ASC, " + matchScore + " ASC, docUpdated DESC" + stableOrderdefault:- return " ORDER BY matchSource ASC, " + matchScore + " DESC, MAX(updated) DESC" + stableOrder+ return " ORDER BY matchSource ASC, " + matchScore + " DESC, docUpdated 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"+ return buildOrderBy(query, 0, orderBy) + ", matchSource ASC, docMatchScore DESC, id ASC"}blockSort := "blockSort DESC"+ matchScore := "docMatchScore DESC"if 6 == orderBy {blockSort = "blockSort ASC"+ matchScore = "docMatchScore ASC"}ret := buildOrderBy(query, 0, 0)- ret = strings.Replace(ret, "ORDER BY ", "ORDER BY matchSource ASC, ", 1)+ ret = strings.Replace(ret, "ORDER BY ", "ORDER BY matchSource ASC, "+matchScore+", ", 1)ret = strings.Replace(ret, "END ASC, ", "END ASC, "+blockSort+", ", 1)return ret + ", id ASC"}+func buildDocumentMatchScore(field string, keywords []string) string {+ var ret strings.Builder+ ret.WriteString("(")+ for i, keyword := range keywords {+ ret.WriteString("(")+ ret.WriteString(field)+ ret.WriteString(" LIKE '%")+ ret.WriteString(keyword)+ ret.WriteString("%')")+ if i < len(keywords)-1 {+ ret.WriteString(" + ")+ }+ }+ ret.WriteString(")")+ return ret.String()+}+func buildSearchDocumentLikeFilter(field string, keywords []string) string {var ret strings.Builderfor i, keyword := range keywords {@@ -2911,6 +2930,17 @@ func markSearch(text string, keyword string, beforeLen int) (marked string, scorreturn}+func matchedSearchTerms(text, terms string) string {+ var matched []string+ for _, term := range search.SplitKeyword(terms) {+ pos, _ := search.MarkText(text, term, -1, Conf.Search.CaseSensitive)+ if -1 < pos {+ matched = append(matched, term)+ }+ }+ return strings.Join(matched, search.TermSep)+}+func fromSQLBlocks(sqlBlocks *[]*sql.Block, terms string, beforeLen int) (ret []*Block) {for _, sqlBlock := range *sqlBlocks {ret = append(ret, fromSQLBlock(sqlBlock, terms, beforeLen))@@ -2997,8 +3027,12 @@ func markBlockHPath(block *Block, hPath, terms string, beforeLen int) {}func fromHPathSearchSQLBlock(sqlBlock *sql.Block, terms string, beforeLen int) (block *Block) {- block = fromSQLBlock(sqlBlock, "", beforeLen)- markBlockHPath(block, sqlBlock.HPath, terms, -1)+ return fromHPathSearchSQLBlockWithContentTerms(sqlBlock, terms, "", beforeLen)+}++func fromHPathSearchSQLBlockWithContentTerms(sqlBlock *sql.Block, hPathTerms, contentTerms string, beforeLen int) (block *Block) {+ block = fromSQLBlock(sqlBlock, contentTerms, beforeLen)+ markBlockHPath(block, sqlBlock.HPath, hPathTerms, -1)return}diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex d246c1afc2..7375b3cb4a 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -405,6 +405,35 @@ func TestFromHPathSearchSQLBlockOnlyMarksHPath(t *testing.T) {}}+func TestFromMixedHPathSearchSQLBlockMarksDirectContent(t *testing.T) {+ setSearchCaseSensitive(t, true)+ terms := "从这里" + search.TermSep + "会员"+ contentTerms := matchedSearchTerms("会员特权", terms)+ if "会员" != contentTerms {+ t.Fatalf("文档自身直接命中的关键词错误:%q", contentTerms)+ }++ sqlBlock := &sql.Block{+ ID: "20260731160000-hpath03",+ RootID: "20260731160000-hpath03",+ HPath: "/思源笔记用户指南/请/从这里开始/会员特权",+ Name: "从这里",+ Content: "会员特权",+ Type: "d",+ }+ block := fromHPathSearchSQLBlockWithContentTerms(sqlBlock, terms, contentTerms, 36)+ if "<mark>会员</mark>特权" != block.Content {+ t.Fatalf("混合命中应高亮文档自身直接命中的关键词:%q", block.Content)+ }+ if strings.Contains(block.Name, "<mark>") {+ t.Fatalf("路径关键词不应扩展高亮到其他文档字段:%q", block.Name)+ }+ if !strings.Contains(block.HPath, "<mark>从这里</mark>") ||+ !strings.Contains(block.HPath, "<mark>会员</mark>") {+ t.Fatalf("混合命中应高亮全部路径关键词:%q", block.HPath)+ }+}+func TestFilterSelfHPathPreservesHighlight(t *testing.T) {setSearchCaseSensitive(t, true)multipleKeywords := fromHPathSearchSQLBlock(&sql.Block{@@ -471,6 +500,7 @@ func TestBuildDocumentSearchOrderBy(t *testing.T) {setSearchCaseSensitive(t, true)assertOrderBySequence(t, buildDocumentSearchOrderBy("Parent Child", 0),"matchSource ASC",+ "docMatchScore DESC","CASE","blockSort DESC","sort ASC",@@ -479,6 +509,7 @@ func TestBuildDocumentSearchOrderBy(t *testing.T) {)assertOrderBySequence(t, buildDocumentSearchOrderBy("Parent Child", 6),"matchSource ASC",+ "docMatchScore ASC","CASE","blockSort ASC","sort ASC",@@ -488,16 +519,98 @@ func TestBuildDocumentSearchOrderBy(t *testing.T) {assertOrderBySequence(t, buildDocumentSearchOrderBy("Parent Child", 2),"created DESC","matchSource ASC",+ "docMatchScore DESC","id ASC",)}+func TestBuildDocumentMatchOrderBy(t *testing.T) {+ assertOrderBySequence(t, buildDocumentMatchOrderBy("docMatchScore", 0),+ "matchSource ASC",+ "docMatchScore DESC",+ "docUpdated DESC",+ "docRootID ASC",+ )+ assertOrderBySequence(t, buildDocumentMatchOrderBy("docMatchScore", 6),+ "matchSource ASC",+ "docMatchScore ASC",+ "docUpdated DESC",+ "docRootID ASC",+ )+ assertOrderBySequence(t, buildDocumentMatchOrderBy("docMatchScore", 2),+ "docCreated DESC",+ "matchSource ASC",+ "docMatchScore DESC",+ "docRootID ASC",+ )+}++func TestDocumentSearchFinalOrderPrioritizesDirectMatches(t *testing.T) {+ setSearchCaseSensitive(t, true)+ testDB := newSearchHPathTestDB(t)+ insertSearchHPathTestBlock(t, testDB, "path-only", "path-only", "/从这里开始/会员特权/资源文件图床", "资源文件图床", "d")+ insertSearchHPathTestBlock(t, testDB, "direct", "direct", "/从这里开始/会员特权", "会员特权", "d")+ if _, err := testDB.Exec("UPDATE blocks SET created = '20260731120002' WHERE id = 'path-only'"); err != nil {+ t.Fatal(err)+ }+ if _, err := testDB.Exec("UPDATE blocks SET created = '20260731120001' WHERE id = 'direct'"); err != nil {+ t.Fatal(err)+ }++ queryResult := func(query string, keywords []string, orderBy, pageSize int) (ids []string, sources, scores []int) {+ stmt := buildDocumentSearchStatement(query, keywords, "type IN ('d')", "", "", "", orderBy, 1, pageSize, true)+ rows, err := testDB.Query("SELECT id, docContent, matchSource, docMatchScore FROM (" + stmt + ")")+ if err != nil {+ t.Fatal(err)+ }+ for rows.Next() {+ var id string+ var docContent string+ var source, score int+ if err = rows.Scan(&id, &docContent, &source, &score); err != nil {+ t.Fatal(err)+ }+ ids = append(ids, id)+ sources = append(sources, source)+ scores = append(scores, score)+ }+ if err = rows.Close(); err != nil {+ t.Fatal(err)+ }+ return+ }++ ids, sources, scores := queryResult("从这里 会员", []string{"从这里", "会员"}, 0, 32)+ if !slices.Equal(ids, []string{"direct", "path-only"}) {+ t.Fatalf("默认排序应优先返回直接命中关键词的文档:%v", ids)+ }+ if !slices.Equal(sources, []int{1, 1}) || !slices.Equal(scores, []int{1, 0}) {+ t.Fatalf("路径辅助文档直接命中分数错误:sources=%v, scores=%v", sources, scores)+ }++ ids, _, _ = queryResult("从这里 会员特权", []string{"从这里", "会员特权"}, 0, 32)+ if !slices.Equal(ids, []string{"direct", "path-only"}) {+ t.Fatalf("完整文档关键词应优先返回直接命中的文档:%v", ids)+ }++ ids, _, _ = queryResult("从这里 会员", []string{"从这里", "会员"}, 0, 1)+ if !slices.Equal(ids, []string{"direct"}) {+ t.Fatalf("分页选择应优先包含直接命中关键词的文档:%v", ids)+ }++ ids, _, _ = queryResult("从这里 会员", []string{"从这里", "会员"}, 2, 32)+ if !slices.Equal(ids, []string{"path-only", "direct"}) {+ t.Fatalf("按创建时间降序时应保持时间优先:%v", ids)+ }+}+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")+ insertSearchHPathTestBlock(t, testDB, "20260729121003-mixed01", "20260729121003-mixed01", "/Project/Parent/keyword", "keyword", "d")contentField := columnConcat()keywords := []string{"Project", "Parent", "keyword"}@@ -523,31 +636,41 @@ func TestDocumentSearchFieldMatchesMultipleHPathLevels(t *testing.T) {t.Fatal(err)}- 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)+ docContentField := "MAX(CASE WHEN type = 'd' THEN (" + contentField + ") END)"+ matchScore := buildDocumentMatchScore(docContentField, keywords)+ docBlocksStmt := "SELECT root_id, CASE WHEN " + contentFilter + " THEN 0 ELSE 1 END AS matchSource, " ++ docContentField + " AS docContent, " + matchScore + " AS docMatchScore, " ++ "MAX(created) AS docCreated, MAX(updated) AS docUpdated FROM blocks " ++ "WHERE type IN ('d', 'p') GROUP BY root_id HAVING " + filter+ sourceStmt := "WITH docBlocks AS (" + docBlocksStmt + ") " ++ "SELECT root_id AS docRootID, matchSource, docContent, docMatchScore, docCreated, docUpdated FROM docBlocks" ++ buildDocumentMatchOrderBy("docMatchScore", 0)rows, err = testDB.Query(sourceStmt)if err != nil {t.Fatal(err)}var sources []int+ var scores []intvar sourceRootIDs []stringfor rows.Next() {var source int+ var score intvar docContent string- if err = rows.Scan(&rootID, &source, &docContent); err != nil {+ var docCreated, docUpdated string+ if err = rows.Scan(&rootID, &source, &docContent, &score, &docCreated, &docUpdated); err != nil {t.Fatal(err)}sourceRootIDs = append(sourceRootIDs, rootID)sources = append(sources, source)+ scores = append(scores, score)}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)+ if !slices.Equal(sources, []int{0, 1, 1}) ||+ !slices.Equal(scores, []int{3, 1, 0}) ||+ !slices.Equal(sourceRootIDs, []string{"20260729121002-content", "20260729121003-mixed01", "20260729121000-child01"}) {+ t.Fatalf("正文与路径辅助文档排序错误:roots=%v, sources=%v, scores=%v", sourceRootIDs, sources, scores)}contentOnlyFilter := buildSearchDocumentLikeFilter("GROUP_CONCAT("+contentField+")", keywords)@@ -560,7 +683,7 @@ func TestDocumentSearchFieldMatchesMultipleHPathLevels(t *testing.T) {}Conf.Search.SetHanSensitive(false)- insertSearchHPathTestBlock(t, testDB, "20260729121003-child02", "20260729121003-child02", "/詩經/Child", "Child", "d")+ insertSearchHPathTestBlock(t, testDB, "20260729121004-child02", "20260729121004-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 {