Milvus向量数据库学习—— Build RAG with Mivus

Milvus向量数据库学习—— Build RAG with Mivus

Milvus 是一个开源的向量数据库,用于存储、管理和检索高维向量数据。它特别适合需要快速近似最近邻搜索(ANN,Approximate Nearest Neighbor)的应用场景,如推荐系统、计算机视觉、自然语言处理等。Milvus 提供了高性能、可扩展的解决方案,可以方便地集成到现代 AI 应用中。
官方文档

1.Prepare the data

from glob import glob

text_lines = []

for file_path in glob("few shots.txt", recursive=True):
    with open(file_path, "r") as file:
        file_text = file.read()

    text_lines += file_text.split("# ")
# 在这里我使用了 ‘# ’ 对文本块进行了分割
# 后续检索出的文本块会是被‘# ’分割的文本
print(type(text_lines))
print(text_lines)


2.Prepare the Embedding Model

from openai import OpenAI
openai_client = OpenAI(
    api_key = "Your api key here.....",
    base_url = "URL"
)
def emb_text(text):
    return (
        openai_client.embeddings.create(input=text, model="text-embedding-v3")
        .data[0]
        .embedding
    )

test_embedding = emb_text("This is a test")
embedding_dim = len(test_embedding)
print(embedding_dim)
print(test_embedding[:10])


3.Load data into Milvus

# 创建Collections
from pymilvus import MilvusClient

milvus_client = MilvusClient(uri="./milvus_demo.db") # 会存储在当前路径下

collection_name = "my_rag_collection" # 创建集合的名称

milvus_client.create_collection(
    collection_name=collection_name,
    dimension=embedding_dim, # 嵌入向量的维度
    metric_type="IP",  # 创建集合时应该定好采用什么样的metric_type
    consistency_level="Strong",  # Strong consistency level
)

consistency_level="Strong" 确保用户可以读取到最新版本的数据,设置集合的一致性级别为"强一致性"。Milvus支持四种一致性级别:Strong(强一致性)、Bounded(有界一致性)、Session(会话一致性)和Eventually(最终一致性)

About collection

  • Collection在Milvus中相当于关系型数据库中的Table

  • 一个数据库中可以拥有多个Collection

  • 不同维度的向量需存储在不同的Collection

  • 需要使用不同相似度计算方式的向量也需要存储在不同的Collection

# 插入数据
from tqdm import tqdm
data = []

for i, line in enumerate(tqdm(text_lines, desc="Creating embeddings")):
    data.append({"id": i, "vector": emb_text(line), "text": line})
milvus_client.insert(collection_name=collection_name, data=data)

{'insert_count': 72,
 'ids': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71],
 'cost': 0}

milvus_client.insert() 方法是增量插入,不会覆盖Collection中的其它内容。

# 插入单条记录
res = client.insert(
    collection_name="test_collection",
    data={
        'id': 0,
        'vector': [
            0.6186516144460161,
            0.5927442462488592,
            0.848608119657156,
            0.9287046808231654,
            -0.42215796530168403
        ]
    }
)

可选参数:

  • collection_nameString 类型

  • timeout :操作超时时间

4. Build RAG

Retrieve data for a query

question = "your question here...."

search_res = milvus_client.search(
    collection_name=collection_name,
    data=[
        emb_text(question)
    ],  # Use the `emb_text` function to convert the question to an embedding vector
    limit=3,  # Return top 3 results
    search_params={"metric_type": "IP", "params": {}},  # Inner product distance   # COSINE
    output_fields=["text"],  # Return the text field
)


这里使用的mertic_type 要与创建collection时所确定的一样。

