数据库使用(Python环境下Milvus向量数据库操作指南)

数据库使用(Python环境下Milvus向量数据库操作指南)
Python环境下Milvus向量数据库操作指南

Milvus Lite安装

pip install pymilvuspip install milvus-litepip install pymilvus.model 向量数据库模型

Milvus向量数据库操作

from pymilvus import MilvusClient, modelfrom pymilvus import Function,FunctionType#创建数据库clientclient = MilvusClient("milvus_hello.db")#创建collection表 if client.has_collection(collection_name="hello_collection"):     client.drop_collection(collection_name="hello_collection") client.create_collection(     collection_name="hello_collection",     dimension=768,  # The vectors we will use in this demo has 768 dimensions )//创建向量数据模型embedding_fn = model.DefaultEmbeddingFunction()//collection数据docs = [    "煤化工技术的发展与新型煤化工技术",    "石油和化工行业智能优化制造若干问题及挑战",    "我国现代煤化工产业发展现状及对石油化工产业的影响",]//将文本数据转化为向量数据存储vectors = embedding_fn.encode_documents(docs)# The output vector has 768 dimensions, matching the collection that we just created.print("Dim:", embedding_fn.dim, vectors[0].shape)  # Dim: 768 (768,)# Each entity has id, vector representation, raw text, and a subject label that we use# to demo metadata filtering later.data = [    {"id": i, "vector": vectors[i], "text": docs[i], "subject": "history"}    for i in range(len(vectors))]print("Data has", len(data), "entities, each with fields: ", data[0].keys())print("Vector dim:", len(data[0]["vector"]))#插入数据res = client.insert(collection_name="hello_collection", data=data)print(res)#稀疏document搜索query_vectors = embedding_fn.encode_queries(["煤化工技术的发展"])# If you don't have the embedding function you can use a fake vector to finish the demo:# query_vectors = [ [ random.uniform(-1, 1) for _ in range(768) ] ]res = client.search(    collection_name="hello_collection",  # target collection    data=query_vectors,  # query vectors    limit=2,  # number of returned entities    output_fields=["text", "subject"],  # specifies fields to be returned)print(res)#模糊查询res = client.query(    collection_name="hello_collection",    filter="text like '%化工%'",    output_fields=["text", "subject"],)print(res)#删除数据res = client.delete(    collection_name="demo_collection",    filter="id == 0",)print(res)

文章版权声明:除非注明,否则均为边学边练网络文章,版权归原作者所有

最新文章

热门文章

本栏目文章