跳至主要內容

SingleStoreDB

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

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

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

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

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 透過允許使用者透過基於 Metadata 欄位進行預先篩選來增強和完善搜尋結果,從而提升了搜尋能力。 此功能使開發人員和資料分析師能夠微調查詢,確保搜尋結果精確地針對其需求量身定制。 透過使用特定的 Metadata 屬性篩選搜尋結果,使用者可以縮小查詢範圍,僅關注相關資料子集。

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)

這個頁面有幫助嗎?