Skip to content

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

:sparkles: Support public APIs for managing saved search criteria https://github.com/siyuan-note/siyuan/issues/18916

Daniel8e2e4e496570
diff --git a/app/src/search/menu.ts b/app/src/search/menu.ts
index 93389c3fd9..278fec1cdd 100644
--- a/app/src/search/menu.ts
+++ b/app/src/search/menu.ts
@@ -746,7 +746,9 @@ const configIsSame = (config: Config.IUILayoutTabSearchConfig, config2: Config.I
if (config2.group === config.group && config2.hPath === config.hPath && config2.hasReplace === config.hasReplace &&
config2.k === config.k && config2.method === config.method && config2.r === config.r &&
config2.sort === config.sort && objEquals(config2.types, config.types) &&
- objEquals(config2.replaceTypes, config.replaceTypes) && objEquals(config2.idPath, config.idPath)) {
+ objEquals({...getDefaultSubType(), ...config2.subTypes},
+ {...getDefaultSubType(), ...config.subTypes}) && objEquals(config2.replaceTypes, config.replaceTypes) &&
+ objEquals(config2.idPath, config.idPath)) {
return true;
}
return false;
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 6753e237b5..606422a22e 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -60,6 +60,10 @@
* [フィールドを削除](#フィールドを削除)
* [グローバルのフィールドソートを設定](#グローバルのフィールドソートを設定)
* [ビュー内のフィールドソートを設定](#ビュー内のフィールドソートを設定)
+* [検索](#検索)
+ * [保存済みの検索条件グループを取得](#保存済みの検索条件グループを取得)
+ * [検索条件グループを保存](#検索条件グループを保存)
+ * [検索条件グループを削除](#検索条件グループを削除)
* [SQL](#SQL)
* [SQLクエリを実行](#SQLクエリを実行)
* [トランザクションをフラッシュ](#トランザクションをフラッシュ)
@@ -2563,3 +2567,99 @@
"data": null
}
```
+
+## 検索
+
+保存済みの検索条件グループは、次のフィールドを使用します。
+
+* `name`:条件グループ名。条件グループの一意なキーとしても使用されます
+* `sort`:結果の並べ替え方法。`0` はブロックタイプ、`1` は作成日時の昇順、`2` は作成日時の降順、`3` は更新日時の昇順、`4` は更新日時の降順、`5` は内容順、`6` は関連度の昇順、`7` は関連度の降順です
+* `group`:グループ化方法。`0` はグループ化なし、`1` はドキュメント単位です
+* `hasReplace`:置換を有効にするかどうか
+* `method`:検索方法。`0` はキーワード、`1` はクエリ構文、`2` は SQL、`3` は正規表現、`4` はセマンティック検索です
+* `hPath`:人間が読める検索範囲のパス
+* `idPath`:検索範囲のパス配列
+* `k`:検索キーワード
+* `r`:置換キーワード
+* `types`:ブロックタイプのフラグ。`mathBlock`、`table`、`blockquote`、`superBlock`、`paragraph`、`document`、`heading`、`list`、`listItem`、`codeBlock`、`htmlBlock`、`embedBlock`、`databaseBlock`、`audioBlock`、`videoBlock`、`iframeBlock`、`widgetBlock`、`callout` を使用できます
+* `subTypes`:ブロックサブタイプのフラグ。`h1` から `h6` は見出しレベルを、`o`、`u`、`t` はそれぞれ番号付きリスト、箇条書きリスト、タスクリストを示します
+* `replaceTypes`:置換タイプのフラグ。`text`、`imgText`、`imgTitle`、`imgSrc`、`aText`、`aTitle`、`aHref`、`code`、`em`、`strong`、`inlineMath`、`inlineMemo`、`blockRef`、`fileAnnotationRef`、`kbd`、`mark`、`s`、`sub`、`sup`、`tag`、`u`、`docTitle`、`codeBlock`、`mathBlock`、`htmlBlock` を使用できます
+
+`types`、`subTypes`、`replaceTypes` で省略された真偽値フラグは `false` として扱われます。
+
+### 保存済みの検索条件グループを取得
+
+* `/api/storage/getCriteria`
+* パラメータなし
+* 戻り値:`data` は保存順に並んだ検索条件グループの配列です。保存済みの条件グループがない場合は空の配列になります
+* 読み取り専用ロールでは、条件グループが公開アクセス権限に基づいてフィルタリングされ、戻り値の `k` と `r` は空になります
+
+### 検索条件グループを保存
+
+条件グループを作成するか、同じ `name` の既存条件グループを完全に置き換えます。置き換えた条件グループの位置は維持され、新しい条件グループは末尾に追加されます。
+
+* `/api/storage/setCriterion`
+* 管理者ロールが必要です。読み取り専用モードでは使用できません
+* パラメータ
+
+ ```json
+ {
+ "criterion": {
+ "name": "公開ノート",
+ "sort": 0,
+ "group": 1,
+ "hasReplace": false,
+ "method": 0,
+ "hPath": "公開ノート",
+ "idPath": ["20210808180117-czj9bvb"],
+ "k": "",
+ "r": "",
+ "types": {
+ "document": true,
+ "paragraph": true
+ },
+ "subTypes": {
+ "h1": true
+ },
+ "replaceTypes": {
+ "text": true
+ }
+ }
+ }
+ ```
+
+ * `criterion`:保存する完全な検索条件グループ
+* 戻り値
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
+
+### 検索条件グループを削除
+
+指定した名前の条件グループを削除します。存在しない名前を指定した場合も成功として扱われます。
+
+* `/api/storage/removeCriterion`
+* 管理者ロールが必要です。読み取り専用モードでは使用できません
+* パラメータ
+
+ ```json
+ {
+ "name": "公開ノート"
+ }
+ ```
+
+ * `name`:条件グループ名
+* 戻り値
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
diff --git a/docs/API.md b/docs/API.md
index 17c8e20061..103f7875f4 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -60,6 +60,10 @@
* [Remove a field](#Remove-a-field)
* [Set global field sort](#Set-global-field-sort)
* [Set per-view field sort](#Set-per-view-field-sort)
+* [Search](#Search)
+ * [Get saved search criteria](#Get-saved-search-criteria)
+ * [Save a search criterion](#Save-a-search-criterion)
+ * [Remove a search criterion](#Remove-a-search-criterion)
* [SQL](#SQL)
* [Execute SQL query](#Execute-SQL-query)
* [Flush transaction](#Flush-transaction)
@@ -2574,3 +2578,99 @@ Reorders a column within a single view's layout (e.g. a table's column order), w
"data": null
}
```
+
+## Search
+
+Saved search criteria use the following fields:
+
+* `name`: Criterion name, which is also its unique key
+* `sort`: Result sorting method — `0` block type, `1` creation time ascending, `2` creation time descending, `3` update time ascending, `4` update time descending, `5` content order, `6` relevance ascending, `7` relevance descending
+* `group`: Grouping method — `0` no grouping, `1` group by document
+* `hasReplace`: Whether replacement is enabled
+* `method`: Search method — `0` keyword, `1` query syntax, `2` SQL, `3` regular expression, `4` semantic search
+* `hPath`: Human-readable search scope path
+* `idPath`: Search scope path array
+* `k`: Search keyword
+* `r`: Replacement keyword
+* `types`: Block type flags. Supported keys are `mathBlock`, `table`, `blockquote`, `superBlock`, `paragraph`, `document`, `heading`, `list`, `listItem`, `codeBlock`, `htmlBlock`, `embedBlock`, `databaseBlock`, `audioBlock`, `videoBlock`, `iframeBlock`, `widgetBlock`, and `callout`
+* `subTypes`: Block subtype flags. `h1` through `h6` select heading levels; `o`, `u`, and `t` select ordered, unordered, and task lists
+* `replaceTypes`: Replacement type flags. Supported keys are `text`, `imgText`, `imgTitle`, `imgSrc`, `aText`, `aTitle`, `aHref`, `code`, `em`, `strong`, `inlineMath`, `inlineMemo`, `blockRef`, `fileAnnotationRef`, `kbd`, `mark`, `s`, `sub`, `sup`, `tag`, `u`, `docTitle`, `codeBlock`, `mathBlock`, and `htmlBlock`
+
+Boolean flags omitted from `types`, `subTypes`, or `replaceTypes` are treated as `false`.
+
+### Get saved search criteria
+
+* `/api/storage/getCriteria`
+* No parameters
+* Return value: `data` is an array of saved search criteria in their saved order; it is an empty array when no criteria have been saved
+* For a read-only role, criteria are filtered by publish access permissions and the returned `k` and `r` values are cleared
+
+### Save a search criterion
+
+Creates a criterion or completely replaces the existing criterion with the same `name`. Replacing a criterion retains its current position; a new criterion is appended.
+
+* `/api/storage/setCriterion`
+* Administrator role required; unavailable in read-only mode
+* Parameters
+
+ ```json
+ {
+ "criterion": {
+ "name": "Public notes",
+ "sort": 0,
+ "group": 1,
+ "hasReplace": false,
+ "method": 0,
+ "hPath": "Public notes",
+ "idPath": ["20210808180117-czj9bvb"],
+ "k": "",
+ "r": "",
+ "types": {
+ "document": true,
+ "paragraph": true
+ },
+ "subTypes": {
+ "h1": true
+ },
+ "replaceTypes": {
+ "text": true
+ }
+ }
+ }
+ ```
+
+ * `criterion`: Complete search criterion to save
+* Return value
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
+
+### Remove a search criterion
+
+Removes the criterion with the specified name. Removing a name that does not exist is also considered successful.
+
+* `/api/storage/removeCriterion`
+* Administrator role required; unavailable in read-only mode
+* Parameters
+
+ ```json
+ {
+ "name": "Public notes"
+ }
+ ```
+
+ * `name`: Criterion name
+* Return value
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index 009ef6519e..4a3ae7d94c 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -60,6 +60,10 @@
* [移除字段](#移除字段)
* [设置全局字段排序](#设置全局字段排序)
* [设置视图内字段排序](#设置视图内字段排序)
+* [搜索](#搜索)
+ * [获取已保存的搜索条件组](#获取已保存的搜索条件组)
+ * [保存搜索条件组](#保存搜索条件组)
+ * [移除搜索条件组](#移除搜索条件组)
* [SQL](#SQL)
* [执行 SQL 查询](#执行-SQL-查询)
* [提交事务](#提交事务)
@@ -2563,3 +2567,99 @@
"data": null
}
```
+
+## 搜索
+
+已保存的搜索条件组使用以下字段:
+
+* `name`:条件组名称,同时也是条件组的唯一键
+* `sort`:结果排序方式,`0` 为按块类型,`1` 为按创建时间升序,`2` 为按创建时间降序,`3` 为按更新时间升序,`4` 为按更新时间降序,`5` 为按内容顺序,`6` 为按相关度升序,`7` 为按相关度降序
+* `group`:分组方式,`0` 为不分组,`1` 为按文档分组
+* `hasReplace`:是否启用替换
+* `method`:搜索方式,`0` 为关键字,`1` 为查询语法,`2` 为 SQL,`3` 为正则表达式,`4` 为语义搜索
+* `hPath`:人类可读的搜索范围路径
+* `idPath`:搜索范围路径数组
+* `k`:搜索关键字
+* `r`:替换关键字
+* `types`:块类型开关,支持 `mathBlock`、`table`、`blockquote`、`superBlock`、`paragraph`、`document`、`heading`、`list`、`listItem`、`codeBlock`、`htmlBlock`、`embedBlock`、`databaseBlock`、`audioBlock`、`videoBlock`、`iframeBlock`、`widgetBlock` 和 `callout`
+* `subTypes`:块子类型开关,`h1` 至 `h6` 表示标题级别,`o`、`u` 和 `t` 分别表示有序列表、无序列表和任务列表
+* `replaceTypes`:替换类型开关,支持 `text`、`imgText`、`imgTitle`、`imgSrc`、`aText`、`aTitle`、`aHref`、`code`、`em`、`strong`、`inlineMath`、`inlineMemo`、`blockRef`、`fileAnnotationRef`、`kbd`、`mark`、`s`、`sub`、`sup`、`tag`、`u`、`docTitle`、`codeBlock`、`mathBlock` 和 `htmlBlock`
+
+`types`、`subTypes` 或 `replaceTypes` 中省略的布尔开关按 `false` 处理。
+
+### 获取已保存的搜索条件组
+
+* `/api/storage/getCriteria`
+* 无参数
+* 返回值:`data` 为按保存顺序排列的搜索条件组数组;没有已保存的条件组时为空数组
+* 对于只读角色,条件组会根据发布访问权限进行过滤,并清空返回结果中的 `k` 和 `r`
+
+### 保存搜索条件组
+
+创建条件组或完整覆盖同名条件组。覆盖时保留原有位置,新增时追加到末尾。
+
+* `/api/storage/setCriterion`
+* 需要管理员角色,在只读模式下不可用
+* 参数
+
+ ```json
+ {
+ "criterion": {
+ "name": "公开笔记",
+ "sort": 0,
+ "group": 1,
+ "hasReplace": false,
+ "method": 0,
+ "hPath": "公开笔记",
+ "idPath": ["20210808180117-czj9bvb"],
+ "k": "",
+ "r": "",
+ "types": {
+ "document": true,
+ "paragraph": true
+ },
+ "subTypes": {
+ "h1": true
+ },
+ "replaceTypes": {
+ "text": true
+ }
+ }
+ }
+ ```
+
+ * `criterion`:要保存的完整搜索条件组
+* 返回值
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
+
+### 移除搜索条件组
+
+移除指定名称的条件组。名称不存在时也视为成功。
+
+* `/api/storage/removeCriterion`
+* 需要管理员角色,在只读模式下不可用
+* 参数
+
+ ```json
+ {
+ "name": "公开笔记"
+ }
+ ```
+
+ * `name`:条件组名称
+* 返回值
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": null
+ }
+ ```
diff --git a/kernel/api/storage_test.go b/kernel/api/storage_test.go
index 48ed9c3182..ad2eccfc48 100644
--- a/kernel/api/storage_test.go
+++ b/kernel/api/storage_test.go
@@ -28,6 +28,75 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+func TestCriteriaCRUD(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ })
+
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) {
+ c.Set(model.RoleContextKey, model.RoleAdministrator)
+ c.Next()
+ })
+ ServeAPI(engine)
+ perform := func(path, body string) *httptest.ResponseRecorder {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+ return recorder
+ }
+ type criterionData struct {
+ Name string `json:"name"`
+ SubTypes map[string]bool `json:"subTypes"`
+ }
+ getCriteria := func() []criterionData {
+ t.Helper()
+ recorder := perform("/api/storage/getCriteria", `{}`)
+ response := &struct {
+ Code int `json:"code"`
+ Data []criterionData `json:"data"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal criteria response failed: %v", err)
+ }
+ if response.Code != 0 {
+ t.Fatalf("get criteria failed: %s", recorder.Body.String())
+ }
+ return response.Data
+ }
+
+ setRecorder := perform("/api/storage/setCriterion", `{"criterion":{"name":"Public notes","subTypes":{"h1":true}}}`)
+ if responseCode(t, setRecorder) != 0 {
+ t.Fatalf("set criterion failed: %s", setRecorder.Body.String())
+ }
+ criteria := getCriteria()
+ if len(criteria) != 1 || criteria[0].Name != "Public notes" || !criteria[0].SubTypes["h1"] {
+ t.Fatalf("criterion was not persisted: %#v", criteria)
+ }
+
+ overwriteRecorder := perform("/api/storage/setCriterion", `{"criterion":{"name":"Public notes","subTypes":{"h2":true}}}`)
+ if responseCode(t, overwriteRecorder) != 0 {
+ t.Fatalf("overwrite criterion failed: %s", overwriteRecorder.Body.String())
+ }
+ criteria = getCriteria()
+ if len(criteria) != 1 || criteria[0].SubTypes["h1"] || !criteria[0].SubTypes["h2"] {
+ t.Fatalf("criterion was not overwritten: %#v", criteria)
+ }
+
+ removeRecorder := perform("/api/storage/removeCriterion", `{"name":"Public notes"}`)
+ if responseCode(t, removeRecorder) != 0 {
+ t.Fatalf("remove criterion failed: %s", removeRecorder.Body.String())
+ }
+ if criteria = getCriteria(); len(criteria) != 0 {
+ t.Fatalf("criterion was not removed: %#v", criteria)
+ }
+}
+
func TestGetLocalStorageByRole(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/kernel/model/storage.go b/kernel/model/storage.go
index a19ef88490..194b18a932 100644
--- a/kernel/model/storage.go
+++ b/kernel/model/storage.go
@@ -123,16 +123,19 @@ func setLocalStorage(val map[string]any) (err error) {
}
type Criterion struct {
- Name string `json:"name"`
- Sort int `json:"sort"` // 0:按块类型(默认),1:按创建时间升序,2:按创建时间降序,3:按更新时间升序,4:按更新时间降序,5:按内容顺序(仅在按文档分组时)
+ Name string `json:"name"`
+ // 排序方式:0 按块类型(默认),1 按创建时间升序,2 按创建时间降序,3 按更新时间升序,4 按更新时间降序,
+ // 5 按内容顺序,6 按相关度升序,7 按相关度降序
+ Sort int `json:"sort"`
Group int `json:"group"` // 0:不分组,1:按文档分组
HasReplace bool `json:"hasReplace"` // 是否有替换
- Method int `json:"method"` // 0:文本,1:查询语法,2:SQL,3:正则表达式
+ Method int `json:"method"` // 0:文本,1:查询语法,2:SQL,3:正则表达式,4:语义搜索
HPath string `json:"hPath"`
IDPath []string `json:"idPath"`
K string `json:"k"` // 搜索关键字
R string `json:"r"` // 替换关键字
Types *CriterionTypes `json:"types"` // 类型过滤选项
+ SubTypes map[string]bool `json:"subTypes"` // 子类型过滤选项
ReplaceTypes *CriterionReplaceTypes `json:"replaceTypes"` // 替换类型过滤选项
}