Milvus笔记

一、创建操作

1、python版本

from pymilvus import Collection, FieldSchema, DataType, CollectionSchema, connections
from pymilvus.orm import utility, dbfrom knowledge_brain.milvus_sink import milvus_sink
from study.connect import Connectclass MilvusOperatC:def __init__(self, host, port, user, password, db_name ,alias,collection_name,schema,num_shards): #,collection_name,schema,shards_numprint("加载milvus依赖")self.host = hostself.port = portself.user = userself.password = passwordself.db_name = db_nameself.alias = aliasself.collection_name = collection_nameself.schema = schemaself.num_shards = num_shardsself.collection = self.con()#创建连接"""host  ipport  端口user  用户名password 密码db_name 数据库alias 别名"""def con(self):connections.connect(host=self.host,user=self.user,password=self.password,port=self.port,alias=self.alias)# 是否有该数据库,无则新建print("建立数据库连接~~~~")if self.db_name in db.list_database():passelse:print("没有%s数据库,进行新建~~~~" % self.db_name)db.create_database(self.db_name)print("新建%s数据库完成!" % self.db_name)# 使用数据库,建立数据库连接db.using_database(self.db_name)# 是否有该集合,无则创建if utility.has_collection(self.collection_name):print("集合已存在")passelse:print("没有%s集合,进行新建~~~~" % self.collection_name)self.col_create()print("新建%s集合完成!" % self.collection_name)collection = Collection(self.collection_name)print("数据库连接完成!")return collection#集合创建"""collection_name 集合名称schema   表头描述信息database  数据库信息shards_num 分片信息"""def col_create(self):# fields = [#     FieldSchema(name='vec', dtype=DataType.FLOAT_VECTOR, descrition='embedding vectors', dim=1024),#     FieldSchema(name='doc_slicing_id', dtype=DataType.VARCHAR, descrition='doc_slicing_id', max_length=100,#                 is_primary=True),#     FieldSchema(name='doc_id', dtype=DataType.VARCHAR, descrition='doc_id', max_length=100)# ]# schema = CollectionSchema(fields=fields, description=self.col_name)collection = Collection(name=self.collection_name, schema=self.schema,num_shards=self.num_shards)print(collection)#索引创建def index_create(self,index_params:str,vec_field:str):# create IVF_FLAT index for collection.# index_params = {#     'metric_type': 'L2',#     'index_type': "IVF_FLAT",#     'params': {"nlist": 150}# }self.collection.create_index(field_name=vec_field, index_params=index_params)# collection.create_index(#     field_name="doc_id",#     index_name="doc_id_index"# )# collection.load()#分区创建def partition_create(self,partition_name:str):self.collection.create_partition(partition_name)def load(self):self.collection.load()print("数据load成功")def unload(self):self.collection.release()if __name__ == '__main__':host='XX.17.38'port='31639'user='Milvus'password='Milvus'db_name='knowledge_test'alias='default'fields = [FieldSchema(name='pk', dtype=DataType.INT64, descrition='主键', max_length=200, is_primary=True,auto_id=True),FieldSchema(name='car_model', dtype=DataType.VARCHAR, descrition='car_model', max_length=65535, is_primary=False,auto_id=False),FieldSchema(name='text', dtype=DataType.VARCHAR, descrition='page_content', max_length=65535, is_primary=False,auto_id=False),FieldSchema(name='vector', dtype=DataType.FLOAT_VECTOR, descrition='embedding vectors', dim=1024)]schema = CollectionSchema(fields=fields, description='集合描述')# Collection('test',schema)# MilvusCreate(host,port,user,password,db_name,alias,'test',schema,2)milvus_sink(db_name,'test',1,1,1)

python调用

