1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| from pymilvus import connections, Collection, CollectionSchema, FieldSchema, DataType from sentence_transformers import SentenceTransformer from langchain.text_splitter import RecursiveCharacterTextSplitter import hashlib
class RAGVectorStore: def __init__(self, db_path="./milvus_rag.db", model_name="paraphrase-multilingual-MiniLM-L12-v2"): connections.connect(uri=db_path) self.collection_name = "rag_knowledge" self.model = SentenceTransformer(model_name) self.embedding_dim = self.model.get_sentence_embedding_dimension() self.chunk_size = 300 self.overlap = 50 self._create_collection() def _create_collection(self): if utility.has_collection(self.collection_name): utility.drop_collection(self.collection_name) fields = [ FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True), FieldSchema(name="text", dtype=DataType.VARCHAR, max_length=65535), FieldSchema(name="source", dtype=DataType.VARCHAR, max_length=255), FieldSchema(name="chunk_id", dtype=DataType.INT64), FieldSchema(name="doc_id", dtype=DataType.VARCHAR, max_length=64), FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=self.embedding_dim) ] schema = CollectionSchema(fields) self.collection = Collection(self.collection_name, schema) index_params = { "metric_type": "COSINE", "index_type": "IVF_FLAT", "params": {"nlist": 128} } self.collection.create_index("embedding", index_params) self.collection.load() def add_document(self, text, source): """添加文档(自动分块)""" splitter = RecursiveCharacterTextSplitter( chunk_size=self.chunk_size, chunk_overlap=self.overlap, separators=["\n\n", "\n", "。", "!", "?", ";", ",", " ", ""] ) chunks = splitter.split_text(text) doc_id = hashlib.md5(text[:100].encode()).hexdigest()[:8] embeddings = self.model.encode(chunks, convert_to_numpy=True) data = [ chunks, [source] * len(chunks), list(range(len(chunks))), [doc_id] * len(chunks), embeddings.tolist() ] self.collection.insert(data) self.collection.flush() return doc_id, len(chunks) def search(self, query, top_k=5, filter_expr=None): """检索相似文档""" query_vec = self.model.encode(query, convert_to_numpy=True) search_params = { "metric_type": "COSINE", "params": {"nprobe": 10} } results = self.collection.search( data=[query_vec.tolist()], anns_field="embedding", param=search_params, limit=top_k, expr=filter_expr, output_fields=["text", "source", "chunk_id", "doc_id"] ) return results[0] def search_and_aggregate(self, query, top_k=10): """检索并聚合为完整文档""" results = self.search(query, top_k=top_k) docs = {} for hit in results: doc_id = hit.entity.get('doc_id') if doc_id not in docs: docs[doc_id] = { 'source': hit.entity.get('source'), 'chunks': [], 'total_score': 0 } docs[doc_id]['chunks'].append({ 'text': hit.entity.get('text'), 'score': hit.score, 'chunk_id': hit.entity.get('chunk_id') }) docs[doc_id]['total_score'] += hit.score for doc_id in docs: docs[doc_id]['chunks'].sort(key=lambda x: x['chunk_id']) docs[doc_id]['full_text'] = "\n".join( [c['text'] for c in docs[doc_id]['chunks']] ) return sorted(docs.values(), key=lambda x: x['total_score'], reverse=True)
if __name__ == "__main__": rag = RAGVectorStore() long_text = "..." doc_id, chunk_count = rag.add_document(long_text, "技术文档") print(f"文档{doc_id}已添加,分{chunk_count}块") results = rag.search_and_aggregate("机器学习是什么?") for doc in results: print(f"来源: {doc['source']}") print(f"相关文本: {doc['full_text'][:200]}...") print(f"综合得分: {doc['total_score']:.4f}")
|