python 操作向量数据库qdrant

发布时间 2023-10-18 10:10:30作者: 乔小生1221

qdrant官网:https://qdrant.tech/documentation/overview/

两个步骤:

1、文本进行向量化

2、连接qdrant进行存储

步骤一:文本向量化

文本向量化可以借助很多现有模型,个人使用bge-large-zh

from sentence_transformers import SentenceTransformer

#模型已下载到本地
MODELBGE = SentenceTransformer(BASE_DIR + '/bge-large-zh')
class LocalEmbedding():
    def __init__(self, text, data=None):
        self.text = text#text必须是一个list:['文本1','文本2']
        self.data = data#list 
  #查询时:搜索关键词+官方给定的instruction
    def achieve_emb(self):
        try:
            MODELBGE = SentenceTransformer(BASE_DIR + '/bge-large-zh')
            instruction = "为这个句子生成表示以用于检索相关文章:"
            q_embeddings = MODELBGE.encode([instruction + self.text], normalize_embeddings=True).tolist()
            self.data.extend(q_embeddings)
            return self.data
        except Exception as e:
            print('本地embedding错误', e)
            return self.data
  #入库文本的向量化
    def achieve_emb_txt(self):
        try:
            p_embeddings = MODELBGE.encode(self.text, normalize_embeddings=True).tolist()
            return p_embeddings
        except Exception as e:
            print('本地embedding错误', e)
            return self.data

步骤二:连接qdrant进行存储

def save_qdrant_url(i_path,file_name):
   '''
i_path:文件路径
file_name:文件名
'''
try:      #连接qdrant数据库 client = QdrantClient('ip', port=6333) collection_name = '自定义的集合名称' try: table_collection = client.get_collection(collection_name=f"{collection_name}") print(table_collection) print(f'集合已存在:{collection_name}')
#update_collection更新集合,不会覆盖原有集合内的数据。 client.update_collection( collection_name
=collection_name ) except: print(f'创建新集合:{collection_name}')
#recreate_collection创建新的集合,原有数据清空 client.recreate_collection( collection_name
=collection_name, vectors_config=VectorParams(size=1024, distance=Distance.COSINE), ) print(f'正在执行json文件为{file_name}') with open(f'{i_path}', 'r', encoding='utf-8') as f: data_lines = json.loads(f.read()) text_all_list=data_lines[file_name] text_list = [text['content'] for text in text_all_list] tt = LocalEmbedding(text_list) vector_list = tt.achieve_emb_txt()        #upload_collection批量存储,注意向量化的列表长度vectors与文本内容列表长度payload要一一对应。 client.upload_collection( collection_name=collection_name, vectors=vector_list, payload=text_all_list, ids=None, batch_size=256, parallel=2 ) print(f'文件:{file_name} qdrant数据存储成功') except Exception as e: print(f'save_qdrant_data存储失败文件为:{file_name},失败原因为{e}')

 


 

 

 

 

 

 

 

 

 

 

 

 

记录个人的一个使用脚本。