Redis 向量儲存
本筆記本涵蓋如何開始使用 Redis 向量儲存。
Redis 是一個熱門的開源、記憶體內資料結構儲存,可用作資料庫、快取、訊息代理和佇列。它現在包含向量相似度搜尋功能,使其適用於作為向量儲存。
什麼是 Redis?
大多數開發人員都熟悉 Redis
。Redis
的核心是一個 NoSQL 資料庫,屬於鍵值系列,可用作快取、訊息代理、流處理和主要資料庫。開發人員選擇 Redis
是因為它速度快、擁有龐大的客戶端函式庫生態系統,並且多年來已被主要企業部署。
除了這些傳統用例之外,Redis
還提供額外功能,例如搜尋和查詢功能,允許使用者在 Redis
內部建立次要索引結構。這使得 Redis
能夠成為向量資料庫,並具有快取的速度。
Redis 作為向量資料庫
Redis
使用壓縮的反向索引,以實現快速索引並降低記憶體佔用量。它還支援許多進階功能,例如
- 在 Redis hash 和
JSON
中索引多個欄位 - 向量相似度搜尋(使用
HNSW
(ANN) 或FLAT
(KNN)) - 向量範圍搜尋(例如,尋找查詢向量半徑內的所有向量)
- 無效能損失的增量索引
- 文件排名(使用 tf-idf,帶有可選的使用者提供權重)
- 欄位權重
- 使用
AND
、OR
和NOT
運算子的複雜布林查詢 - 前綴比對、模糊比對和精確詞組查詢
- 支援 double-metaphone 語音比對
- 自動完成建議(帶有模糊前綴建議)
- 在 多種語言 中基於詞幹的查詢擴展(使用 Snowball)
- 支援中文斷詞和查詢(使用 Friso)
- 數值篩選器和範圍
- 使用 Redis 地理空間索引進行地理空間搜尋
- 強大的聚合引擎
- 支援所有
utf-8
編碼文字 - 檢索完整文件、選定欄位或僅檢索文件 ID
- 排序結果(例如,按建立日期)
客戶端
由於 Redis
不僅僅是一個向量資料庫,因此除了 LangChain
整合之外,通常還有需要使用 Redis
客戶端的情況。您可以使用任何標準 Redis
客戶端函式庫來執行搜尋和查詢命令,但最簡單的方法是使用包裝搜尋和查詢 API 的函式庫。以下是一些範例,但您可以在這裡找到更多客戶端函式庫。
專案 | 語言 | 授權條款 | 作者 | 星數 |
---|---|---|---|---|
jedis | Java | MIT | Redis | |
redisvl | Python | MIT | Redis | |
redis-py | Python | MIT | Redis | |
node-redis | Node.js | MIT | Redis | |
nredisstack | .NET | MIT | Redis |
部署選項
有許多方法可以部署具有 RediSearch 的 Redis。入門最簡單的方法是使用 Docker,但還有許多潛在的部署選項,例如
- Redis Cloud
- Docker (Redis Stack)
- 雲端市場:AWS Marketplace、Google Marketplace 或 Azure Marketplace
- 本地部署:Redis Enterprise Software
- Kubernetes:Kubernetes 上的 Redis Enterprise Software
Redis 連線 URL 結構描述
有效的 Redis URL 結構描述為
redis://
- 連接到 Redis 單機版,未加密rediss://
- 連接到 Redis 單機版,使用 TLS 加密redis+sentinel://
- 透過 Redis Sentinel 連接到 Redis 伺服器,未加密rediss+sentinel://
- 透過 Redis Sentinel 連接到 Redis 伺服器,所有連線均使用 TLS 加密
有關其他連線參數的更多資訊,請參閱 redis-py 文件。
設定
若要使用 RedisVectorStore,您需要安裝 langchain-redis
合作夥伴套件,以及本筆記本中使用的其他套件。
%pip install -qU langchain-redis langchain-huggingface sentence-transformers scikit-learn
Note: you may need to restart the kernel to use updated packages.
憑證
Redis 連線憑證作為 Redis 連線 URL 的一部分傳遞。Redis 連線 URL 用途廣泛,可以適應各種 Redis 伺服器拓撲和驗證方法。這些 URL 遵循特定格式,包括連線協定、驗證詳細資訊、主機、埠和資料庫資訊。Redis 連線 URL 的基本結構是
[protocol]://[auth]@[host]:[port]/[database]
其中
- protocol 可以是標準連線的 redis、SSL/TLS 連線的 rediss 或 Sentinel 連線的 redis+sentinel。
- auth 包括使用者名稱和密碼(如果適用)。
- host 是 Redis 伺服器主機名稱或 IP 位址。
- port 是 Redis 伺服器埠。
- database 是 Redis 資料庫編號。
Redis 連線 URL 支援各種組態,包括
- 獨立 Redis 伺服器(帶或不帶驗證)
- Redis Sentinel 設定
- SSL/TLS 加密連線
- 不同的驗證方法(僅密碼或使用者名稱-密碼)
以下是不同組態的 Redis 連線 URL 範例
# connection to redis standalone at localhost, db 0, no password
redis_url = "redis://127.0.0.1:6379"
# connection to host "redis" port 7379 with db 2 and password "secret" (old style authentication scheme without username / pre 6.x)
redis_url = "redis://:secret@redis:7379/2"
# connection to host redis on default port with user "joe", pass "secret" using redis version 6+ ACLs
redis_url = "redis://joe:secret@redis/0"
# connection to sentinel at localhost with default group mymaster and db 0, no password
redis_url = "redis+sentinel://127.0.0.1:26379"
# connection to sentinel at host redis with default port 26379 and user "joe" with password "secret" with default group mymaster and db 0
redis_url = "redis+sentinel://joe:secret@redis"
# connection to sentinel, no auth with sentinel monitoring group "zone-1" and database 2
redis_url = "redis+sentinel://redis:26379/zone-1/2"
# connection to redis standalone at localhost, db 0, no password but with TLS support
redis_url = "rediss://127.0.0.1:6379"
# connection to redis sentinel at localhost and default port, db 0, no password
# but with TLS support for booth Sentinel and Redis server
redis_url = "rediss+sentinel://127.0.0.1"
使用 Docker 啟動 Redis 執行個體
若要將 Redis 與 LangChain 搭配使用,您需要執行中的 Redis 執行個體。您可以使用 Docker 啟動一個,方法是
docker run -d -p 6379:6379 redis/redis-stack:latest
在此範例中,我們將使用本機 Redis 執行個體。如果您使用遠端執行個體,則需要相應地修改 Redis URL。
import os
REDIS_URL = os.getenv("REDIS_URL", "redis://127.0.0.1:6379")
print(f"Connecting to Redis at: {REDIS_URL}")
Connecting to Redis at: redis://redis:6379
如果您想要取得模型呼叫的自動追蹤,您也可以透過取消註解下方內容來設定您的 LangSmith API 金鑰
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"
讓我們透過 ping Redis 來檢查 Redis 是否已啟動並執行
import redis
redis_client = redis.from_url(REDIS_URL)
redis_client.ping()
True
範例資料
20 個新聞群組資料集包含約 18000 篇關於 20 個主題的新聞群組貼文。我們將使用一個子集進行此示範,並專注於兩個類別:「alt.atheism」和「sci.space」
from langchain.docstore.document import Document
from sklearn.datasets import fetch_20newsgroups
categories = ["alt.atheism", "sci.space"]
newsgroups = fetch_20newsgroups(
subset="train", categories=categories, shuffle=True, random_state=42
)
# Use only the first 250 documents
texts = newsgroups.data[:250]
metadata = [
{"category": newsgroups.target_names[target]} for target in newsgroups.target[:250]
]
len(texts)
250
初始化
RedisVectorStore 執行個體可以透過多種方式初始化
RedisVectorStore.__init__
- 直接初始化RedisVectorStore.from_texts
- 從文字清單初始化(可選地帶有元數據)RedisVectorStore.from_documents
- 從langchain_core.documents.Document
物件清單初始化RedisVectorStore.from_existing_index
- 從現有的 Redis 索引初始化
下面我們將使用 RedisVectorStore.__init__
方法,使用 RedisConfig
執行個體。
pip install -qU langchain-openai
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
我們將使用 SentenceTransformer 模型來建立嵌入。此模型在本機執行,不需要 API 金鑰。
from langchain_redis import RedisConfig, RedisVectorStore
config = RedisConfig(
index_name="newsgroups",
redis_url=REDIS_URL,
metadata_schema=[
{"name": "category", "type": "tag"},
],
)
vector_store = RedisVectorStore(embeddings, config=config)
管理向量儲存
將項目新增至向量儲存
ids = vector_store.add_texts(texts, metadata)
print(ids[0:10])
['newsgroups:f1e788ee61fe410daa8ef941dd166223', 'newsgroups:80b39032181f4299a359a9aaed6e2401', 'newsgroups:99a3efc1883647afba53d115b49e6e92', 'newsgroups:503a6c07cd71418eb71e11b42589efd7', 'newsgroups:7351210e32d1427bbb3c7426cf93a44f', 'newsgroups:4e79fdf67abe471b8ee98ba0e8a1a055', 'newsgroups:03559a1d574e4f9ca0479d7b3891402e', 'newsgroups:9a1c2a7879b8409a805db72feac03580', 'newsgroups:3578a1e129f5435f9743cf803413f37a', 'newsgroups:9f68baf4d6b04f1683d6b871ce8ad92d']
讓我們檢查第一個文件
texts[0], metadata[0]
('From: bil@okcforum.osrhe.edu (Bill Conner)\nSubject: Re: Not the Omni!\nNntp-Posting-Host: okcforum.osrhe.edu\nOrganization: Okcforum Unix Users Group\nX-Newsreader: TIN [version 1.1 PL6]\nLines: 18\n\nCharley Wingate (mangoe@cs.umd.edu) wrote:\n: \n: >> Please enlighten me. How is omnipotence contradictory?\n: \n: >By definition, all that can occur in the universe is governed by the rules\n: >of nature. Thus god cannot break them. Anything that god does must be allowed\n: >in the rules somewhere. Therefore, omnipotence CANNOT exist! It contradicts\n: >the rules of nature.\n: \n: Obviously, an omnipotent god can change the rules.\n\nWhen you say, "By definition", what exactly is being defined;\ncertainly not omnipotence. You seem to be saying that the "rules of\nnature" are pre-existant somehow, that they not only define nature but\nactually cause it. If that\'s what you mean I\'d like to hear your\nfurther thoughts on the question.\n\nBill\n',
{'category': 'alt.atheism'})
從向量儲存區刪除項目
# Delete documents by passing one or more keys/ids
vector_store.index.drop_keys(ids[0])
1
檢查已建立的索引
一旦建構了 Redis
VectorStore 物件,如果 Redis 中尚不存在索引,則會建立索引。可以使用 rvl
和 redis-cli
命令列工具來檢查索引。如果您已安裝上述的 redisvl
,則可以使用 rvl
命令列工具來檢查索引。
# assumes you're running Redis locally (use --host, --port, --password, --username, to change this)
!rvl index listall --port 6379
[32m17:54:50[0m [34m[RedisVL][0m [1;30mINFO[0m Using Redis address from environment variable, REDIS_URL
[32m17:54:50[0m [34m[RedisVL][0m [1;30mINFO[0m Indices:
[32m17:54:50[0m [34m[RedisVL][0m [1;30mINFO[0m 1. newsgroups
Redis
VectorStore 實作將嘗試為透過 from_texts
、from_texts_return_keys
和 from_documents
方法傳遞的任何中繼資料產生索引結構描述(用於篩選的欄位)。這樣一來,無論傳遞何種中繼資料,都將被索引到 Redis 搜尋索引中,以便可以根據這些欄位進行篩選。
下面我們展示了從上面定義的中繼資料建立的欄位
!rvl index info -i newsgroups --port 6379
[32m17:54:50[0m [34m[RedisVL][0m [1;30mINFO[0m Using Redis address from environment variable, REDIS_URL
Index Information:
╭──────────────┬────────────────┬────────────────┬─────────────────┬────────────╮
│ Index Name │ Storage Type │ Prefixes │ Index Options │ Indexing │
├──────────────┼────────────────┼────────────────┼─────────────────┼────────────┤
│ newsgroups │ HASH │ ['newsgroups'] │ [] │ 0 │
╰──────────────┴────────────────┴────────────────┴─────────────────┴────────────╯
Index Fields:
╭───────────┬─────────────┬────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬─────────────────┬────────────────╮
│ Name │ Attribute │ Type │ Field Option │ Option Value │ Field Option │ Option Value │ Field Option │ Option Value │ Field Option │ Option Value │
├───────────┼─────────────┼────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼─────────────────┼────────────────┤
│ text │ text │ TEXT │ WEIGHT │ 1 │ │ │ │ │ │ │
│ embedding │ embedding │ VECTOR │ algorithm │ FLAT │ data_type │ FLOAT32 │ dim │ 768 │ distance_metric │ COSINE │
│ category │ category │ TAG │ SEPARATOR │ | │ │ │ │ │ │ │
╰───────────┴─────────────┴────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴─────────────────┴────────────────╯
!rvl stats -i newsgroups --port 6379
[32m17:54:51[0m [34m[RedisVL][0m [1;30mINFO[0m Using Redis address from environment variable, REDIS_URL
Statistics:
╭─────────────────────────────┬────────────╮
│ Stat Key │ Value │
├─────────────────────────────┼────────────┤
│ num_docs │ 249 │
│ num_terms │ 16178 │
│ max_doc_id │ 250 │
│ num_records │ 50394 │
│ percent_indexed │ 1 │
│ hash_indexing_failures │ 0 │
│ number_of_uses │ 2 │
│ bytes_per_record_avg │ 38.2743 │
│ doc_table_size_mb │ 0.0263586 │
│ inverted_sz_mb │ 1.83944 │
│ key_table_size_mb │ 0.00932026 │
│ offset_bits_per_record_avg │ 10.6699 │
│ offset_vectors_sz_mb │ 0.089057 │
│ offsets_per_term_avg │ 1.38937 │
│ records_per_doc_avg │ 202.386 │
│ sortable_values_size_mb │ 0 │
│ total_indexing_time │ 72.444 │
│ total_inverted_index_blocks │ 16207 │
│ vector_index_sz_mb │ 3.01776 │
╰─────────────────────────────┴────────────╯
查詢向量儲存區
一旦您的向量儲存區已建立,並且已新增相關文件,您很可能希望在執行您的鏈或代理程式期間查詢它。
直接查詢
可以按如下方式執行簡單的相似性搜尋
query = "Tell me about space exploration"
results = vector_store.similarity_search(query, k=2)
print("Simple Similarity Search Results:")
for doc in results:
print(f"Content: {doc.page_content[:100]}...")
print(f"Metadata: {doc.metadata}")
print()
Simple Similarity Search Results:
Content: From: aa429@freenet.carleton.ca (Terry Ford)
Subject: A flawed propulsion system: Space Shuttle
X-Ad...
Metadata: {'category': 'sci.space'}
Content: From: nsmca@aurora.alaska.edu
Subject: Space Design Movies?
Article-I.D.: aurora.1993Apr23.124722.1
...
Metadata: {'category': 'sci.space'}
如果您想執行相似性搜尋並接收相應的分數,您可以執行
# Similarity search with score and filter
scored_results = vector_store.similarity_search_with_score(query, k=2)
print("Similarity Search with Score Results:")
for doc, score in scored_results:
print(f"Content: {doc.page_content[:100]}...")
print(f"Metadata: {doc.metadata}")
print(f"Score: {score}")
print()
Similarity Search with Score Results:
Content: From: aa429@freenet.carleton.ca (Terry Ford)
Subject: A flawed propulsion system: Space Shuttle
X-Ad...
Metadata: {'category': 'sci.space'}
Score: 0.569670975208
Content: From: nsmca@aurora.alaska.edu
Subject: Space Design Movies?
Article-I.D.: aurora.1993Apr23.124722.1
...
Metadata: {'category': 'sci.space'}
Score: 0.590400338173
透過轉換為檢索器來查詢
您也可以將向量儲存區轉換為檢索器,以便在您的鏈中更輕鬆地使用。
retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 2})
retriever.invoke("What planet in the solar system has the largest number of moons?")
[Document(metadata={'category': 'sci.space'}, page_content='Subject: Re: Comet in Temporary Orbit Around Jupiter?\nFrom: Robert Coe <bob@1776.COM>\nDistribution: world\nOrganization: 1776 Enterprises, Sudbury MA\nLines: 23\n\njgarland@kean.ucs.mun.ca writes:\n\n> >> Also, perihelions of Gehrels3 were:\n> >> \n> >> April 1973 83 jupiter radii\n> >> August 1970 ~3 jupiter radii\n> > \n> > Where 1 Jupiter radius = 71,000 km = 44,000 mi = 0.0005 AU. So the\n> > 1970 figure seems unlikely to actually be anything but a perijove.\n> > Is that the case for the 1973 figure as well?\n> > -- \n> Sorry, _perijoves_...I\'m not used to talking this language.\n\nHmmmm.... The prefix "peri-" is Greek, not Latin, so it\'s usually used\nwith the Greek form of the name of the body being orbited. (That\'s why\nit\'s "perihelion" rather than "perisol", "perigee" rather than "periterr",\nand "pericynthion" rather than "perilune".) So for Jupiter I\'d expect it\nto be something like "perizeon".) :^)\n\n ___ _ - Bob\n /__) _ / / ) _ _\n(_/__) (_)_(_) (___(_)_(/_______________________________________ bob@1776.COM\nRobert K. Coe ** 14 Churchill St, Sudbury, Massachusetts 01776 ** 508-443-3265\n'),
Document(metadata={'category': 'sci.space'}, page_content='From: pyron@skndiv.dseg.ti.com (Dillon Pyron)\nSubject: Re: Why not give $1 billion to first year-long moon residents?\nLines: 42\nNntp-Posting-Host: skndiv.dseg.ti.com\nReply-To: pyron@skndiv.dseg.ti.com\nOrganization: TI/DSEG VAX Support\n\n\nIn article <1qve4kINNpas@sal-sun121.usc.edu>, schaefer@sal-sun121.usc.edu (Peter Schaefer) writes:\n>In article <1993Apr19.130503.1@aurora.alaska.edu>, nsmca@aurora.alaska.edu writes:\n>|> In article <6ZV82B2w165w@theporch.raider.net>, gene@theporch.raider.net (Gene Wright) writes:\n>|> > With the continuin talk about the "End of the Space Age" and complaints \n>|> > by government over the large cost, why not try something I read about \n>|> > that might just work.\n>|> > \n>|> > Announce that a reward of $1 billion would go to the first corporation \n>|> > who successfully keeps at least 1 person alive on the moon for a year. \n>|> > Then you\'d see some of the inexpensive but not popular technologies begin \n>|> > to be developed. THere\'d be a different kind of space race then!\n>|> > \n>|> > --\n>|> > gene@theporch.raider.net (Gene Wright)\n>|> > theporch.raider.net 615/297-7951 The MacInteresteds of Nashville\n>|> ====\n>|> If that were true, I\'d go for it.. I have a few friends who we could pool our\n>|> resources and do it.. Maybe make it a prize kind of liek the "Solar Car Race"\n>|> in Australia..\n>|> Anybody game for a contest!\n>|> \n>|> ==\n>|> Michael Adams, nsmca@acad3.alaska.edu -- I\'m not high, just jacked\n>\n>\n>Oh gee, a billion dollars! That\'d be just about enough to cover the cost of the\n>feasability study! Happy, Happy, JOY! JOY!\n>\n\nFeasability study?? What a wimp!! While you are studying, others would be\ndoing. Too damn many engineers doing way too little engineering.\n\n"He who sits on his arse sits on his fortune" - Sir Richard Francis Burton\n--\nDillon Pyron | The opinions expressed are those of the\nTI/DSEG Lewisville VAX Support | sender unless otherwise stated.\n(214)462-3556 (when I\'m here) |\n(214)492-4656 (when I\'m home) |Texans: Vote NO on Robin Hood. We need\npyron@skndiv.dseg.ti.com |solutions, not gestures.\nPADI DM-54909 |\n\n')]
用於檢索增強生成的使用方式
有關如何將此向量儲存區用於檢索增強生成 (RAG) 的指南,請參閱以下章節
Redis 特有功能
Redis 為向量搜尋提供了一些獨特的功能
具有中繼資料篩選的相似性搜尋
我們可以根據中繼資料篩選搜尋結果
from redisvl.query.filter import Tag
query = "Tell me about space exploration"
# Create a RedisVL filter expression
filter_condition = Tag("category") == "sci.space"
filtered_results = vector_store.similarity_search(query, k=2, filter=filter_condition)
print("Filtered Similarity Search Results:")
for doc in filtered_results:
print(f"Content: {doc.page_content[:100]}...")
print(f"Metadata: {doc.metadata}")
print()
Filtered Similarity Search Results:
Content: From: aa429@freenet.carleton.ca (Terry Ford)
Subject: A flawed propulsion system: Space Shuttle
X-Ad...
Metadata: {'category': 'sci.space'}
Content: From: nsmca@aurora.alaska.edu
Subject: Space Design Movies?
Article-I.D.: aurora.1993Apr23.124722.1
...
Metadata: {'category': 'sci.space'}
最大邊際相關性搜尋
最大邊際相關性搜尋有助於獲得多樣化的結果
# Maximum marginal relevance search with filter
mmr_results = vector_store.max_marginal_relevance_search(
query, k=2, fetch_k=10, filter=filter_condition
)
print("Maximum Marginal Relevance Search Results:")
for doc in mmr_results:
print(f"Content: {doc.page_content[:100]}...")
print(f"Metadata: {doc.metadata}")
print()
Maximum Marginal Relevance Search Results:
Content: From: aa429@freenet.carleton.ca (Terry Ford)
Subject: A flawed propulsion system: Space Shuttle
X-Ad...
Metadata: {'category': 'sci.space'}
Content: From: moroney@world.std.com (Michael Moroney)
Subject: Re: Vulcan? (No, not the guy with the ears!)
...
Metadata: {'category': 'sci.space'}
鏈的使用方式
下面的程式碼示範了如何在簡單的 RAG 鏈中使用向量儲存區作為檢索器
pip install -qU "langchain[openai]"
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
from langchain.chat_models import init_chat_model
llm = init_chat_model("gpt-4o-mini", model_provider="openai")
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
# Prompt
prompt = ChatPromptTemplate.from_messages(
[
(
"human",
"""You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.
Question: {question}
Context: {context}
Answer:""",
),
]
)
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
rag_chain.invoke("Describe the Space Shuttle program?")
'The Space Shuttle program was a NASA initiative that enabled reusable spacecraft to transport astronauts and cargo to and from low Earth orbit. It conducted a variety of missions, including satellite deployment, scientific research, and assembly of the International Space Station, and typically carried a crew of five astronauts. Although it achieved many successes, the program faced criticism for its safety concerns and the complexity of its propulsion system.'
連線到現有的索引
為了在使用 Redis
VectorStore 時索引相同的中繼資料,您需要傳入相同的 index_schema
,可以是 YAML 檔案的路徑或字典。以下示範如何從索引取得結構描述並連線到現有的索引。
# write the schema to a yaml file
vector_store.index.schema.to_yaml("redis_schema.yaml")
# now we can connect to our existing index as follows
new_rdvs = RedisVectorStore(
embeddings,
redis_url=REDIS_URL,
schema_path="redis_schema.yaml",
)
results = new_rdvs.similarity_search("Space Shuttle Propulsion System", k=3)
print(results[0])
18:19:58 redisvl.index.index INFO Index already exists, not overwriting.
page_content='From: aa429@freenet.carleton.ca (Terry Ford)
Subject: A flawed propulsion system: Space Shuttle
X-Added: Forwarded by Space Digest
Organization: [via International Space University]
Original-Sender: isu@VACATION.VENARI.CS.CMU.EDU
Distribution: sci
Lines: 13
For an essay, I am writing about the space shuttle and a need for a better
propulsion system. Through research, I have found that it is rather clumsy
(i.e. all the checks/tests before launch), the safety hazards ("sitting
on a hydrogen bomb"), etc.. If you have any beefs about the current
space shuttle program Re: propulsion, please send me your ideas.
Thanks a lot.
--
Terry Ford [aa429@freenet.carleton.ca]
Nepean, Ontario, Canada.
' metadata={'category': 'sci.space'}
# compare the two schemas to verify they are the same
new_rdvs.index.schema == vector_store.index.schema
True
清除向量儲存區
# Clear vector store
vector_store.index.delete(drop=True)
API 參考
有關所有 RedisVectorStore 功能和配置的詳細文件,請前往 API 參考:https://langchain-python.dev.org.tw/api_reference/redis/vectorstores/langchain_redis.vectorstores.RedisVectorStore.html