跳到主要內容
Open In ColabOpen on GitHub

SingleStoreDB

SingleStoreDB 是一個強大、高效能的分散式 SQL 資料庫解決方案,旨在在 雲端 和內部部署環境中表現出色。它擁有通用的功能集,提供無縫的部署選項,同時提供無與倫比的效能。

SingleStoreDB 的一個突出特點是其對向量儲存和運算的進階支援,使其成為需要複雜 AI 功能(例如文字相似度比對)的應用程式的理想選擇。憑藉內建的向量函數,如 dot_producteuclidean_distance,SingleStoreDB 使開發人員能夠高效地實作複雜的演算法。

對於熱衷於在 SingleStoreDB 中利用向量資料的開發人員,有一個全面的教學課程可用,指導他們深入了解 使用向量資料 的複雜性。本教學課程深入探討了 SingleStoreDB 中的向量儲存,展示了其促進基於向量相似度搜尋的能力。透過利用向量索引,可以以卓越的速度執行查詢,從而實現相關資料的快速檢索。

此外,SingleStoreDB 的向量儲存與 基於 Lucene 的全文索引 無縫整合,實現了強大的文字相似度搜尋。使用者可以根據文件元資料物件的選定欄位篩選搜尋結果,從而提高查詢精確度。

SingleStoreDB 的與眾不同之處在於其能夠以各種方式組合向量和全文搜尋,從而提供彈性和多功能性。無論是透過文字或向量相似度預先篩選並選擇最相關的資料,還是採用加權總和方法來計算最終相似度分數,開發人員都可以使用多種選項。

從本質上講,SingleStoreDB 為管理和查詢向量資料提供了一個全面的解決方案,為 AI 驅動的應用程式提供無與倫比的效能和彈性。

您需要使用 pip install -qU langchain-community 安裝 langchain-community 才能使用此整合

# Establishing a connection to the database is facilitated through the singlestoredb Python connector.
# Please ensure that this connector is installed in your working environment.
%pip install --upgrade --quiet singlestoredb
import getpass
import os

# We want to use OpenAIEmbeddings so we have to get the OpenAI API Key.
if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
from langchain_community.vectorstores import SingleStoreDB
from langchain_community.vectorstores.utils import DistanceStrategy
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
# loading docs
# we will use some artificial data for this example
docs = [
Document(
page_content="""In the parched desert, a sudden rainstorm brought relief,
as the droplets danced upon the thirsty earth, rejuvenating the landscape
with the sweet scent of petrichor.""",
metadata={"category": "rain"},
),
Document(
page_content="""Amidst the bustling cityscape, the rain fell relentlessly,
creating a symphony of pitter-patter on the pavement, while umbrellas
bloomed like colorful flowers in a sea of gray.""",
metadata={"category": "rain"},
),
Document(
page_content="""High in the mountains, the rain transformed into a delicate
mist, enveloping the peaks in a mystical veil, where each droplet seemed to
whisper secrets to the ancient rocks below.""",
metadata={"category": "rain"},
),
Document(
page_content="""Blanketing the countryside in a soft, pristine layer, the
snowfall painted a serene tableau, muffling the world in a tranquil hush
as delicate flakes settled upon the branches of trees like nature's own
lacework.""",
metadata={"category": "snow"},
),
Document(
page_content="""In the urban landscape, snow descended, transforming
bustling streets into a winter wonderland, where the laughter of
children echoed amidst the flurry of snowballs and the twinkle of
holiday lights.""",
metadata={"category": "snow"},
),
Document(
page_content="""Atop the rugged peaks, snow fell with an unyielding
intensity, sculpting the landscape into a pristine alpine paradise,
where the frozen crystals shimmered under the moonlight, casting a
spell of enchantment over the wilderness below.""",
metadata={"category": "snow"},
),
]

embeddings = OpenAIEmbeddings()

有多種方法可以建立與資料庫的連線。您可以設定環境變數或將具名參數傳遞給 SingleStoreDB 建構函式。或者,您可以將這些參數提供給 from_documentsfrom_texts 方法。

# Setup connection url as environment variable
os.environ["SINGLESTOREDB_URL"] = "root:pass@localhost:3306/db"

# Load documents to the store
docsearch = SingleStoreDB.from_documents(
docs,
embeddings,
table_name="notebook", # use table with a custom name
)
query = "trees in the snow"
docs = docsearch.similarity_search(query) # Find documents that correspond to the query
print(docs[0].page_content)

SingleStoreDB 透過允許使用者透過基於元資料欄位進行預先篩選來增強和改進搜尋結果,從而提升了搜尋能力。此功能使開發人員和資料分析師能夠微調查詢,確保搜尋結果精確地根據他們的需求進行客製化。透過使用特定的元資料屬性篩選搜尋結果,使用者可以縮小查詢範圍,僅關注相關的資料子集。

