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 recent sorting for document reference candidates https://github.com/siyuan-note/siyuan/issues/16468
Daniel6531225a1a21
diff --git a/kernel/model/search.go b/kernel/model/search.goindex dc2edd3dda..b3636d40d7 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -428,10 +428,10 @@ func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBractypeFilter := Conf.Search.TypeFilter()ignoreLines := getRefSearchIgnoreLines()- refs := sql.QueryRefsRecentInBox(onlyDoc, typeFilter, ignoreLines, boxID)- // 候选已按 refs.id DESC 兜底排序,这里再按"最近引用时间"精确排序:- // 有记录的目标块按时间戳降序排前,无记录的(历史数据)保持兜底序排后refUsed := GetRefUsed()+ refs := sql.QueryRefsRecentInBox(onlyDoc, typeFilter, ignoreLines, sortedRefUsedIDs(refUsed), boxID)+ // 查询阶段已将有使用记录的目标块放入候选集,这里再按最近引用时间精确排序。+ // 无记录的历史数据保持 refs.id DESC 兜底顺序。sort.SliceStable(refs, func(i, j int) bool {ti, oki := refUsed[refs[i].DefBlockID]tj, okj := refUsed[refs[j].DefBlockID]@@ -2280,6 +2280,27 @@ func fullTextSearchRefBlockInBox(keyword string, beforeLen int, onlyDoc bool, bo}func buildRefUsedOrderBy(refUsed map[string]int64) string {+ ids := sortedRefUsedIDs(refUsed)+ if 1 > len(ids) {+ return ""+ }++ buf := bytes.Buffer{}+ buf.WriteString("CASE id ")+ for i, id := range ids {+ buf.WriteString("WHEN '")+ buf.WriteString(id)+ buf.WriteString("' THEN ")+ buf.WriteString(strconv.Itoa(i))+ buf.WriteByte(' ')+ }+ buf.WriteString("ELSE ")+ buf.WriteString(strconv.Itoa(len(ids)))+ buf.WriteString(" END ASC, ")+ return buf.String()+}++func sortedRefUsedIDs(refUsed map[string]int64) (ret []string) {type refUsedEntry struct {id stringtimestamp int64@@ -2291,10 +2312,6 @@ func buildRefUsedOrderBy(refUsed map[string]int64) string {entries = append(entries, refUsedEntry{id: id, timestamp: timestamp})}}- if 1 > len(entries) {- return ""- }-sort.Slice(entries, func(i, j int) bool {if entries[i].timestamp == entries[j].timestamp {return entries[i].id > entries[j].id@@ -2302,19 +2319,10 @@ func buildRefUsedOrderBy(refUsed map[string]int64) string {return entries[i].timestamp > entries[j].timestamp})- buf := bytes.Buffer{}- buf.WriteString("CASE id ")- for i, entry := range entries {- buf.WriteString("WHEN '")- buf.WriteString(entry.id)- buf.WriteString("' THEN ")- buf.WriteString(strconv.Itoa(i))- buf.WriteByte(' ')+ for _, entry := range entries {+ ret = append(ret, entry.id)}- buf.WriteString("ELSE ")- buf.WriteString(strconv.Itoa(len(entries)))- buf.WriteString(" END ASC, ")- return buf.String()+ return}func extractID(content string) (ret string) {diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex 7375b3cb4a..58263a9d14 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -210,6 +210,23 @@ func TestBuildRefUsedOrderByEmpty(t *testing.T) {}}+func TestSortedRefUsedIDs(t *testing.T) {+ newestID := "20260714120000-newest1"+ higherID := "20260714110000-older01"+ lowerID := "20260714110000-newer01"+ ids := sortedRefUsedIDs(map[string]int64{+ lowerID: 100,+ newestID: 200,+ higherID: 100,+ "invalid-id": 300,+ })++ expected := []string{newestID, higherID, lowerID}+ if !slices.Equal(ids, expected) {+ t.Fatalf("最近引用块 ID 排序错误:%v", ids)+ }+}+func TestBuildOrderByPrioritizesExactDocumentAndHeading(t *testing.T) {setSearchCaseSensitive(t, true)diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.goindex d36a62ecfc..030fa4d1a2 100644--- a/kernel/sql/encrypted_query.go+++ b/kernel/sql/encrypted_query.go@@ -22,6 +22,7 @@ import ("database/sql""math""regexp"+ "strconv""strings""github.com/siyuan-note/logging"@@ -402,7 +403,7 @@ func QueryRefsByDefIDRefIDInBox(defBlockID, refBlockID, boxID string) (ret []*Re}// QueryRefsRecentInBox 按 boxID 路由查最近引用,用于加密笔记本内的块引搜索。-func QueryRefsRecentInBox(onlyDoc bool, typeFilter string, ignoreLines []string, boxID string) (ret []*Ref) {+func QueryRefsRecentInBox(onlyDoc bool, typeFilter string, ignoreLines, recentDefBlockIDs []string, boxID string) (ret []*Ref) {stmt := "SELECT r.* FROM refs AS r, blocks AS b WHERE b.id = r.def_block_id AND b.type IN " + typeFilterif onlyDoc {stmt = "SELECT r.* FROM refs AS r, blocks AS b WHERE b.id = r.def_block_id AND b.type = 'd'"@@ -415,8 +416,9 @@ func QueryRefsRecentInBox(onlyDoc bool, typeFilter string, ignoreLines []string,}stmt += buf.String()}- stmt += " GROUP BY r.def_block_id ORDER BY r.id DESC LIMIT 32"- rows, err := queryForBox(boxID, stmt)+ orderBy, args := buildRefsRecentOrderBy(recentDefBlockIDs)+ stmt += " GROUP BY r.def_block_id ORDER BY " + orderBy + " LIMIT 32"+ rows, err := queryForBox(boxID, stmt, args...)if err != nil {logging.LogErrorf("sql query failed: %s", err)return@@ -429,6 +431,25 @@ func QueryRefsRecentInBox(onlyDoc bool, typeFilter string, ignoreLines []string,return}+func buildRefsRecentOrderBy(recentDefBlockIDs []string) (ret string, args []any) {+ if 1 > len(recentDefBlockIDs) {+ return "r.id DESC", nil+ }++ buf := bytes.Buffer{}+ buf.WriteString("CASE r.def_block_id ")+ for i, id := range recentDefBlockIDs {+ buf.WriteString("WHEN ? THEN ")+ buf.WriteString(strconv.Itoa(i))+ buf.WriteByte(' ')+ args = append(args, id)+ }+ buf.WriteString("ELSE ")+ buf.WriteString(strconv.Itoa(len(recentDefBlockIDs)))+ buf.WriteString(" END ASC, r.id DESC")+ return buf.String(), args+}+// QueryChildRefDefIDsByRootDefIDInBox 按 rootDefID 查子引用定义,按 boxID 路由。func QueryChildRefDefIDsByRootDefIDInBox(rootDefID, boxID string) (ret map[string][]string) {ret = map[string][]string{}diff --git a/kernel/sql/encrypted_query_test.go b/kernel/sql/encrypted_query_test.goindex 599365c667..f085c09778 100644--- a/kernel/sql/encrypted_query_test.go+++ b/kernel/sql/encrypted_query_test.go@@ -62,6 +62,23 @@ func TestQueryRefsByDefIDInBoxContainsChildren(t *testing.T) {}}+func TestQueryRefsRecentInBoxPrioritizesUsageBeforeLimit(t *testing.T) {+ testDB, boxID := useEncryptedQueryTestDB(t)+ for i := 0; i < 40; i++ {+ defID := fmt.Sprintf("def-%02d", i)+ insertEncryptedQueryTestBlock(t, testDB, defID, "", defID, "d")+ insertEncryptedQueryTestRef(t, testDB, fmt.Sprintf("ref-%02d", i), defID, defID)+ }++ refs := QueryRefsRecentInBox(true, "('d')", nil, []string{"def-00"}, boxID)+ if 32 != len(refs) {+ t.Fatalf("最近引用查询数量错误:%d", len(refs))+ }+ if "def-00" != refs[0].DefBlockID {+ t.Fatalf("最近引用的文档未排在候选列表首位:%s", refs[0].DefBlockID)+ }+}+func TestExistRefByDefIDsSearchesGlobalAndEncryptedIndexes(t *testing.T) {globalDB, err := gosql.Open("sqlite3_extended", ":memory:")if nil != err {