from pymilvus import FieldSchema, DataType, CollectionSchema
from study.MilvusOperatC import MilvusOperatCif __name__ == '__main__':host='XXX.17.38'port='31639sss'user='Milvus'password='Milvus'db_name='knowledge_test'alias='default'fields = [FieldSchema(name='pk', dtype=DataType.INT64, descrition='主键', max_length=200, is_primary=True,auto_id=True),FieldSchema(name='car_model', dtype=DataType.VARCHAR, descrition='car_model', max_length=65535,is_primary=False,auto_id=False),FieldSchema(name='text', dtype=DataType.VARCHAR, descrition='page_content', max_length=65535, is_primary=False,auto_id=False),FieldSchema(name='vector', dtype=DataType.FLOAT_VECTOR, descrition='embedding vectors', dim=1024)]schema = CollectionSchema(fields=fields, description='集合描述')index_params = {'metric_type': 'L2',#COSINE IP'index_type': "IVF_FLAT",'params': {"nlist": 150}}#embedding字段名称vec_field = "vector"mc = MilvusOperatC(host,port,user,password,db_name,alias,'test',schema,2)mc.index_create(index_params,vec_field)mc.partition_create('2024032103')mc.load()mc.unload()

2、java版本

package com.gwm.milvus;import com.google.gson.internal.$Gson$Preconditions;
import io.milvus.client.MilvusServiceClient;
import io.milvus.grpc.DataType;
import io.milvus.grpc.GetLoadStateResponse;
import io.milvus.grpc.GetLoadingProgressResponse;
import io.milvus.param.*;
import io.milvus.param.collection.*;
import io.milvus.param.index.CreateIndexParam;
import io.milvus.param.partition.CreatePartitionParam;/*** @author yangyingchun* @version 1.0* @date 2024/3/20 16:02*/
public class MilvusOperateC {/*** 获取连接* @param host* @param port* @param username* @param password* @param database* @return*/public static MilvusServiceClient getConn(String host,Integer port,String username,String password,String database){MilvusServiceClient milvusServiceClient= new MilvusServiceClient(ConnectParam.newBuilder().withHost(host).withPort(port).withAuthorization(username, password).withDatabaseName(database).build());return milvusServiceClient;}/*** 创建集合* @param milvusServiceClient* @param collectionName* @param databaseName* @param shardsNum* @param description* @return*/public static Integer col_create(MilvusServiceClient milvusServiceClient,String collectionName,String databaseName,Integer shardsNum,String description){FieldType fieldType1 = FieldType.newBuilder().withName("id").withDataType(DataType.Int64).withPrimaryKey(true).withAutoID(true).build();FieldType fieldType2 = FieldType.newBuilder().withName("text").withDataType(DataType.VarChar).withMaxLength(65535) //varchar类型必填.build();FieldType fieldType3 = FieldType.newBuilder().withName("vector").withDataType(DataType.FloatVector).withDimension(1024).build();CreateCollectionParam createCollectionParam= CreateCollectionParam.newBuilder().withCollectionName(collectionName).withDatabaseName(databaseName).withShardsNum(shardsNum).withDescription(description).addFieldType(fieldType1).addFieldType(fieldType2).addFieldType(fieldType3).build();R<RpcStatus> collection = milvusServiceClient.createCollection(createCollectionParam);Integer status = collection.getStatus();return status;}/*** 创建 索引* @param milvusServiceClient* @param metricType* @param collectionName* @param fieldName* @param INDEX_TYPE* @param INDEX_PARAM* @return*/public static Integer index_create(MilvusServiceClient milvusServiceClient,MetricType metricType, String collectionName, String fieldName, IndexType INDEX_TYPE,String INDEX_PARAM){R<RpcStatus> index = milvusServiceClient.createIndex(CreateIndexParam.newBuilder().withCollectionName(collectionName).withFieldName(fieldName).withIndexType(INDEX_TYPE).withMetricType(metricType).withExtraParam(INDEX_PARAM).withSyncMode(Boolean.FALSE).build());Integer status = index.getStatus();return status;}/*** 创建分区* @param milvusServiceClient* @param collectionName* @param partitionName* @return*/public static Integer partition_create(MilvusServiceClient milvusServiceClient,String collectionName,String partitionName){R<RpcStatus> partition = milvusServiceClient.createPartition(CreatePartitionParam.newBuilder().withCollectionName(collectionName).withPartitionName(partitionName).build());Integer status = partition.getStatus();return status;}/*** load数据到内存中,load进展情况* @param milvusServiceClient* @param collectionName* @param database* @return*/public static Integer load(MilvusServiceClient milvusServiceClient,String collectionName,String database){// You can check the loading statusInteger loadstatus = -1;GetLoadStateParam loadparam = GetLoadStateParam.newBuilder().withCollectionName(collectionName).build();R<GetLoadStateResponse> responseLoad = milvusServiceClient.getLoadState(loadparam);System.out.println("当前状态:"+responseLoad.getData().getState());System.out.println("当前状态:"+responseLoad.getStatus() + R.Status.Success.getCode());if (responseLoad.getStatus() != R.Status.Success.getCode()) {System.out.println(responseLoad.getMessage());}
//        System.out.println(responseLoad.getStatus());
//
//        // and loading progress as well
//
//        GetLoadingProgressParam loadingparam = GetLoadingProgressParam.newBuilder()
//                .withCollectionName(collectionName)
//                .build();
//        R<GetLoadingProgressResponse> responseLoading = milvusServiceClient.getLoadingProgress(loadingparam);
//        if (responseLoading.getStatus() != R.Status.Success.getCode()) {
//            System.out.println(responseLoading.getMessage());
//        }
//        /**
//         * load进展
//         */
//        System.out.println(responseLoading.getData().getProgress());LoadCollectionParam loadCollectionParam = LoadCollectionParam.newBuilder().withDatabaseName(database).withCollectionName(collectionName).build();R<RpcStatus> rpcStatusR = milvusServiceClient.loadCollection(loadCollectionParam);loadstatus = rpcStatusR.getStatus();return loadstatus;}/*** 释放内存数据* @param milvusServiceClient* @param collectionName* @return*/public static Integer release(MilvusServiceClient milvusServiceClient,String collectionName){R<RpcStatus> rpcStatusR = milvusServiceClient.releaseCollection(ReleaseCollectionParam.newBuilder().withCollectionName(collectionName).build());Integer status = rpcStatusR.getStatus();return status;}
}

调用

package com.gwm.milvus;import io.milvus.client.MilvusServiceClient;
import io.milvus.param.IndexType;
import io.milvus.param.MetricType;/*** @author yangyingchun* @version 1.0* @date 2024/3/20 16:50*/
public class MilvusTest {public static void main(String[] args) {String collectionName = "repositoryId_test1";String databaseName = "knowledge_cosine_test";Integer shards =2;String description = "测试java创建collection";MilvusServiceClient milvusClient =MilvusOperateC.getConn("XXX.17.38", 31630, "Milvus", "Milvus", "knowledge_test");Integer integer = MilvusOperateC.col_create(milvusClient,collectionName,databaseName,shards,description);System.out.println("collection创建状态:"+integer);String INDEX_PARAM = "{\"nlist\":1024}";Integer vector = MilvusOperateC.index_create(milvusClient, MetricType.COSINE, collectionName, "vector", IndexType.IVF_FLAT, INDEX_PARAM);System.out.println("索引创建状态:"+vector);Integer partitionCreate = MilvusOperateC.partition_create(milvusClient, collectionName, "20240320");System.out.println("分区创建状态:"+partitionCreate);Integer load = MilvusOperateC.load(milvusClient, collectionName, databaseName);System.out.println("集合load状态:"+load);Integer release = MilvusOperateC.release(milvusClient, collectionName);System.out.println("集合释放状态"+release);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/759517.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前后端分离项目springsecurity实现用户登录认证快速使用

目录 1、引入依赖 2、创建类继承WebSecurityConfigurerAdapter &#xff08;1&#xff09;重写里面的configure(HttpSecurity http)方法 &#xff08;2&#xff09;重写AuthenticationManager authenticationManagerBean() &#xff08;3&#xff09;密码加密工具 3、继承…

k8s kubectl 常用命令

查询节点node kubectl get node查询节点标签 kubectl get node --show-labels查询所有pod kubectl get pod -A查询指定命名空间下的pod kubectl get pod -n project-3428查询pod详细 kubectl -n project-3428 get pod xxxxxxxxxxxx -o widePOD打标签 kubectl label pod my…

vue前端面试题

描述一下Vue.js的响应式数据绑定原理。 答案&#xff1a; Vue.js 使用 Observer、Compile 和 Watcher 三个组件来实现响应式数据绑定。Observer 负责监听数据对象的属性变化&#xff0c;Compile 负责解析模板指令并建立依赖关系&#xff0c;Watcher 则负责在数据变化时执行相应…

实战打靶集锦-027-SoSimple1

文章目录 1.主机发现2. 端口扫描3. 服务枚举4. 服务探查5. 提权5.1 枚举系统信息5.2 枚举定时任务5.3 查看passwd文件5.4 枚举可执行文件5.5 查看家目录5.6 Linpeas提权 6. 获取flag 靶机地址&#xff1a;https://download.vulnhub.com/sosimple/So-Simple-1.7z 1.主机发现 目…

阿里云99元服务器40G ESSD Entry系统盘够用吗?

阿里云99元服务器40G ESSD Entry云盘够用吗&#xff1f;够用&#xff0c;操作系统占15GB左右&#xff0c;还有25G富余。如果是40G ESSD Entry系统盘不够用&#xff0c;还可以为云服务器另外挂载数据盘&#xff0c;所以不用担心40G系统盘不够用。可以在阿里云CLUB中心查看 aliyu…

Flutter 3.13 之后如何监听 App 生命周期事件

在 Flutter 中&#xff0c;您可以监听多个生命周期事件来处理应用程序的不同状态&#xff0c;但今天我们将讨论 didChangeAppLifecycleState 事件。每当应用程序的生命周期状态发生变化时&#xff0c;就会触发此事件。可能的状态有 resumed 、 inactive 、 paused 、 detached …

android 音频焦点,音频策略梳理

音频焦点和音频策略两个不同的概念&#xff0c;容易搞混 先来看下音频焦点和音频策略直接的区别和联系 音频策略的主要功能是为该音频找到合适的硬件设备播放 1 音频策略流程&#xff1a; (从usage->device) attributesBuilder.setUsage--->audioservice.mCarAudioCont…

SpringBoot特性--Profiles

Spring Profiles提供了一种方法来隔离你的应用程序配置的一部分&#xff0c;并使其仅在某些环境中可用。任何Component&#xff0c;Configuration或ConfigurationProperties都可以用Profile标记&#xff0c;以限制它的加载时机&#xff0c;如下面的例子所示。 Configuration(p…

大数据扩展

层面控制点四级三级二级 安全 物理 环境 基础 设施 位置 应保证承载大数据存储、处理和分析的设备机房位于中国境内。应保证承载大数据存储、处理和分析的设备机房位于中国境内。应保证承载大数据存储、处理和分析的设备机房位于中国境内。安全 通信 网络网络 架构b)应保证大数…

idea使用git笔记

1.创建分支和切换分支 创建分支 切换分支 2.把新创建的分支提交到远程服务器上&#xff08;注&#xff1a;如果没有提交的&#xff0c;随便找个文件修改再提交&#xff09; (1)切换到要提交的分支&#xff0c;add (2)commit (3)push 3.在自己分支修改代码及提交到自己的远…

【讲解Node.js常用的命令】进阶版

Node.js常用命令 Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境&#xff0c;它使得可以在服务器端运行 JavaScript 代码。Node.js 采用了事件驱动、非阻塞 I/O 模型&#xff0c;非常适用于构建高效的网络应用程序。以下是一些Node.js开发中常用的命令&#xff1…

【K3s】在 AWS EC2 上运行生产 K3s 集群

【K3s】在 AWS EC2 上运行生产 K3s 集群 本文将介绍如何在 AWS EC2 上运行 K3s。您将创建一个 EC2 实例并在 AWS 上运行单节点 K3s 集群。 自托管的 K3s 允许您在裸金属上运行 Kubernetes,并应用较小、低资源工作负载的原则。哦,你还可以控制你的控制平面。这有点像逃离托管…

探索软件工程:构建可靠、高效的数字世界

软件工程是一门涵盖了设计、开发、测试、维护和管理软件的学科&#xff0c;它在如今数字化时代的发展中扮演着至关重要的角色。随着科技的不断进步和社会的不断变迁&#xff0c;软件工程的意义也愈发凸显。本文将探索软件工程的重要性、原则和实践&#xff0c;以及其对当今社会…

Python Qt Designer 初探

代码下载在最下面 #开发环境安装# 本示例在Windows11下, 使用VSCode开发, Python 3.12.2, Qt Designer 5.11 VSCode插件Python、Python Debugger、PYQT Integration、Pylance (准备) VSCode自行官网下载 Visual Studio Code - Code Editing. Redefined (准备) Python 直接…

Hive自定义UpperGenericUDF函数

Hive自定义UpperGenericUDF函数 当创建自定义函数时&#xff0c;推荐使用 GenericUDF 类而不是 UDF 类&#xff0c;因为 GenericUDF 提供了更灵活的功能和更好的性能。以下是使用 GenericUDF 类创建自定义函数的步骤&#xff1a; 编写Java函数逻辑&#xff1a;编写继承自 Gener…

上位机图像处理和嵌入式模块部署(qmacvisual拟合直线)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 测量是图像处理的一个基本技能。那么测量的前提&#xff0c;就是我们需要在图像中找出特定的集合图形&#xff0c;比如说直线。当然&#xff0c;发…

# Maven Bom 的使用

Maven Bom 的使用 文章目录 Maven Bom 的使用概述BOM特点优点缺点 MavenMaven 安装安装步骤settingx.ml常用仓库地址Idea 使用maven常见坑 SpringBoot 项目Bom使用案例项目结构主项目 zerocode-back-servezc-dependency&#xff08;第三方jar管理&#xff09;子模块zc-serve子模…

Java中的监视器锁 (synchronized 关键字)

在使用多线程的时候,我们会经常遇到线程不安全的问题,即多个线程访问共享数据时出现不确定的结果或异常,此时引入我们今天要介绍的synchronized 关键字 一.synchronized 的特性 1) 互斥 synchronized 会起到互斥效果, 某个线程执行到某个对象的 synchronized 中时, 其他线程如…

手机运营商二要素检测:重塑信任基石,筑牢信息安全屏障

随着移动互联网的普及和数字经济的快速发展&#xff0c;用户信息安全的重要性日益凸显。运营商二要素检测作为一种强大的安全验证机制&#xff0c;以其精准匹配与实时验证的特性&#xff0c;为各类应用场景提供了一种可靠的身份识别解决方案&#xff0c;正在成为众多企业和服务…

PyTorch 深度学习(GPT 重译)(六)

十四、端到端结节分析&#xff0c;以及接下来的步骤 本章内容包括 连接分割和分类模型 为新任务微调网络 将直方图和其他指标类型添加到 TensorBoard 从过拟合到泛化 在过去的几章中&#xff0c;我们已经构建了许多对我们的项目至关重要的系统。我们开始加载数据&#xf…