找回密码
 立即注册
首页 业界区 安全 AI开发-python-milvus向量数据库(2-18 -milvus-文本匹 ...

AI开发-python-milvus向量数据库(2-18 -milvus-文本匹配)

表弊捞 4 小时前
解锁 Milvus 新玩法:基于文本匹配的精准检索实战

 在向量数据库的主流应用里,大家通常更关注向量相似度检索,但 Milvus 除了强大的向量检索能力外,还内置了非常实用的文本匹配功能。我们不需要额外引入搜索引擎,就能直接在文本字段上做精准关键词检索,快速搭建支持文本过滤的检索服务。 
 一、Milvus 文本匹配:不止是模糊匹配

 Milvus 的文本匹配不是简单的字符串模糊查询,而是通过内置分词器对文本做预处理,再配合字段级别的匹配开关,实现更精准的关键词检索。 这一能力特别适合同时需要向量检索 + 文本过滤的场景: 

  • 房产信息检索
  • 商品详情检索
  • 文档 / 内容检索
 使用这套方案,可以省去单独部署 ES 等文本引擎,大幅简化架构。 
 二、核心配置:让文本匹配真正生效

 实现 TEXT_MATCH 检索,关键在于集合 Schema 的设计: 

  • 文本字段使用 VARCHAR 类型,并设置合理长度
  • 开启 enable_analyzer,配置对应语言的分词器(支持中英文等)
  • 开启 enable_match,这是文本匹配功能的开关
 配置完成后,插入带文本的数据,就可以在查询时使用 TEXT_MATCH 函数,按关键词精准过滤结果。 
 三、超强组合:文本过滤 + 向量检索

 Milvus 最实用的一点,是文本匹配与向量检索可以无缝联用: 

  • 单独使用:只做关键词过滤查询
  • 混合使用:先用 TEXT_MATCH 做精准过滤,再用向量做相似度排序
 例如在房源场景中,可以先筛选出包含 dining(餐厅)相关描述的文本,再通过向量召回最相似的条目,兼顾精准性相关性。 
 四、实操避坑:这些细节一定要注意

 在实际使用中,有几个关键点容易踩坑: 

  • 分词器与语言要匹配 英文文本用英文分词器,中文文本用中文分词器,否则会影响匹配效果。
  • 索引与加载的时序 索引创建完成后再加载集合,异步索引要等待构建完毕,避免出现 “索引找不到” 异常。
  • 数据插入后需要同步 数据插入后建议短暂等待落盘,确保数据已持久化再执行查询与加载操作。
 
 五、架构优势:更轻量、更简单

 对比传统的「向量数据库 + 文本搜索引擎」双组件架构: 

  • 减少外部依赖,部署与维护成本更低
  • 一套 SDK 完成向量 + 文本检索,开发更高效
  • 依托 Milvus 分布式能力,性能与扩展性有保障
 不管是快速做 PoC 验证,还是搭建轻量级检索系统,Milvus 文本匹配都是性价比极高的选择。 
 六、总结

 Milvus 内置的文本匹配功能,提供了轻量化的一站式检索方案,把文本关键词过滤和向量相似度检索完美融合。开发者不再需要在多系统间切换,只用一套 Milvus 就能实现多维度、高性能的混合检索,在实际业务中拥有极高的落地价值。 代码:
  1. # 导入 Milvus 客户端相关模块和时间模块
  2. from pymilvus import MilvusClient, DataType, Function, FunctionType
  3. import time
  4. # 1. 初始化 Milvus 客户端连接
  5. client = MilvusClient(
  6.     uri="http://192.168.211.128:19530",
  7.     token="root:Milvus"
  8. )
  9. # 2. 准备数据环境:清理旧数据(避免集合已存在导致报错)
  10. try:
  11.     client.drop_collection(collection_name="demo")
  12. except Exception as e:
  13.     print(f"删除集合时出现异常(可能集合不存在):{e}")
  14. # 3. 定义集合的 Schema(结构)
  15. schema = MilvusClient.create_schema(
  16.     auto_id=False,
  17.     enable_dynamic_field=True,
  18. )
  19. # 定义文本字段的分词器参数(english:使用英文分词器)
  20. analyzer_params={"type": "english"}
  21. # 添加主键字段
  22. schema.add_field(field_name="id", datatype=DataType.INT64, is_primary=True)
  23. # 添加文本字段(启用分词和匹配)
  24. schema.add_field(
  25.     field_name='text',
  26.     datatype=DataType.VARCHAR,
  27.     max_length=500,
  28.     enable_analyzer=True,
  29.     analyzer_params=analyzer_params,
  30.     enable_match=True,
  31. )
  32. # 添加向量字段(5维浮点向量)
  33. schema.add_field(field_name="vector", datatype=DataType.FLOAT_VECTOR, dim=5)
  34. # 4. 创建集合
  35. client.create_collection(collection_name="demo", schema=schema)
  36. # 5. 准备待插入的数据
  37. data = [
  38.     {
  39.      "id": 0,
  40.      "vector": [0.3580376395471989, -0.6023495712049978, 0.18414012509913835, -0.26286205330961354, 0.9029438446296592],
  41.      "text": "The five-room apartment is very spacious and comfortable, with a large living room, dining room, and kitchen, as well as three bedrooms and two bathrooms. It's perfect for a family of five or more"},
  42.     {
  43.      "id": 1,
  44.      "vector": [0.19886812562848388, 0.06023560599112088, 0.6976963061752597, 0.2614474506242501, 0.838729485096104],
  45.      "text": "The house has five rooms in total, including a master bedroom with an en-suite bathroom, two other bedrooms sharing a bathroom, a study that can be used as a fourth bedroom if needed, and a guest room with its own bathroom"},
  46.     {
  47.         "id": 2,
  48.      "vector": [0.43742130801983836, -0.5597502546264526, 0.6457887650909682, 0.7894058910881185, 0.20785793220625592],
  49.      "text": "We stayed in a lovely five-room villa during our vacation. It had a beautiful garden, a swimming pool, and plenty of space for all of us to relax and enjoy ourselves"},
  50.     {
  51.      "id": 3,
  52.      "vector": [0.3172005263489739, 0.9719044792798428, -0.36981146090600725, -0.4860894583077995, 0.95791889146345],
  53.      "text": "The new building will have five floors, with each floor containing five rooms. This means there will be a total of 25 rooms in the building, which should provide ample accommodation for the residents"},
  54.     {
  55.      "id": 4,
  56.      "vector": [0.4452349528804562, -0.8757026943054742, 0.8220779437047674, 0.46406290649483184, 0.30337481143159106],
  57.      "text": "I'm looking for a five-room apartment in the city center, but I'm finding it quite difficult to find one that meets my requirements. Most of the ones I've seen are either too small or too expensive"}
  58. ]
  59. # 6. 插入数据到集合中
  60. res = client.insert(collection_name="demo", data=data)
  61. print(f"数据插入结果:{res}")
  62. # 8. 为向量字段创建索引(提升向量查询效率)
  63. index_params = MilvusClient.prepare_index_params()
  64. index_params.add_index(
  65.     field_name="vector",
  66.     metric_type="COSINE",
  67.     index_type="IVF_FLAT",
  68.     index_name="vector_index",
  69.     params={ "nlist": 128 }
  70. )
  71. # 设置 sync=True,等待索引创建完成后再继续
  72. client.create_index(
  73.     collection_name="demo",
  74.     index_params=index_params,
  75.     sync=True  # 等待索引创建完成
  76. )
  77. # 8. 加载集合到内存(索引创建完成后再加载,避免报错)
  78. client.load_collection(collection_name="demo")
  79. # 9. 执行文本匹配查询
  80. res = client.query(
  81.     collection_name="demo",
  82.     limit=5,
  83.     filter="TEXT_MATCH(text, 'dining')",
  84.     output_fields=["id","text"]
  85. )
  86. # 打印查询结果
  87. print('------------------')
  88. print("文本匹配 'dining' 的查询结果:")
  89. print(res)
复制代码
结果输出:
数据插入结果:{'insert_count': 5, 'ids': [0, 1, 2, 3, 4]}
------------------
文本匹配 'dining' 的查询结果:
data: ['{\'id\': 0, \'text\': "The five-room apartment is very spacious and comfortable, with a large living room, dining room, and kitchen, as well as three bedrooms and two bathrooms. It\'s perfect for a family of five or more"}'] 
 
 
更多学习资料尽在 老虎网盘资源
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册