在现代AI技术中,数据处理管道是一个关键的组成部分。本文将介绍如何使用Redis来构建一个高效的数据处理管道。我们将使用Redis作为向量存储、缓存和文档存储,结合HuggingFace的嵌入模型来实现这一过程。以下是详细步骤和示例代码。
依赖项安装
首先,我们需要安装必要的依赖项。包括Redis服务器、Redis的Python客户端以及HuggingFace的嵌入模型。
%pip install llama-index-storage-docstore-redis
%pip install llama-index-vector-stores-redis
%pip install llama-index-embeddings-huggingface
!pip install redis
启动Redis服务器:
!docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest
创建初始数据
我们首先创建一些测试数据,以便在后续步骤中使用。
!rm -rf test_redis_data
!mkdir -p test_redis_data
!echo "This is a test file: one!" > test_redis_data/test1.txt
!echo "This is a test file: two!" > test_redis_data/test2.txt
加载数据:
from llama_index.core import SimpleDirectoryReader
documents = SimpleDirectoryReader(
"./test_redis_data", filename_as_id=True
).load_data()
运行基于Redis的数据处理管道
我们将构建一个数据处理管道,将数据上载到向量存储中。
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core.ingestion import (
DocstoreStrategy,
IngestionPipeline,
IngestionCache,
)
from llama_index.core.ingestion.cache import RedisCache
from llama_index.storage.docstore.redis import RedisDocumentStore
from llama_index.core.node_parser import SentenceSplitter
from llama_index.vector_stores.redis import RedisVectorStore
embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
pipeline = IngestionPipeline(
transformations=[
SentenceSplitter(),
embed_model,
],
docstore=RedisDocumentStore.from_host_and_port(
"localhost", 6379, namespace="document_store"
),
vector_store=RedisVectorStore(
index_name="redis_vector_store",
index_prefix="vector_store",
redis_url="redis://localhost:6379",
),
cache=IngestionCache(
cache=RedisCache.from_host_and_port("localhost", 6379),
collection="redis_cache",
),
docstore_strategy=DocstoreStrategy.UPSERTS,
)
nodes = pipeline.run(documents=documents)
print(f"Ingested {len(nodes)} Nodes") # 输出: Ingested 2 Nodes
确认文档是否被正确上载
我们可以创建一个向量索引并快速查询已上传的文档。
from llama_index.core import VectorStoreIndex
index = VectorStoreIndex.from_vector_store(
pipeline.vector_store, embed_model=embed_model
)
response = index.as_query_engine(similarity_top_k=10).query(
"What documents do you see?"
)
print(response)
添加新数据并重新上载
我们可以更新现有文件并添加新文件,再次运行数据处理管道。
!echo "This is a test file: three!" > test_redis_data/test3.txt
!echo "This is a NEW test file: one!" > test_redis_data/test1.txt
documents = SimpleDirectoryReader(
"./test_redis_data", filename_as_id=True
).load_data()
nodes = pipeline.run(documents=documents)
print(f"Ingested {len(nodes)} Nodes") # 输出: Ingested 2 Nodes
index = VectorStoreIndex.from_vector_store(
pipeline.vector_store, embed_model=embed_model
)
response = index.as_query_engine(similarity_top_k=10).query(
"What documents do you see?"
)
print(response)
for node in response.source_nodes:
print(node.get_text())
常见错误及解决方案
- Redis连接错误:如果Redis服务器未启动或连接参数错误,可能会导致连接失败。确保Redis服务器已启动并且连接参数正确。
- 数据重复:在处理数据上载时,可能会出现重复数据。可以调整DocstoreStrategy策略来避免重复。
- 环境变量错误:确保环境变量(如API密钥)正确配置。
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!
参考资料: