trunks_service.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. from sqlalchemy import func
  2. from sqlalchemy.orm import Session
  3. from db.session import get_db
  4. from typing import List, Optional
  5. from model.trunks_model import Trunks
  6. from db.session import SessionLocal
  7. import logging
  8. from utils.vectorizer import Vectorizer
  9. logger = logging.getLogger(__name__)
  10. class TrunksService:
  11. def __init__(self):
  12. self.db = next(get_db())
  13. def create_trunk(self, trunk_data: dict) -> Trunks:
  14. # 自动生成向量和全文检索字段
  15. content = trunk_data.get('content')
  16. if 'embedding' in trunk_data and len(trunk_data['embedding']) != 1024:
  17. raise ValueError("向量维度必须为1024")
  18. trunk_data['embedding'] = Vectorizer.get_embedding(content)
  19. print("embedding length:", len(trunk_data['embedding']))
  20. logger.debug(f"生成的embedding长度: {len(trunk_data['embedding'])}, 内容摘要: {content[:20]}")
  21. # trunk_data['content_tsvector'] = func.to_tsvector('chinese', content)
  22. db = SessionLocal()
  23. try:
  24. trunk = Trunks(**trunk_data)
  25. db.add(trunk)
  26. db.commit()
  27. db.refresh(trunk)
  28. return trunk
  29. except Exception as e:
  30. db.rollback()
  31. logger.error(f"创建trunk失败: {str(e)}")
  32. raise
  33. finally:
  34. db.close()
  35. def get_trunk_by_id(self, trunk_id: int) -> Optional[Trunks]:
  36. db = SessionLocal()
  37. try:
  38. return db.query(Trunks).filter(Trunks.id == trunk_id).first()
  39. finally:
  40. db.close()
  41. def search_by_vector(self, text: str, limit: int = 10, metadata_condition: Optional[dict] = None) -> List[dict]:
  42. embedding = Vectorizer.get_embedding(text)
  43. db = SessionLocal()
  44. try:
  45. query = db.query(
  46. Trunks.id,
  47. Trunks.file_path,
  48. Trunks.content,
  49. Trunks.embedding.l2_distance(embedding).label('distance')
  50. )
  51. if metadata_condition:
  52. query = query.filter_by(**metadata_condition)
  53. results = query.order_by('distance').limit(limit).all()
  54. return [{
  55. 'id': r.id,
  56. 'file_path': r.file_path,
  57. 'content': r.content,
  58. 'distance': r.distance
  59. } for r in results]
  60. finally:
  61. db.close()
  62. def fulltext_search(self, query: str) -> List[Trunks]:
  63. db = SessionLocal()
  64. try:
  65. return db.query(Trunks).filter(
  66. Trunks.content_tsvector.match(query)
  67. ).all()
  68. finally:
  69. db.close()
  70. def update_trunk(self, trunk_id: int, update_data: dict) -> Optional[Trunks]:
  71. if 'content' in update_data:
  72. content = update_data['content']
  73. update_data['embedding'] = Vectorizer.get_embedding(content)
  74. logger.debug(f"更新生成的embedding长度: {len(update_data['embedding'])}, 内容摘要: {content[:20]}")
  75. # update_data['content_tsvector'] = func.to_tsvector('chinese', content)
  76. db = SessionLocal()
  77. try:
  78. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  79. if trunk:
  80. for key, value in update_data.items():
  81. setattr(trunk, key, value)
  82. db.commit()
  83. db.refresh(trunk)
  84. return trunk
  85. except Exception as e:
  86. db.rollback()
  87. logger.error(f"更新trunk失败: {str(e)}")
  88. raise
  89. finally:
  90. db.close()
  91. def delete_trunk(self, trunk_id: int) -> bool:
  92. db = SessionLocal()
  93. try:
  94. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  95. if trunk:
  96. db.delete(trunk)
  97. db.commit()
  98. return True
  99. return False
  100. except Exception as e:
  101. db.rollback()
  102. logger.error(f"删除trunk失败: {str(e)}")
  103. raise
  104. finally:
  105. db.close()
  106. def paginated_search(self, search_params: dict) -> dict:
  107. """
  108. 分页查询方法
  109. :param search_params: 包含keyword, pageNo, limit的字典
  110. :return: 包含结果列表和分页信息的字典
  111. """
  112. keyword = search_params.get('keyword', '')
  113. page_no = search_params.get('pageNo', 1)
  114. limit = search_params.get('limit', 10)
  115. if page_no < 1:
  116. page_no = 1
  117. if limit < 1:
  118. limit = 10
  119. embedding = Vectorizer.get_embedding(keyword)
  120. offset = (page_no - 1) * limit
  121. db = SessionLocal()
  122. try:
  123. # 获取总条数
  124. total_count = db.query(func.count(Trunks.id)).scalar()
  125. # 执行向量搜索
  126. results = db.query(
  127. Trunks.id,
  128. Trunks.file_path,
  129. Trunks.content,
  130. Trunks.embedding.l2_distance(embedding).label('distance')
  131. ).order_by('distance').offset(offset).limit(limit).all()
  132. return {
  133. 'data': [{
  134. 'id': r.id,
  135. 'file_path': r.file_path,
  136. 'content': r.content,
  137. 'distance': r.distance
  138. } for r in results],
  139. 'pagination': {
  140. 'total': total_count,
  141. 'pageNo': page_no,
  142. 'limit': limit,
  143. 'totalPages': (total_count + limit - 1) // limit
  144. }
  145. }
  146. finally:
  147. db.close()