[
    [
        " Where does Milvus store data?\n\nMilvus deals with two types of data, inserted data and metadata. \n\nInserted data, including vector data, scalar data, and collection-specific schema, are stored in persistent storage as incremental log. Milvus supports multiple object storage backends, including [MinIO](https://min.io/), [AWS S3](https://aws.amazon.com/s3/?nc1=h_ls), [Google Cloud Storage](https://cloud.google.com/storage?hl=en#object-storage-for-companies-of-all-sizes) (GCS), [Azure Blob Storage](https://azure.microsoft.com/en-us/products/storage/blobs), [Alibaba Cloud OSS](https://www.alibabacloud.com/product/object-storage-service), and [Tencent Cloud Object Storage](https://www.tencentcloud.com/products/cos) (COS).\n\nMetadata are generated within Milvus. Each Milvus module has its own metadata that are stored in etcd.\n\n###",
        0.7883545756340027
    ],
    [
        "How does Milvus handle vector data types and precision?\n\nMilvus supports Binary, Float32, Float16, and BFloat16 vector types.\n\n- Binary vectors: Store binary data as sequences of 0s and 1s, used in image processing and information retrieval.\n- Float32 vectors: Default storage with a precision of about 7 decimal digits. Even Float64 values are stored with Float32 precision, leading to potential precision loss upon retrieval.\n- Float16 and BFloat16 vectors: Offer reduced precision and memory usage. Float16 is suitable for applications with limited bandwidth and storage, while BFloat16 balances range and efficiency, commonly used in deep learning to reduce computational requirements without significantly impacting accuracy.\n\n###",
        0.6757288575172424
    ],
    [
        "How much does Milvus cost?\n\nMilvus is a 100% free open-source project.\n\nPlease adhere to [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) when using Milvus for production or distribution purposes.\n\nZilliz, the company behind Milvus, also offers a fully managed cloud version of the platform for those that don't want to build and maintain their own distributed instance. [Zilliz Cloud](https://zilliz.com/cloud) automatically maintains data reliability and allows users to pay only for what they use.\n\n###",
        0.6421123147010803
    ]
]
<think>好的,用户想了解如何在LangChain4j中使用RAGMilvus集成,并请求一个示例教程。首先,我需要回顾一下自己关于LangChain4j和Milvus的知识,确保信息的准确性。记得RAG分为索引和检索两个阶段,而Milvus向量数据库,用于存储和检索向量数据。 首先,要确认用户可能需要的步骤。根据引用[2],LangChain4j为RAG的索引和检索阶段提供了工具,所以应该分这两个部分来讲解。然后,参考引用[3]中的案例,他们使用了JSON文件作为数据源,包含问答对,这可能是一个好的示例结构。 接下来,需要考虑如何将文档加载、分块、嵌入,然后存储到Milvus中。可能需要使用LangChain4j的文档加载器,比如FileSystemDocumentLoader来加载JSON文件。分块部分,可能需要使用DocumentSplitter,例如按段落或固定大小分块。嵌入模型部分,用户可能没有指定,可以建议使用本地模型如All-MiniLM-L6-v2,或者云端如OpenAI的API,但根据引用[3],他们用了本地模型,可能更贴近用户需求。 然后是集成Milvus,需要配置Milvus的依赖,比如MilvusEmbeddingStore,并设置连接参数。在代码示例中,需要展示如何创建EmbeddingStore,并将文档向量化后存储进去。 在检索阶段,需要构建检索器,使用Retriever从Milvus中查询相关段落,再结合大模型生成答案。引用[1]提到使用阿里Qwen大模型,但用户可能也需要其他选项,比如本地运行的Ollama,如引用[3]中的案例。因此,在示例中可以选择一个常用的大模型,并给出配置方法。 另外,需要注意代码的正确性,比如确保导入正确的类,处理可能的异常,以及配置参数的准确性,比如Milvus的主机、端口、集合名称等。还要提醒用户安装必要的依赖,比如LangChain4j和Milvus的客户端库。 可能的问题点包括:文档分块的大小是否合适,嵌入模型的选择影响检索效果,Milvus集合的配置(如索引类型、距离度量方法)是否正确,以及大模型生成答案的质量。需要确保示例中的参数是合理的,并建议用户根据实际数据调整。 最后,生成相关问题时要围绕RAG流程、Milvus优化、数据处理和大模型选择等方面,帮助用户深入理解相关技术。</think>以下是使用LangChain4j集成Milvus实现RAG的完整示例说明: ### 一、环境准备 1. 添加依赖 ```xml <!-- LangChain4j核心库 --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j</artifactId> <version>0.27.0</version> </dependency> <!-- Milvus集成 --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-milvus</artifactId> <version>0.27.0</version> </dependency> ``` 2. 初始化Milvus服务 确保本地或远程运行Milvus服务(推荐Docker部署)[^3] ### 二、RAG实现流程 #### 步骤1:文档索引 ```java // 1. 加载文档(示例使用JSON问答对) Path jsonPath = Paths.get("qa_pairs.json"); Document document = FileSystemDocumentLoader.loadDocument(jsonPath); // 2. 文档分块(按段落分割) DocumentSplitter splitter = new DocumentByParagraphSplitter(300, 50); List<TextSegment> segments = splitter.split(document); // 3. 创建嵌入模型 EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); // 4. 初始化Milvus存储 EmbeddingStore<TextSegment> embeddingStore = MilvusEmbeddingStore.builder() .host("localhost") .port(19530) .collectionName("qa_vectors") .dimension(384) // 与AllMiniLmL6V2维度匹配 .build(); // 5. 存储向量 EmbeddingStoreIngestor.ingest(segments, embeddingModel, embeddingStore); ``` #### 步骤2:检索增强生成 ```java // 1. 创建检索器 Retriever<TextSegment> retriever = EmbeddingStoreRetriever.from(embeddingStore, embeddingModel); // 2. 配置大模型(示例使用本地Ollama) OpenAiChatModel chatModel = OpenAiChatModel.builder() .baseUrl("http://localhost:11434") .modelName("qwen:7b") .temperature(0.3) .build(); // 3. 构建RAG链 Assistant assistant = AiServices.builder(Assistant.class) .chatLanguageModel(chatModel) .retriever(retriever) .build(); // 4. 执行查询 String answer = assistant.chat("樟脑丸可以吃吗?"); System.out.println(answer); // 输出:樟脑丸不能食用,它是用于驱虫的化学制品 ``` ### 三、关键配置说明 1. **向量维度匹配**:需确保嵌入模型输出维度与Milvus集合配置一致,例如: - `AllMiniLmL6V2` → 384维 - `text-embedding-3-small` → 1536维[^1] 2. **检索参数优化**: ```java Retriever<TextSegment> retriever = EmbeddingStoreRetriever.from( embeddingStore, embeddingModel, 5, // 最大返回结果数 0.6 // 相似度阈值 ); ``` 3. **混合检索策略**:可结合关键词搜索与向量搜索 ```java ContentRetriever hybridRetriever = new HybridContentRetriever( new EmbeddingStoreRetriever(...), new KeywordSearchRetriever(...) ); ``` ### 四、典型应用场景 1. 智能客服系统(如弱智吧问答场景[^3]) 2. 企业知识库查询 3. 法律文件智能解读 4. 医疗知识问答系统
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值