Weaviate 向量数据库¶
如果您在 Colab 上打开此 Notebook,可能需要安装 LlamaIndex 🦙。
In [ ]:
Copied!
%pip install llama-index-vector-stores-weaviate
%pip install llama-index-vector-stores-weaviate
In [ ]:
Copied!
!pip install llama-index
!pip install llama-index
创建 Weaviate 客户端¶
In [ ]:
Copied!
import os
import openai
os.environ["OPENAI_API_KEY"] = ""
openai.api_key = os.environ["OPENAI_API_KEY"]
import os
import openai
os.environ["OPENAI_API_KEY"] = ""
openai.api_key = os.environ["OPENAI_API_KEY"]
In [ ]:
Copied!
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
In [ ]:
Copied!
import weaviate
import weaviate
In [ ]:
Copied!
# cloud
cluster_url = ""
api_key = ""
client = weaviate.connect_to_wcs(
cluster_url=cluster_url,
auth_credentials=weaviate.auth.AuthApiKey(api_key),
)
# local
# client = connect_to_local()
# cloud
cluster_url = ""
api_key = ""
client = weaviate.connect_to_wcs(
cluster_url=cluster_url,
auth_credentials=weaviate.auth.AuthApiKey(api_key),
)
# local
# client = connect_to_local()
加载文档并构建 VectorStoreIndex¶
In [ ]:
Copied!
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores.weaviate import WeaviateVectorStore
from IPython.display import Markdown, display
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores.weaviate import WeaviateVectorStore
from IPython.display import Markdown, display
下载数据
In [ ]:
Copied!
!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
In [ ]:
Copied!
# load documents
documents = SimpleDirectoryReader("./data/paul_graham").load_data()
# load documents
documents = SimpleDirectoryReader("./data/paul_graham").load_data()
In [ ]:
Copied!
from llama_index.core import StorageContext
# If you want to load the index later, be sure to give it a name!
vector_store = WeaviateVectorStore(
weaviate_client=client, index_name="LlamaIndex"
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
# NOTE: you may also choose to define a index_name manually.
# index_name = "test_prefix"
# vector_store = WeaviateVectorStore(weaviate_client=client, index_name=index_name)
from llama_index.core import StorageContext
# If you want to load the index later, be sure to give it a name!
vector_store = WeaviateVectorStore(
weaviate_client=client, index_name="LlamaIndex"
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
# NOTE: you may also choose to define a index_name manually.
# index_name = "test_prefix"
# vector_store = WeaviateVectorStore(weaviate_client=client, index_name=index_name)
使用自定义批处理配置¶
Llamaindex 默认采用 Weaviate 的动态批处理功能,该功能已针对大多数常见场景进行优化。但在低延迟环境中,这种方式可能导致服务器过载或触发 GRPC 消息大小限制。若需更精细的控制并优化数据摄入流程,建议通过固定大小的批处理来调整批次规模。
以下展示如何微调 WeaviateVectorStore 并定义自定义批处理:
In [ ]:
Copied!
from weaviate.classes.config import ConsistencyLevel
custom_batch = client.batch.fixed_size(
batch_size=123,
concurrent_requests=3,
consistency_level=ConsistencyLevel.ALL,
)
vector_store_fixed = WeaviateVectorStore(
weaviate_client=client,
index_name="LlamaIndex",
# we pass our custom batch as a client_kwargs
client_kwargs={"custom_batch": custom_batch},
)
from weaviate.classes.config import ConsistencyLevel
custom_batch = client.batch.fixed_size(
batch_size=123,
concurrent_requests=3,
consistency_level=ConsistencyLevel.ALL,
)
vector_store_fixed = WeaviateVectorStore(
weaviate_client=client,
index_name="LlamaIndex",
# we pass our custom batch as a client_kwargs
client_kwargs={"custom_batch": custom_batch},
)
查询索引¶
In [ ]:
Copied!
# set Logging to DEBUG for more detailed outputs
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
# set Logging to DEBUG for more detailed outputs
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
In [ ]:
Copied!
display(Markdown(f"<b>{response}</b>"))
display(Markdown(f"{response}"))
加载索引¶
此处我们使用与创建初始索引时相同的索引名称。这样可以避免自动生成新索引,并让我们能够轻松地重新连接到原有索引。
In [ ]:
Copied!
cluster_url = ""
api_key = ""
client = weaviate.connect_to_wcs(
cluster_url=cluster_url,
auth_credentials=weaviate.auth.AuthApiKey(api_key),
)
# local
# client = weaviate.connect_to_local()
cluster_url = ""
api_key = ""
client = weaviate.connect_to_wcs(
cluster_url=cluster_url,
auth_credentials=weaviate.auth.AuthApiKey(api_key),
)
# local
# client = weaviate.connect_to_local()
In [ ]:
Copied!
vector_store = WeaviateVectorStore(
weaviate_client=client, index_name="LlamaIndex"
)
loaded_index = VectorStoreIndex.from_vector_store(vector_store)
vector_store = WeaviateVectorStore(
weaviate_client=client, index_name="LlamaIndex"
)
loaded_index = VectorStoreIndex.from_vector_store(vector_store)
In [ ]:
Copied!
# set Logging to DEBUG for more detailed outputs
query_engine = loaded_index.as_query_engine()
response = query_engine.query("What happened at interleaf?")
display(Markdown(f"<b>{response}</b>"))
# set Logging to DEBUG for more detailed outputs
query_engine = loaded_index.as_query_engine()
response = query_engine.query("What happened at interleaf?")
display(Markdown(f"{response}"))
元数据过滤¶
让我们插入一个虚拟文档,然后尝试通过过滤仅返回该文档。
In [ ]:
Copied!
from llama_index.core import Document
doc = Document.example()
print(doc.metadata)
print("-----")
print(doc.text[:100])
from llama_index.core import Document
doc = Document.example()
print(doc.metadata)
print("-----")
print(doc.text[:100])
In [ ]:
Copied!
loaded_index.insert(doc)
loaded_index.insert(doc)
In [ ]:
Copied!
from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters
filters = MetadataFilters(
filters=[ExactMatchFilter(key="filename", value="README.md")]
)
query_engine = loaded_index.as_query_engine(filters=filters)
response = query_engine.query("What is the name of the file?")
display(Markdown(f"<b>{response}</b>"))
from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters
filters = MetadataFilters(
filters=[ExactMatchFilter(key="filename", value="README.md")]
)
query_engine = loaded_index.as_query_engine(filters=filters)
response = query_engine.query("What is the name of the file?")
display(Markdown(f"{response}"))
完全删除索引¶
您可以使用 delete_index 函数删除向量存储创建的索引
In [ ]:
Copied!
vector_store.delete_index()
vector_store.delete_index()
In [ ]:
Copied!
vector_store.delete_index() # calling the function again does nothing
vector_store.delete_index() # calling the function again does nothing
连接终止¶
您必须确保客户端连接被正确关闭:
In [ ]:
Copied!
client.close()
client.close()