当前位置: 首页 > news >正文

全文检索官网示例

链接地址:https://milvus.io/docs/zh/full_text_search_with_milvus.md
full_text_demo:

from typing import List
from __init__ import openai_client
import sysfrom pymilvus import (MilvusClient,DataType,Function,FunctionType,AnnSearchRequest,RRFRanker,
)# Connect to Milvus:连接到 Milvus
uri = "http://ip:19530"
collection_name = "full_text_demo"
client = MilvusClient(uri=uri)
print("连接成功")# sys.exit()analyzer_params = {"tokenizer": "standard", "filter": ["lowercase"]}schema = MilvusClient.create_schema()
schema.add_field(field_name="id",datatype=DataType.VARCHAR,is_primary=True,auto_id=True,max_length=100,
)
schema.add_field(field_name="content",datatype=DataType.VARCHAR,max_length=65535,analyzer_params=analyzer_params,enable_match=True,  # Enable text matchingenable_analyzer=True,  # Enable text analysis
)
schema.add_field(field_name="sparse_vector", datatype=DataType.SPARSE_FLOAT_VECTOR)
schema.add_field(field_name="dense_vector",datatype=DataType.FLOAT_VECTOR,dim=1536,  # Dimension for text-embedding-3-small
)
schema.add_field(field_name="metadata", datatype=DataType.JSON)bm25_function = Function(name="bm25",function_type=FunctionType.BM25,input_field_names=["content"],output_field_names="sparse_vector",
)schema.add_function(bm25_function)# 创建索引
index_params = MilvusClient.prepare_index_params()
index_params.add_index(field_name="sparse_vector",index_type="SPARSE_INVERTED_INDEX",metric_type="BM25",
)
index_params.add_index(field_name="dense_vector", index_type="FLAT", metric_type="IP")if client.has_collection(collection_name):client.drop_collection(collection_name)
client.create_collection(collection_name=collection_name,schema=schema,index_params=index_params,
)
print(f"Collection '{collection_name}' created successfully")# openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
model_name = "text-embedding-3-small"def get_embeddings(texts: List[str]) -> List[List[float]]:if not texts:return []response = openai_client.embeddings.create(input=texts, model=model_name)return [embedding.embedding for embedding in response.data]# Define indexes
index_params = MilvusClient.prepare_index_params()
index_params.add_index(field_name="sparse_vector",index_type="SPARSE_INVERTED_INDEX",metric_type="BM25",
)
index_params.add_index(field_name="dense_vector", index_type="FLAT", metric_type="IP")# Drop collection if exist
if client.has_collection(collection_name):client.drop_collection(collection_name)
# Create the collection
client.create_collection(collection_name=collection_name,schema=schema,index_params=index_params,
)
print(f"Collection '{collection_name}' created successfully")# Set up OpenAI for embeddings
openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
model_name = "text-embedding-3-small"# Define embedding generation function for reuse
def get_embeddings(texts: List[str]) -> List[List[float]]:if not texts:return []response = openai_client.embeddings.create(input=texts, model=model_name)return [embedding.embedding for embedding in response.data]# Example documents to insert
documents = [{"content": "Milvus is a vector database built for embedding similarity search and AI applications.","metadata": {"source": "documentation", "topic": "introduction"},},{"content": "Full-text search in Milvus allows you to search using keywords and phrases.","metadata": {"source": "tutorial", "topic": "full-text search"},},{"content": "Hybrid search combines the power of sparse BM25 retrieval with dense vector search.","metadata": {"source": "blog", "topic": "hybrid search"},},
]# Prepare entities for insertion
entities = []
texts = [doc["content"] for doc in documents]
embeddings = get_embeddings(texts)for i, doc in enumerate(documents):entities.append({"content": doc["content"],"dense_vector": embeddings[i],"metadata": doc.get("metadata", {}),})# Insert data
client.insert(collection_name, entities)
print(f"Inserted {len(entities)} documents")# Example query for semantic search
query = "How does Milvus help with similarity search?"# Generate embedding for query
query_embedding = get_embeddings([query])[0]# Semantic search using dense vectors
results = client.search(collection_name=collection_name,data=[query_embedding],anns_field="dense_vector",limit=5,output_fields=["content", "metadata"],
)
dense_results = results[0]# Print results
print("\nDense Search (Semantic):")
for i, result in enumerate(dense_results):print(f"{i+1}. Score: {result['distance']:.4f}, Content: {result['entity']['content']}")
http://www.lryc.cn/news/600481.html

相关文章:

  • “给予” 超越 “莲花”,支持图片在线编辑
  • [论文阅读] 人工智能 + 软件工程 | NoCode-bench:评估LLM无代码功能添加能力的新基准
  • SSRF_XXE_RCE_反序列化学习
  • 面试实战,问题十三,Redis在Java项目中的作用及使用场景详解,怎么回答
  • 大语言模型 LLM 通过 Excel 知识库 增强日志分析,根因分析能力的技术方案(3):使用云平台最小外部依赖方案
  • GMP模型
  • 深入解析Java内存模型:原理与并发优化实践
  • Oracle 误删数据恢复
  • ClickHouse高性能实时分析数据库-高性能的模式设计
  • 学习随想录-- web3学习入门计划
  • 50道JavaScript基础面试题:从基础到进阶
  • haproxy原理及实战部署
  • 根本是什么
  • 统计学07:概率论基础
  • Chukonu 阅读笔记
  • 分类预测 | MATLAB实现DBO-SVM蜣螂算法优化支持向量机分类预测
  • 深入解析YARN中的FairScheduler与CapacityScheduler:资源分配策略的核心区别
  • 检索召回率优化探究一:基于 LangChain 0.3集成 Milvus 2.5向量数据库构建的智能问答系统
  • 微信小程序 自定义带图片弹窗
  • 数据存储:OLAP vs OLTP
  • Flutter实现Retrofit风格的网络请求封装
  • Apache Doris Data Agent 解决方案:开启智能运维与数据治理新纪元
  • RS485转Profinet网关配置指南:高效启动JRT激光测距传感器测量模式
  • React入门学习——指北指南(第四节)
  • SQL Developer Data Modeler:一款免费跨平台的数据库建模工具
  • Flutter 提取图像主色调 ColorScheme.fromImageProvider
  • Javaweb————HTTP消息体拆分讲解
  • 渗透艺术系列之Laravel框架(一)
  • 互联网应用主流框架整合 Spring Boot开发
  • 大模型——字节Coze重磅开源!Dify何去何从