milvus和相似度检索

流程

milvus的使用流程是 创建collection -> 创建partition -> 创建索引(如果需要检索) -> 插入数据 -> 检索
这里以Python为例, 使用的milvus版本为2.3.x
首先按照库, python3 -m pip install pymilvus

Connect

from pymilvus import connections
connections.connect(
  alias="default",
  user='username',
  password='password',
  host='localhost',
  port='19530'
)


connections.list_connections()
connections.get_connection_addr('default')

connections.disconnect("default")

2.png
以上是源码,可以看出alias只是一个字典的映射的key

3.png
通过源码可以看到,还有两种连接方式:

  1. 在.env文件中添加参数,MILVUS_URI=milvus://<Your_Host>:<Your_Port>,之后可以使用connections.connect()连接
  2. 在一次连接成功后,将连接配置数据保存在内存,下次近执行connections.connect()即可连接,可以通过connections.remove_connection删除连接配置数据

Database

from pymilvus import connections, db

conn = connections.connect(host="127.0.0.1", port=19530)

database = db.create_database("book")

db.using_database("book") # 切换数据库
db.list_database()
db.drop_database("book")

Collection

和一些非关系型数据库(MongoDB)类似,Collection就是表

# collection
from pymilvus import Collection, CollectionSchema, FieldSchema, DataType, utility

## 需要提前创建列的名称、类型等数据,并且必须添加一个主键
book_id = FieldSchema(
  name="book_id",
  dtype=DataType.INT64,
  is_primary=True,
)
book_name = FieldSchema(
  name="book_name",
  dtype=DataType.VARCHAR,
  max_length=200,
  # The default value will be used if this field is left empty during data inserts or upserts.
  # The data type of `default_value` must be the same as that specified in `dtype`.
  default_value="Unknown"
)
word_count = FieldSchema(
  name="word_count",
  dtype=DataType.INT64,
  # The default value will be used if this field is left empty during data inserts or upserts.
  # The data type of `default_value` must be the same as that specified in `dtype`.
  default_value=9999
)
book_intro = FieldSchema(
  name="book_intro",
  dtype=DataType.FLOAT_VECTOR,
  dim=2
)
# dim=2是向量的维度

schema = CollectionSchema(
  fields=[book_id, book_name, word_count, book_intro],
  description="Test book search",
  enable_dynamic_field=True
)


collection_name = "book"

collection = Collection(
    name=collection_name,
    schema=schema,
    using='default',
    shards_num=2
    )

utility.rename_collection("book", "lights4") 
utility.has_collection("lights1")
utility.list_collections()
# utility.drop_collection("lights")

collection = Collection("lights3")      
collection.load(replica_number=2)
# reduce memory usage
collection.release()

Partition

# Create a Partition

collection = Collection("book")      # Get an existing collection.
collection.create_partition("novel")

Index

milvus的索引决定了搜索所用的算法,必须设置好所引才能进行搜索。

# Index
index_params = {
  "metric_type":"L2",
  "index_type":"IVF_FLAT",
  "params":{"nlist":1024}
}

collection.create_index(
  field_name="book_intro", 
  index_params=index_params
)

## metric_type是相似性计算算法,可选的有以下
## For floating point vectors:
## L2 (Euclidean distance)
## IP (Inner product)
## COSINE (Cosine similarity)
## For binary vectors:
## JACCARD (Jaccard distance)
## HAMMING (Hamming distance)
utility.index_building_progress("<Your_Collection>")

Data

数据可以从dataFrame来,也可以从其他方式获得,只要列名对上,即可。

import pandas as pd
import numpy as np

insert_data = pd.read_csv("<Your_File>")
mr = collection.insert(insert_data)

Search

# search
search_params = {
    "metric_type": "L2", 
    "offset": 5, 
    "ignore_growing": False, 
    "params": {"nprobe": 10}
}

results = collection.search(
    data=[[0.1, 0.2]], 
    anns_field="book_intro", 
    # the sum of `offset` in `param` and `limit` 
    # should be less than 16384.
    param=search_params,
    limit=10,
    expr=None,
    # 这里需要将想看的列名列举出来
    output_fields=['title'],
    consistency_level="Strong"
)

# get the IDs of all returned hits
results[0].ids

# get the distances to the query vector from all returned hits
results[0].distances

# get the value of an output field specified in the search request.
hit = results[0][0]
hit.entity.get('title')

具体的代码在我的github。希望对你有所帮助!

  • 12
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于 Milvus 的多模态检索系统可以实现对多种类型数据的检索,例如图像、文本、语音等。下面是一个简单的演示: 1. 首先,需要安装 Milvus 和相应的 Python SDK: ```shell pip install pymilvus==2.0.0rc5 pip install opencv-python==4.5.1.48 pip install Pillow==8.2.0 pip install grpcio==1.32.0 pip install grpcio-tools==1.32.0 ``` 2. 接下来,我们需要准备一些数据。这里以图像为例,将一些图像文件存储在本地文件夹中。 3. 然后,我们需要将这些图像向量化,并将它们插入到 Milvus 中。这里使用 ResNet50 模型提取图像特征,并使用 Milvus Python SDK 将特征向量插入到 Milvus 中。 ```python import os import cv2 import numpy as np from PIL import Image from milvus import Milvus, IndexType, MetricType, Status # 连接 Milvus milvus = Milvus(host='localhost', port='19530') # 创建 collection collection_name = 'image_collection' if collection_name in milvus.list_collections(): milvus.drop_collection(collection_name) milvus.create_collection(collection_name, {'fields': [ {'name': 'id', 'type': 'int64', 'is_primary': True}, {'name': 'embedding', 'type': 'float', 'params': {'dim': 2048}} ], 'segment_row_limit': 4096, 'auto_id': False}) # 加载 ResNet50 模型 model = cv2.dnn.readNetFromTorch('resnet50.t7') model.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV) model.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) # 提取图像特征并插入到 Milvus 中 data_path = 'image_data' for i, file_name in enumerate(os.listdir(data_path)): file_path = os.path.join(data_path, file_name) img = cv2.imread(file_path) img = cv2.resize(img, (224, 224)) blob = cv2.dnn.blobFromImage(img, 1, (224, 224), (104, 117, 123)) model.setInput(blob) embedding = model.forward().flatten() status, ids = milvus.insert(collection_name=collection_name, records=[ {'id': i, 'embedding': embedding.tolist()} ]) print(f'Insert image {file_name} with id {ids[0]}') # 创建索引 milvus.create_index(collection_name, IndexType.IVF_FLAT, {'nlist': 128}) ``` 4. 现在,我们已经将图像向量化并插入到 Milvus 中了。接下来,我们可以使用 Milvus 的向量相似度搜索功能来实现多模态检索。这里以图像检索为例,给定一张查询图像,我们可以使用同样的方式提取其特征向量,并在 Milvus 中搜索与其相似的图像。 ```python # 加载查询图像 query_path = 'query_image.jpg' query_img = cv2.imread(query_path) query_img = cv2.resize(query_img, (224, 224)) query_blob = cv2.dnn.blobFromImage(query_img, 1, (224, 224), (104, 117, 123)) # 提取查询图像特征 model.setInput(query_blob) query_embedding = model.forward().flatten() # 在 Milvus 中搜索相似的图像 search_param = {'nprobe': 16} status, results = milvus.search(collection_name, query_embedding.tolist(), 10, search_params=search_param) print(f'Search results: {results}') ``` 以上就是一个简单的基于 Milvus 的多模态检索系统的演示。除了图像检索,我们也可以使用类似的方式实现文本、语音等多种类型数据的检索

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值