Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Semantic search using AI embeddings https://github.com/siyuan-note/siyuan/issues/17788

Daniel501a0af7e78b
diff --git a/kernel/api/search.go b/kernel/api/search.go
index c730ea9102..3f84af55c7 100644
--- a/kernel/api/search.go
+++ b/kernel/api/search.go
@@ -550,9 +550,9 @@ func semanticSearchBlock(c *gin.Context) {
return
}
- page, pageSize, query, _, boxes, types, subTypes, _, _, _ := parseSearchBlockArgs(arg)
+ page, pageSize, query, paths, boxes, types, subTypes, _, _, _ := parseSearchBlockArgs(arg)
- blocks, matchedBlockCount, matchedRootCount, pageCount := model.SemanticSearchBlock(query, boxes, nil, types, subTypes, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount, pageCount := model.SemanticSearchBlock(query, boxes, paths, types, subTypes, page, pageSize)
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
blocks = model.FilterBlocksByPublishAccess(c, publishAccess, blocks)
diff --git a/kernel/model/embedding.go b/kernel/model/embedding.go
index 3dd0bed803..710f26f010 100644
--- a/kernel/model/embedding.go
+++ b/kernel/model/embedding.go
@@ -305,6 +305,12 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes ma
}
queryVec := vectors[0]
+ boxFilter := buildBoxesFilter(boxes, "be.")
+ pathFilter := buildPathsFilter(paths, "be.")
+ typeFilter := buildTypeFilter(types, subTypes, "b.")
+ hasFilter := 0 < len(boxes) || 0 < len(paths) || 0 < len(types)
+ hasTypeFilter := 0 < len(types)
+
numWorkers := runtime.GOMAXPROCS(0)
if numWorkers < 1 {
numWorkers = 1
@@ -318,7 +324,17 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes ma
cursor := int64(0)
for {
- q := fmt.Sprintf("SELECT rowid, id, embedding FROM block_embeddings WHERE embedding IS NOT NULL AND length(embedding) > 0 AND rowid > %d ORDER BY rowid LIMIT %d", cursor, scanSize)
+ var q string
+ if hasFilter {
+ q = fmt.Sprintf("SELECT be.rowid, be.id, be.embedding FROM block_embeddings be JOIN blocks b ON be.id = b.id WHERE be.embedding IS NOT NULL AND length(be.embedding) > 0 AND be.rowid > %d", cursor)
+ if hasTypeFilter {
+ q += " AND " + typeFilter
+ }
+ q += boxFilter + pathFilter
+ q += fmt.Sprintf(" ORDER BY be.rowid LIMIT %d", scanSize)
+ } else {
+ q = fmt.Sprintf("SELECT rowid, id, embedding FROM block_embeddings WHERE embedding IS NOT NULL AND length(embedding) > 0 AND rowid > %d ORDER BY rowid LIMIT %d", cursor, scanSize)
+ }
rows, qErr := sql.QueryNoLimit(q)
if qErr != nil {
logging.LogErrorf("query embeddings for search failed: %s", qErr)
diff --git a/kernel/model/search.go b/kernel/model/search.go
index ac9c7d4ba4..ae0be850bc 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -1332,14 +1332,18 @@ func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes ma
return
}
-func buildBoxesFilter(boxes []string) string {
+func buildBoxesFilter(boxes []string, alias ...string) string {
if 0 == len(boxes) {
return ""
}
+ prefix := ""
+ if 0 < len(alias) && "" != alias[0] {
+ prefix = alias[0]
+ }
builder := bytes.Buffer{}
builder.WriteString(" AND (")
for i, box := range boxes {
- builder.WriteString(fmt.Sprintf("box = '%s'", box))
+ builder.WriteString(fmt.Sprintf("%sbox = '%s'", prefix, box))
if i < len(boxes)-1 {
builder.WriteString(" OR ")
}
@@ -1348,14 +1352,18 @@ func buildBoxesFilter(boxes []string) string {
return builder.String()
}
-func buildPathsFilter(paths []string) string {
+func buildPathsFilter(paths []string, alias ...string) string {
if 0 == len(paths) {
return ""
}
+ prefix := ""
+ if 0 < len(alias) && "" != alias[0] {
+ prefix = alias[0]
+ }
builder := bytes.Buffer{}
builder.WriteString(" AND (")
for i, path := range paths {
- builder.WriteString(fmt.Sprintf("path LIKE '%s%%'", path))
+ builder.WriteString(fmt.Sprintf("%spath LIKE '%s%%'", prefix, path))
if i < len(paths)-1 {
builder.WriteString(" OR ")
}
@@ -1407,7 +1415,11 @@ func buildOrderBy(query string, method, orderBy int) string {
// Example output:
//
// (type IN ('p','c') OR (type = 'h' AND subtype IN ('h1','h2')))
-func buildTypeFilter(types, subTypes map[string]bool) string {
+func buildTypeFilter(types, subTypes map[string]bool, alias ...string) string {
+ prefix := ""
+ if 0 < len(alias) && "" != alias[0] {
+ prefix = alias[0]
+ }
s := conf.NewSearch()
if err := copier.Copy(s, Conf.Search); err != nil {
logging.LogErrorf("copy search conf failed: %s", err)
@@ -1493,8 +1505,8 @@ func buildTypeFilter(types, subTypes map[string]bool) string {
if 0 == len(headingSubs) {
simpleTypes = append(simpleTypes, headingAbbr)
} else {
- clauses = append(clauses, fmt.Sprintf("(type = '%s' AND subtype IN (%s))",
- headingAbbr, sqlQuoteJoin(headingSubs)))
+ clauses = append(clauses, fmt.Sprintf("(%stype = '%s' AND %ssubtype IN (%s))",
+ prefix, headingAbbr, prefix, sqlQuoteJoin(headingSubs)))
}
}
@@ -1509,17 +1521,16 @@ func buildTypeFilter(types, subTypes map[string]bool) string {
if 0 == len(listSubs) {
simpleTypes = append(simpleTypes, listTypes...)
} else {
- clauses = append(clauses, fmt.Sprintf("(type IN (%s) AND subtype IN (%s))",
- sqlQuoteJoin(listTypes), sqlQuoteJoin(listSubs)))
+ clauses = append(clauses, fmt.Sprintf("(%stype IN (%s) AND %ssubtype IN (%s))",
+ prefix, sqlQuoteJoin(listTypes), prefix, sqlQuoteJoin(listSubs)))
}
}
if 0 < len(simpleTypes) {
- clauses = append([]string{"type IN (" + sqlQuoteJoin(simpleTypes) + ")"}, clauses...)
+ clauses = append([]string{prefix + "type IN (" + sqlQuoteJoin(simpleTypes) + ")"}, clauses...)
}
if 0 == len(clauses) {
- // Match nothing without producing invalid SQL when concatenated after AND.
return "(1 = 0)"
}
return "(" + strings.Join(clauses, " OR ") + ")"