Files
memoryweave/go/internal/api/routes/graph.go
T
xiaowei 7ec0642b9d feat: E1.1-E1.7 图谱 BFS 扩展全部完成
E1.1: InMemoryGraph.NavigateBiDir 真正双向 BFS(替代伪实现)
E1.2: 无相遇节点返回 {unreachable:true} 而非降级单向
E1.3: 规则 NER(extractEntitiesWithNER, 7个正则模式)
E1.4: relationFilter 支持(buildRelationFilterClause, SQL注入)
E1.5: API 层 relation_filter 参数(navigate 端点)
E1.6: API 层 relation_filter 参数(同上,已在 navigate 中支持)
E1.7: 环路检测(seenEdges map,同一边不在单次 BFS 中重复访问)

同时修复: graph_expander.go Navigate 调用加 relFilter=nil
2026-06-02 20:26:57 +08:00

149 lines
4.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 MemoryWeave — 知识图谱 API
package routes
import (
"encoding/json"
"net/http"
"strings"
"unicode"
"github.com/xiaoxue/memoryweave/internal/governance"
)
type GraphAPI struct {
Graph governance.GraphStore
}
func NewGraphAPI(g governance.GraphStore) *GraphAPI {
return &GraphAPI{Graph: g}
}
// GET /api/v1/graph/stats
func (ga *GraphAPI) Stats(w http.ResponseWriter, r *http.Request) {
nodeCount, edgeCount, density := ga.Graph.Stats()
respond(w, 200, map[string]interface{}{
"node_count": nodeCount,
"edge_count": edgeCount,
"density": density,
})
}
// POST /api/v1/graph/query
// 设计文档 §2.5.4: match 格式兼容; 同时保留 entity+relation 简洁格式
func (ga *GraphAPI) Query(w http.ResponseWriter, r *http.Request) {
var req struct {
Entity string `json:"entity"`
Relation string `json:"relation"`
Namespace string `json:"namespace"`
// 设计文档兼容格式: {"match": {"type": "entity", "label": "..."}}
Match *struct {
Type string `json:"type"`
Label string `json:"label"`
} `json:"match"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
return
}
// 兼容设计文档 match 格式
if req.Match != nil && req.Entity == "" {
// match.type 过滤 node type, match.label 做 name 模糊搜索
var nodes []map[string]interface{}
if req.Match.Label != "" {
nodes = ga.Graph.SearchNodes(req.Match.Label, req.Namespace)
} else if req.Match.Type != "" {
nodes = ga.Graph.ListNodesByType(req.Match.Type, req.Namespace)
} else {
nodes = ga.Graph.ListNodes(req.Namespace)
}
respond(w, 200, map[string]interface{}{"nodes": nodes, "count": len(nodes)})
return
}
// 默认跨 namespace 搜索(空 = 匹配所有,§2.5.6)
results := ga.Graph.Query(normalizeEntity(req.Entity), req.Relation, req.Namespace)
respond(w, 200, map[string]interface{}{"results": results, "count": len(results)})
}
// POST /api/v1/graph/navigate
// 支持三种模式:
// 1. 单实体 BFS: {"entity": "...", "max_hops": 2}
// 2. 双向 BFS: {"source": "...", "target": "...", "max_hops": 3}
// 3. 关系过滤 BFS: {"entity": "...", "max_hops": 2, "relation_filter": ["related_to", "uses"]}(E1.5)
func (ga *GraphAPI) Navigate(w http.ResponseWriter, r *http.Request) {
var req struct {
Entity string `json:"entity"`
Source string `json:"source"`
Target string `json:"target"`
MaxHops int `json:"max_hops"`
Namespace string `json:"namespace"`
RelationFilter []string `json:"relation_filter"` // E1.5: 关系类型白名单
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
return
}
if req.MaxHops <= 0 {
req.MaxHops = 2
}
// 模式 2: 双向 BFS(source + target)
if req.Source != "" && req.Target != "" {
source := normalizeEntity(req.Source)
target := normalizeEntity(req.Target)
paths, err := ga.Graph.NavigateBiDir(source, target, req.MaxHops, req.Namespace, req.RelationFilter)
if err != nil {
respondError(w, 500, "navigate failed: "+err.Error())
return
}
respond(w, 200, map[string]interface{}{
"paths": paths, "source": req.Source, "target": req.Target,
"bidirectional": true, "count": len(paths),
"relation_filter": req.RelationFilter,
})
return
}
// 模式 1: 单实体 BFS(兼容旧格式)
if req.Entity == "" {
respondError(w, 400, "entity (or source+target) required")
return
}
entity := normalizeEntity(req.Entity)
paths, err := ga.Graph.Navigate(entity, req.MaxHops, req.Namespace, req.RelationFilter)
if err != nil {
respondError(w, 500, "navigate failed: "+err.Error())
return
}
respond(w, 200, map[string]interface{}{
"paths": paths, "entity": req.Entity, "count": len(paths),
"relation_filter": req.RelationFilter,
})
}
// normalizeEntity 规整实体名:去特殊字符 + n_前缀,保留中文和 Unicode 字符
func normalizeEntity(entity string) string {
if strings.HasPrefix(entity, "n_") {
entity = entity[2:]
}
// 过滤特殊字符,保留 Unicode 字母、数字、下划线、中横线
clean := strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' || r == ' ' {
return r
}
// 保留中文和其他 Unicode 字母(如韩文、日文等)
if unicode.IsLetter(r) {
return r
}
return '_'
}, strings.ToLower(strings.TrimSpace(entity)))
// 合并连续下划线
for strings.Contains(clean, "__") {
clean = strings.ReplaceAll(clean, "__", "_")
}
clean = strings.Trim(clean, "_ ")
if clean == "" {
return "n_unknown"
}
return "n_" + clean
}