Coverage for merco/memory/search.py: 0%

16 statements  

« prev     ^ index     » next       coverage.py v7.15.0, created at 2026-07-07 14:04 +0800

1"""记忆搜索索引""" 

2 

3import sqlite3 

4from pathlib import Path 

5 

6 

7class MemorySearch: 

8 """基于 SQLite FTS5 的记忆搜索""" 

9 

10 def __init__(self, db_path: str = None): 

11 self.db_path = Path(db_path or "~/.merco/memory.db").expanduser() 

12 self._init_db() 

13 

14 def _init_db(self): 

15 """初始化数据库""" 

16 with sqlite3.connect(self.db_path) as conn: 

17 conn.execute(""" 

18 CREATE VIRTUAL TABLE IF NOT EXISTS memories USING fts5( 

19 key, content, tags 

20 ) 

21 """) 

22 

23 def index(self, key: str, content: str, tags: str = ""): 

24 """索引记忆内容""" 

25 with sqlite3.connect(self.db_path) as conn: 

26 conn.execute("INSERT INTO memories VALUES (?, ?, ?)", (key, content, tags)) 

27 

28 def search(self, query: str, limit: int = 10) -> list[dict]: 

29 """搜索记忆""" 

30 with sqlite3.connect(self.db_path) as conn: 

31 cursor = conn.execute( 

32 "SELECT key, content, tags FROM memories WHERE memories MATCH ? LIMIT ?", 

33 (query, limit), 

34 ) 

35 return [{"key": row[0], "content": row[1], "tags": row[2]} for row in cursor.fetchall()]