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 exact document match ranking when searching for a move destination https://github.com/siyuan-note/siyuan/issues/18303
Danielc96500bf2a0b
diff --git a/kernel/model/file.go b/kernel/model/file.goindex 865bd817a7..6352eae276 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -155,6 +155,7 @@ func (box *Box) moveCorruptedData(filePath string) {func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[string]string) {ret = []map[string]string{}+ var results []searchDocResultvar deck *riff.Deckvar deckBlockIDs []string@@ -177,50 +178,41 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[var rootBlocks []*sql.Blockif ast.IsNodeIDPattern(keyword) {- rootBlocks = sql.QueryRootBlockByCondition("id='"+keyword+"'", 1)+ rootBlocks = sql.QueryRootBlockByCondition("id = ?", keyword, 1, keyword)} else {keywords := strings.Fields(keyword)if 0 < len(keywords) {for _, box := range boxes {if util.ContainsSubStr(box.Name, keywords) {+ data := map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon}if flashcard {newFlashcardCount, dueFlashcardCount, flashcardCount := countBoxFlashcard(box.ID, deck, deckBlockIDs)- if 0 < flashcardCount {- ret = append(ret, map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon, "newFlashcardCount": strconv.Itoa(newFlashcardCount), "dueFlashcardCount": strconv.Itoa(dueFlashcardCount), "flashcardCount": strconv.Itoa(flashcardCount)})+ if 1 > flashcardCount {+ continue}- } else {- ret = append(ret, map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon})+ data["newFlashcardCount"] = strconv.Itoa(newFlashcardCount)+ data["dueFlashcardCount"] = strconv.Itoa(dueFlashcardCount)+ data["flashcardCount"] = strconv.Itoa(flashcardCount)}+ results = append(results, searchDocResult{data: data, exact: box.Name == keyword})}}- var condition strings.Builder- for i, k := range keywords {- condition.WriteString("(hpath LIKE '%" + k + "%'")- namCondition := Conf.Search.NAMFilter(k)- condition.WriteString(" " + namCondition)- condition.WriteString(")")-- if i < len(keywords)-1 {- condition.WriteString(" AND ")- }- }-- for _, excludeID := range excludeIDs {- condition.WriteString(fmt.Sprintf(" AND path NOT LIKE '%%%s%%' ", excludeID))- }-- rootBlocks = sql.QueryRootBlockByCondition(condition.String(), Conf.Search.Limit)+ condition, args := buildSearchDocsCondition(keywords, excludeIDs, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo)+ rootBlocks = sql.QueryRootBlockByCondition(condition, keyword, Conf.Search.Limit, args...)} else {for _, box := range boxes {+ data := map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon}if flashcard {newFlashcardCount, dueFlashcardCount, flashcardCount := countBoxFlashcard(box.ID, deck, deckBlockIDs)- if 0 < flashcardCount {- ret = append(ret, map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon, "newFlashcardCount": strconv.Itoa(newFlashcardCount), "dueFlashcardCount": strconv.Itoa(dueFlashcardCount), "flashcardCount": strconv.Itoa(flashcardCount)})+ if 1 > flashcardCount {+ continue}- } else {- ret = append(ret, map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon})+ data["newFlashcardCount"] = strconv.Itoa(newFlashcardCount)+ data["dueFlashcardCount"] = strconv.Itoa(dueFlashcardCount)+ data["flashcardCount"] = strconv.Itoa(flashcardCount)}+ results = append(results, searchDocResult{data: data})}}}@@ -234,22 +226,82 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[continue}hPath := b.Name + rootBlock.HPath+ data := map[string]string{"path": rootBlock.Path, "hPath": hPath, "box": rootBlock.Box, "boxIcon": b.Icon}if flashcard {newFlashcardCount, dueFlashcardCount, flashcardCount := countTreeFlashcard(rootBlock.ID, deck, deckBlockIDs)- if 0 < flashcardCount {- ret = append(ret, map[string]string{"path": rootBlock.Path, "hPath": hPath, "box": rootBlock.Box, "boxIcon": b.Icon, "newFlashcardCount": strconv.Itoa(newFlashcardCount), "dueFlashcardCount": strconv.Itoa(dueFlashcardCount), "flashcardCount": strconv.Itoa(flashcardCount)})+ if 1 > flashcardCount {+ continue}- } else {- ret = append(ret, map[string]string{"path": rootBlock.Path, "hPath": hPath, "box": rootBlock.Box, "boxIcon": b.Icon})+ data["newFlashcardCount"] = strconv.Itoa(newFlashcardCount)+ data["dueFlashcardCount"] = strconv.Itoa(dueFlashcardCount)+ data["flashcardCount"] = strconv.Itoa(flashcardCount)}+ results = append(results, searchDocResult{data: data, exact: rootBlock.Content == keyword})}- sort.Slice(ret, func(i, j int) bool {- return ret[i]["hPath"] < ret[j]["hPath"]- })+ sortSearchDocResults(results)+ for _, result := range results {+ ret = append(ret, result.data)+ }return}+func sortSearchDocResults(results []searchDocResult) {+ sort.SliceStable(results, func(i, j int) bool {+ if results[i].exact != results[j].exact {+ return results[i].exact+ }+ return results[i].data["hPath"] < results[j].data["hPath"]+ })+}++type searchDocResult struct {+ data map[string]string+ exact bool+}++func buildSearchDocsCondition(keywords, excludeIDs []string, searchName, searchAlias, searchMemo bool) (condition string, args []any) {+ var ret strings.Builder+ for i, keyword := range keywords {+ pattern := "%" + escapeSearchDocLikePattern(keyword) + "%"+ ret.WriteString("(hpath LIKE ? ESCAPE '\\'")+ args = append(args, pattern)+ if searchName {+ ret.WriteString(" OR name LIKE ? ESCAPE '\\'")+ args = append(args, pattern)+ }+ if searchAlias {+ ret.WriteString(" OR alias LIKE ? ESCAPE '\\'")+ args = append(args, pattern)+ }+ if searchMemo {+ ret.WriteString(" OR memo LIKE ? ESCAPE '\\'")+ args = append(args, pattern)+ }+ ret.WriteString(")")+ if i < len(keywords)-1 {+ ret.WriteString(" AND ")+ }+ }+ for _, excludeID := range excludeIDs {+ ret.WriteString(" AND path NOT LIKE ? ESCAPE '\\'")+ args = append(args, "%"+escapeSearchDocLikePattern(excludeID)+"%")+ }+ return ret.String(), args+}++func escapeSearchDocLikePattern(s string) string {+ var ret strings.Builder+ ret.Grow(len(s))+ for _, r := range s {+ if '%' == r || '_' == r || '\\' == r {+ ret.WriteRune('\\')+ }+ ret.WriteRune(r)+ }+ return ret.String()+}+type FileInfo struct {path stringname stringdiff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex b182496d45..91f17304b7 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -151,3 +151,41 @@ func TestMoveDocsRejectsInvalidPathsBeforeMoving(t *testing.T) {})}}++func TestSortSearchDocResults(t *testing.T) {+ results := []searchDocResult{+ {data: map[string]string{"hPath": "A/初中数学"}},+ {data: map[string]string{"hPath": "Z/数学"}, exact: true},+ {data: map[string]string{"hPath": "A/数学/"}, exact: true},+ {data: map[string]string{"hPath": "B/高等数学"}},+ }++ sortSearchDocResults(results)+ expected := []string{"A/数学/", "Z/数学", "A/初中数学", "B/高等数学"}+ for i, hPath := range expected {+ if hPath != results[i].data["hPath"] {+ t.Fatalf("unexpected search result order at %d: got %q, want %q", i, results[i].data["hPath"], hPath)+ }+ }+}++func TestBuildSearchDocsCondition(t *testing.T) {+ condition, args := buildSearchDocsCondition([]string{"O'Reilly", "100%_done\\file"}, []string{"20260720000000-abc_def"}, true, true, true)+ if strings.Contains(condition, "O'Reilly") || strings.Contains(condition, "100%_done") {+ t.Fatalf("search condition should contain placeholders instead of keywords: %q", condition)+ }+ if placeholderCount := strings.Count(condition, "?"); placeholderCount != len(args) {+ t.Fatalf("search condition placeholder/arg mismatch: %d placeholders, %d args", placeholderCount, len(args))+ }++ expectedArgs := []string{+ "%O'Reilly%", "%O'Reilly%", "%O'Reilly%", "%O'Reilly%",+ "%100\\%\\_done\\\\file%", "%100\\%\\_done\\\\file%", "%100\\%\\_done\\\\file%", "%100\\%\\_done\\\\file%",+ "%20260720000000-abc\\_def%",+ }+ for i, expected := range expectedArgs {+ if actual := args[i].(string); expected != actual {+ t.Fatalf("unexpected search arg at %d: got %q, want %q", i, actual, expected)+ }+ }+}diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.goindex 1e24223d94..0198335330 100644--- a/kernel/sql/block_query.go+++ b/kernel/sql/block_query.go@@ -70,9 +70,11 @@ func queryBlockHashes(tx *sql.Tx, rootID string) (ret map[string]string) {return}-func QueryRootBlockByCondition(condition string, limit int) (ret []*Block) {- sqlStmt := "SELECT *, length(hpath) - length(replace(hpath, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition + " ORDER BY box DESC,lv ASC LIMIT " + strconv.Itoa(limit)- rows, err := query(sqlStmt)+func QueryRootBlockByCondition(condition, exactKeyword string, limit int, args ...any) (ret []*Block) {+ sqlStmt := "SELECT *, length(hpath) - length(replace(hpath, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition ++ " ORDER BY CASE WHEN content = ? THEN 0 ELSE 1 END ASC, box DESC, lv ASC LIMIT ?"+ args = append(args, exactKeyword, limit)+ rows, err := query(sqlStmt, args...)if err != nil {logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)return