query = "trees branches"
docs = docsearch.similarity_search(
query, filter={"category": "snow"}
) # Find documents that correspond to the query and has category "snow"
print(docs[0].page_content)

透過利用 ANN 向量索引,提高 SingleStore DB 8.5 或更高版本的搜尋效率。透過在向量儲存物件建立期間設定 use_vector_index=True,您可以啟用此功能。此外,如果您的向量維度與預設 OpenAI 嵌入大小 1536 不同,請確保相應地指定 vector_size 參數。

SingleStoreDB 提供了多樣化的搜尋策略,每種策略都經過精心設計,以滿足特定的用例和使用者偏好。預設的 VECTOR_ONLY 策略利用向量運算(如 dot_producteuclidean_distance)來直接計算向量之間的相似度分數,而 TEXT_ONLY 則採用基於 Lucene 的全文搜尋,特別適用於以文字為中心的應用程式。對於尋求平衡方法的用戶,FILTER_BY_TEXT 首先根據文字相似度改進結果,然後再進行向量比較,而 FILTER_BY_VECTOR 則優先考慮向量相似度,在評估文字相似度之前篩選結果以獲得最佳匹配。值得注意的是,FILTER_BY_TEXTFILTER_BY_VECTOR 都需要全文索引才能運作。此外,WEIGHTED_SUM 作為一種複雜的策略出現,透過權衡向量和文字相似度來計算最終相似度分數,儘管它僅使用點積距離計算,並且也需要全文索引。這些多功能的策略使使用者能夠根據其獨特的需求微調搜尋,從而促進高效且精確的資料檢索和分析。此外,SingleStoreDB 的混合方法(以 FILTER_BY_TEXTFILTER_BY_VECTORWEIGHTED_SUM 策略為例)無縫地融合了向量和基於文字的搜尋,以最大限度地提高效率和準確性,確保使用者可以為各種應用程式充分利用平台的功能。

docsearch = SingleStoreDB.from_documents(
docs,
embeddings,
distance_strategy=DistanceStrategy.DOT_PRODUCT, # Use dot product for similarity search
use_vector_index=True, # Use vector index for faster search
use_full_text_search=True, # Use full text index
)

vectorResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreDB.SearchStrategy.VECTOR_ONLY,
filter={"category": "rain"},
)
print(vectorResults[0].page_content)

textResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreDB.SearchStrategy.TEXT_ONLY,
)
print(textResults[0].page_content)

filteredByTextResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_TEXT,
filter_threshold=0.1,
)
print(filteredByTextResults[0].page_content)

filteredByVectorResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_VECTOR,
filter_threshold=0.1,
)
print(filteredByVectorResults[0].page_content)

weightedSumResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM,
text_weight=0.2,
vector_weight=0.8,
)
print(weightedSumResults[0].page_content)

多模態範例:利用 CLIP 和 OpenClip 嵌入

在多模態資料分析領域,整合圖像和文字等多種資訊類型已變得越來越重要。 CLIP 是一種促進此類整合的強大工具,它是一種能夠將圖像和文字嵌入到共享語義空間中的尖端模型。透過這樣做,CLIP 能夠透過相似度搜尋檢索不同模態的相關內容。

為了說明,讓我們考慮一個應用場景,我們的目標是有效地分析多模態資料。在本範例中,我們利用了 OpenClip 多模態嵌入 的功能,它利用了 CLIP 的框架。透過 OpenClip,我們可以無縫地嵌入文字描述以及相應的圖像,從而實現全面的分析和檢索任務。無論是根據文字查詢識別視覺上相似的圖像,還是尋找與特定視覺內容相關的相關文字段落,OpenClip 都能讓使用者以卓越的效率和準確性探索和提取多模態資料的見解。

%pip install -U langchain openai singlestoredb langchain-experimental # (newest versions required for multi-modal)
import os

from langchain_community.vectorstores import SingleStoreDB
from langchain_experimental.open_clip import OpenCLIPEmbeddings

os.environ["SINGLESTOREDB_URL"] = "root:pass@localhost:3306/db"

TEST_IMAGES_DIR = "../../modules/images"

docsearch = SingleStoreDB(OpenCLIPEmbeddings())

image_uris = sorted(
[
os.path.join(TEST_IMAGES_DIR, image_name)
for image_name in os.listdir(TEST_IMAGES_DIR)
if image_name.endswith(".jpg")
]
)

# Add images
docsearch.add_images(uris=image_uris)

此頁面是否對您有幫助?