Spring AI(6)——向量存儲

向量數據庫是一種特殊類型的數據庫,在 AI 應用中發揮著至關重要的作用。

在向量數據庫中,查詢與傳統關系型數據庫不同。它們執行的是相似性搜索,而非精確匹配。當給定一個向量作為查詢時,向量數據庫會返回與該查詢向量“相似”的向量。

Spring AI 通過?VectorStore?接口提供了一個抽象的 API,用于與向量數據庫交互。

VectorStore接口中主要方法:

public interface VectorStore extends DocumentWriter {default String getName() {return this.getClass().getSimpleName();}// 向向量數據庫寫入數據void add(List<Document> documents);// 根據id刪除數據void delete(List<String> idList);// 根據過濾表達式刪除數據void delete(Filter.Expression filterExpression);default void delete(String filterExpression) { ... };// 進行相似度搜索List<Document> similaritySearch(String query);List<Document> similaritySearch(SearchRequest request);default <T> Optional<T> getNativeClient() {return Optional.empty();}
}

支持的向量數據庫:

  • Azure Vector Search
  • Apache Cassandra
  • Chroma Vector Store
  • Elasticsearch Vector Store
  • GemFire Vector Store
  • MariaDB Vector Store
  • Milvus Vector Store
  • MongoDB Atlas Vector Store
  • Neo4j Vector Store
  • OpenSearch Vector Store
  • Oracle Vector Store
  • PgVector Store
  • Pinecone Vector Store
  • Qdrant Vector Store
  • Redis Vector Store
  • SAP Hana Vector Store
  • Typesense Vector Store
  • Weaviate Vector Store
  • SimpleVectorStore - 一個簡單的持久化向量存儲實現,適合教學目的。

SimpleVectorStore使用

注意:需要提前啟動上篇博客中通過Ollama安裝的嵌入模型

SimpleVectorStore將向量數據存儲在內存中。

導入jar

        <dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-vector-store</artifactId></dependency>

創建SimpleVectorStore對象

    @Beanpublic SimpleVectorStore vectorStore() {return SimpleVectorStore.builder(embeddingModel).build();}

創建對象時,將存儲對象和嵌入模型進行關聯。關于嵌入模型的使用,參考:

Spring AI(5)——通過嵌入模型進行數據的向量化處理-CSDN博客

向SimpleVectorStore對象中寫入測試數據

本例中,創建Document對象時,三個參數分別為:文檔id,文檔內容,文檔的元數據。

    @PostConstructpublic void init() {List<Document> documents = List.of(new Document("1", "今天天氣不錯", Map.of("country", "鄭州", "date", "2025-05-13")),new Document("2", "天氣不錯,適合旅游", Map.of("country", "開封", "date", "2025-05-15")),new Document("3", "去哪里旅游好呢", Map.of("country", "洛陽", "date", "2025-05-15")));// 存儲數據simpleVectorStore.add(documents);}

通過調試可以看出,?SimpleVectorStore對象中存儲的原始文檔信息和向量化后的數據。

進行相似度搜索

根據字符串內容進行搜索

    @GetMapping("/store")public String store(String message) {// 相似度檢索List<Document> list= simpleVectorStore.similaritySearch("旅游");System.out.println(list.size());System.out.println(list.get(0).getText());return "success";}

通過調試可以看到,對所有的數據進行向量的相似度計算,并進行打分,計算結果按照score的降序排列?。

根據元數據過濾器進行搜索

使用字符串設置搜索條件

例如:

  • "country == 'BG'"

  • "genre == 'drama' && year >= 2020"

  • "genre in ['comedy', 'documentary', 'drama']"

SearchRequest request = SearchRequest.builder().query("World").filterExpression("country == 'Bulgaria'").build();

使用Filter.Expression設置搜索條件

可以使用?FilterExpressionBuilder?創建?Filter.Expression?的實例。一個簡單的示例如下:

FilterExpressionBuilder b = new FilterExpressionBuilder();
Expression expression = this.b.eq("country", "BG").build();

可以使用以下運算符構建復雜的表達式:

EQUALS: '=='
MINUS : '-'
PLUS: '+'
GT: '>'
GE: '>='
LT: '<'
LE: '<='
NE: '!='

可以使用以下運算符組合表達式:

AND: 'AND' | 'and' | '&&';
OR: 'OR' | 'or' | '||';

參考示例:

Expression exp = b.and(b.eq("genre", "drama"), b.gte("year", 2020)).build();

還可以使用以下運算符:

IN: 'IN' | 'in';
NIN: 'NIN' | 'nin';
NOT: 'NOT' | 'not';

參考示例:

Expression exp = b.and(b.in("genre", "drama", "documentary"), b.not(b.lt("year", 2020))).build();

測試案例:?

    @GetMapping("/store")public String store(String message) {// 相似度檢索// List<Document> list = simpleVectorStore.similaritySearch("旅游");// 創建過濾器對象FilterExpressionBuilder b = new FilterExpressionBuilder();Filter.Expression filter = b.eq("country", "鄭州").build();// Filter.Expression filter = b.and(b.eq("country", "鄭州"), b.gte("date", "2025-05-15")).build();;// 創建搜索對象SearchRequest request = SearchRequest.builder().query("旅游") // 搜索內容.filterExpression(filter) // 指定過濾器對象.build();List<Document> list = simpleVectorStore.similaritySearch(request);System.out.println(list.size());System.out.println(list.get(0).getText());return "success";}

刪除數據

    @GetMapping("/store2")public String store2(String message) {// 刪除數據simpleVectorStore.delete(List.of("3"));return "success";}

注意:也可以根據元數據過濾器進行刪除,本文不再演示

?Milvus進行向量存儲

關于milvus的介紹和環境安裝,參考:

LangChain4j(16)——使用milvus進行向量存儲-CSDN博客

注意:需要提前啟動上篇博客中通過Ollama安裝的嵌入模型

導入jar?

<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-vector-store-milvus</artifactId>
</dependency>

yml配置

在原來的基礎上,增加如下配置:

spring:ai:vectorstore:milvus:client:host: "localhost"port: 19530databaseName: "myai"collectionName: "vector_store"embeddingDimension: 768indexType: IVF_FLATmetricType: COSINE

該配置中指定了milvus的數據庫名,collection名稱,向量緯度,索引的類型,向量搜索的算法等,更多的屬性設置可以參考官網:

屬性描述默認值

spring.ai.vectorstore.milvus.database-name

要使用的 Milvus 數據庫名稱。

default

spring.ai.vectorstore.milvus.collection-name

用于存儲向量的 Milvus Collection 名稱

vector_store

spring.ai.vectorstore.milvus.initialize-schema

是否初始化 Milvus 后端

false

spring.ai.vectorstore.milvus.embedding-dimension

存儲在 Milvus Collection 中的向量維度。

1536

spring.ai.vectorstore.milvus.index-type

為 Milvus Collection 創建的索引類型。

IVF_FLAT

spring.ai.vectorstore.milvus.metric-type

用于 Milvus Collection 的度量類型(Metric Type)。

COSINE

spring.ai.vectorstore.milvus.index-parameters

用于 Milvus Collection 的索引參數。

{"nlist":1024}

spring.ai.vectorstore.milvus.id-field-name

Collection 的 ID 字段名稱

doc_id

spring.ai.vectorstore.milvus.is-auto-id

布爾標志,指示 ID 字段是否使用 auto-id

false

spring.ai.vectorstore.milvus.content-field-name

Collection 的內容字段名稱

content

spring.ai.vectorstore.milvus.metadata-field-name

Collection 的元數據字段名稱

metadata

spring.ai.vectorstore.milvus.embedding-field-name

Collection 的嵌入字段名稱

embedding

spring.ai.vectorstore.milvus.client.host

主機名稱或地址。

localhost

spring.ai.vectorstore.milvus.client.port

連接端口。

19530

spring.ai.vectorstore.milvus.client.uri

Milvus 實例的 URI

-

spring.ai.vectorstore.milvus.client.token

用作身份識別和認證目的的 Token。

-

spring.ai.vectorstore.milvus.client.connect-timeout-ms

客戶端通道的連接超時值。超時值必須大于零。

10000

spring.ai.vectorstore.milvus.client.keep-alive-time-ms

客戶端通道的 Keep-alive 時間值。Keep-alive 值必須大于零。

55000

spring.ai.vectorstore.milvus.client.keep-alive-timeout-ms

客戶端通道的 Keep-alive 超時值。超時值必須大于零。

20000

spring.ai.vectorstore.milvus.client.rpc-deadline-ms

愿意等待服務器回復的截止時間。設置截止時間后,客戶端在遇到由網絡波動引起的快速 RPC 失敗時將等待。截止時間值必須大于或等于零。

0

spring.ai.vectorstore.milvus.client.client-key-path

用于 TLS 雙向認證的 client.key 路徑,僅當 "secure" 為 true 時生效

-

spring.ai.vectorstore.milvus.client.client-pem-path

用于 TLS 雙向認證的 client.pem 路徑,僅當 "secure" 為 true 時生效

-

spring.ai.vectorstore.milvus.client.ca-pem-path

用于 TLS 雙向認證的 ca.pem 路徑,僅當 "secure" 為 true 時生效

-

spring.ai.vectorstore.milvus.client.server-pem-path

用于 TLS 單向認證的 server.pem 路徑,僅當 "secure" 為 true 時生效。

-

spring.ai.vectorstore.milvus.client.server-name

設置 SSL 主機名檢查的目標名稱覆蓋,僅當 "secure" 為 True 時生效。注意:此值會傳遞給 grpc.ssl_target_name_override

-

spring.ai.vectorstore.milvus.client.secure

保護此連接的授權,設置為 True 以啟用 TLS。

false

spring.ai.vectorstore.milvus.client.idle-timeout-ms

客戶端通道的空閑超時值。超時值必須大于零。

24h

spring.ai.vectorstore.milvus.client.username

此連接的用戶名和密碼。

root

spring.ai.vectorstore.milvus.client.password

此連接的密碼。

milvus

通過attu創建collection

注意:collection中的字段名稱使用的是上面屬性中的默認名稱:

spring.ai.vectorstore.milvus.id-field-name=doc_id

spring.ai.vectorstore.milvus.content-field-name=content
spring.ai.vectorstore.milvus.metadata-field-name=metadata
spring.ai.vectorstore.milvus.embedding-field-name=embedding

注入MilvusVectorStore對象

    @Resourceprivate MilvusVectorStore milvusVectorStore;

添加測試數據

    @PostConstructpublic void init() {List<Document> documents = List.of(new Document("今天天氣不錯", Map.of("country", "鄭州", "date", "2025-05-13")),new Document("天氣不錯,適合旅游", Map.of("country", "開封", "date", "2025-05-15")),new Document("去哪里旅游好呢", Map.of("country", "洛陽", "date", "2025-05-15")));// 存儲數據milvusVectorStore.add(documents);}

本例沒有指定Document的id,id會隨機生成

相似度搜索

    @GetMapping("/search")public String search(String message) {// 相似度檢索List<Document> list = milvusVectorStore.similaritySearch("旅游");System.out.println(list.size());System.out.println(list.get(0).getText());return "success";}@GetMapping("/search5")public String search5(String message) {MilvusSearchRequest request = MilvusSearchRequest.milvusBuilder().query("旅游").topK(5).similarityThreshold(0.7).filterExpression("date == '2025-05-15'") // Ignored if nativeExpression is set//.searchParamsJson("{\"nprobe\":128}").build();// 相似度檢索List<Document> list = milvusVectorStore.similaritySearch(request);System.out.println(list.size());System.out.println(list.get(0).getText());return "success";}

top_k:?表示根據token排名,只考慮前k個token

similarity threshold:相似度的閾值

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/83260.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/83260.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/83260.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Qt功能區:簡介與安裝

Qt功能區 1. 功能區簡介2. SARibbon2.1 簡介2.2 編譯與安裝采用CMake-gui進行編譯采用VS進行編譯安裝與使用 Qt 官方不支持 Ribbon 風格&#xff08;Ribbon UI 風格是微軟開創的&#xff0c;具有專利許可協議&#xff0c;許可協議對從構建 UI 的指令到每個按鈕間的空格數都做了…

iOS safari和android chrome開啟網頁調試與檢查器的方法

手機開啟遠程調試教程&#xff08;適用于 Chrome / Safari&#xff09; 前端移動端調試指南&#xff5c;適用 iPhone 和 Android&#xff5c;WebDebugX 出品 本教程將詳細介紹如何在 iPhone 和 Android 手機上開啟網頁檢查器&#xff0c;配合 WebDebugX 實現遠程調試。教程包含…

Golang企業級商城高并發微服務實戰

Golang企業級商城高并發微服務實戰包含內容介紹&#xff1a; 從零開始講了百萬級單體高并發架構、千萬級微服務架構&#xff0c;其中包含Rpc實現微服務、微服務的跨語言調用jsonrpc和protobuf、protobuf的安裝、protobuf高級語法、protobuf結合Grpc實現微服務實戰、微服務服務…

實現可靠的 WebSocket 連接:心跳與自動重連的最佳實踐

概覽 本文將手把手教你如何從零編寫一個可用于直播或在線聊天的 WSocket 類&#xff0c;依次實現連接建立、心跳檢測、斷線重連、消息收發以及資源清理等功能。我們將結合 WebSocket API 的標準用法、心跳保持 和 重連策略&#xff0c;并充分運用現代 JavaScript 語法&#xf…

UEFI Spec 學習筆記---33 - Human Interface Infrastructure Overview(1)

33 - Human Interface Infrastructure Overview 本章節主要用于介紹Human Interface Infrastructure&#xff08;HII&#xff09;架構介紹&#xff0c;描述如何通過 HII 來管理用戶的輸入&#xff0c;以及描述在 UEFI spec 中涉及 HII 相關的 Protocol、function 和類型定義。…

ip命令詳解

控制網卡的硬件狀態 ip link set ens36 down ip link set ens36 up 修改網卡名稱&#xff08;臨時&#xff09; ip link set ens36 down ip link set ens36 name xxx 修改網卡的mac地址 ip link set ens36 down ip link set xxx name ens36 查看ip的addr ip addr show ip ad…

hadoop中了解yarm

Hadoop中的YARN&#xff08;Yet Another Resource Negotiator&#xff09;是一種新的Hadoop資源管理器&#xff0c;是一個通用資源管理系統&#xff0c;可為上層應用提供統一的資源管理和調度。以下是其相關介紹&#xff1a; 核心思想 將JobTracker的資源管理和作業調度/監控功…

做好的QT軟件,換一個筆記本打開后發現字體很小,部分字體還被控件遮擋

出現這種情況的原因主要是屏幕的DPI&#xff08;每英寸點數&#xff09;不同。Qt中控件的大小單位為像素&#xff0c;在高DPI下&#xff0c;控件會變小&#xff0c;低DPI下控件會變大。而Qt中字體的單位默認為磅&#xff0c;無論在什么顯示器上顯示同一磅值的字體&#xff0c;其…

linux - 權限的概念

目錄 用戶權限 超級用戶與普通用戶的區別 超級用戶&#xff08;root&#xff09;&#xff1a; 普通用戶&#xff1a; 切換用戶身份 使用sudo執行高權限命令 用戶管理 用戶組管理 文件權限 文件訪問者類別 基本權限 權限表示方法 權限修改 chmod chown chgrp u…

Python函數返回值的藝術:為何True/False是更優實踐及例外情況分析

在Python編程實踐中&#xff0c;子程序的返回值設計往往是一個容易被忽視但卻至關重要的設計決策。本文將深入探討為什么返回True/False往往是更好的選擇&#xff0c;何時應該避免這種做法&#xff0c;以及如何處理與None值相關的問題。 為什么返回True/False是更好的實踐&…

STM32單片機內存分配詳細講解

單片機的內存無非就兩種&#xff0c;內部FLASH和SRAM&#xff0c;最多再加上一個外部的FLASH拓展。在這里我以STM32F103C8T6為例子講解FLASH和SRAM。 STM32F103C8T6具有64KB的閃存和20KB的SRAM。 一. Flash 1.1 定義 非易失性存儲器&#xff0c;即使在斷電后&#xff0c;其所…

【Tools】Visual Studio使用經驗介紹(包括基本功能、遠程調試、引入第三方庫等等)

這里寫目錄標題 1. VS基本使用1.1. 快捷鍵1.2. 查看變量地址1.3. 查看代碼匯編1.4. visual studio 熱重載功能的使用1.5. vs遠程服務器調試1.6. 引入第三方庫VLD1.7. release debug模式 1. VS基本使用 1.1. 快捷鍵 ctrl c :復制光標所在行 注意&#xff1a;只需要光標在這…

網絡爬蟲學習之httpx的使用

開篇 本文整理自《Python3 網絡爬蟲實戰》&#xff0c;主要是httpx的使用。 筆記整理 使用urllib庫requests庫的使用&#xff0c;已經可以爬取絕大多數網站的數據&#xff0c;但對于某些網站依然無能為力。 這是因為這些網站強制使用HTTP/2.0協議訪問&#xff0c;這時urllib和r…

Python內存管理:賦值、淺拷貝與深拷貝解析

賦值與共享資源 在Python中&#xff0c;直接賦值操作&#xff08;如 list2 list1&#xff09;會導致兩個變量共享同一個內存地址。這意味著對 list1 的修改會直接影響到 list2&#xff0c;因為它們指向同一個對象。 注意: 賦值等于完全共享資源 如果我們不希望這樣完全共享&…

CentOS7原有磁盤擴容實戰記錄(LVM非LVM)【針對GPT分區】

一、環境 二、命令及含義 fdisk ????fdisk?是一個較老的分區表創建和管理工具&#xff0c;主要支持MBR&#xff08;Master Boot Record&#xff09;格式的分區表。MBR分區表支持的硬盤單個分區最大容量為2TB&#xff0c;最多可以有4個主分區。fdisk通過命令行界面進行操…

獲取相機圖像(ROS2)

文章目錄 前言一、獲取筆記本自帶相機圖像1.打開終端2.安裝usb-cam功能包3.啟動相機節點4.再打開一個終端5.啟動rqt查看圖像(1)方法一&#xff1a;點擊窗口選項&#xff0c;打開圖像話題(2)方法二&#xff1a;使用命令行&#xff0c;直接打開圖像話題 二、獲取USB相機圖像總結 …

Go 語言中接口類型轉換為具體類型

類型轉換方法 在 Go 語言中&#xff0c;將接口類型轉換為具體類型主要有以下幾種方法&#xff1a; 1. 類型斷言&#xff08;Type Assertion&#xff09; var i interface{} "hello"// 基本形式 s : i.(string) // 將接口i轉換為string類型 fmt.Println(s) // 輸…

ES C++客戶端安裝及使用

介紹 Elasticsearch &#xff0c; 簡稱 ES &#xff0c;它是個開源分布式搜索引擎&#xff0c;它的特點有&#xff1a;分布式&#xff0c;零配置&#xff0c;自動發現&#xff0c;索引自動分片&#xff0c;索引副本機制&#xff0c;restful 風格接口&#xff0c;多數據源&…

力扣-94.二叉樹的中序遍歷

題目描述 給定一個二叉樹的根節點 root &#xff0c;返回 它的 中序 遍歷 。 class Solution { public:void inorder(TreeNode* root, vector<int>& res){//C這里&一定要加if(!root)return;inorder(root->left,res);res.push_back(root->val);inorder(ro…

《大模型微調實戰:Llama 3.0全參數優化指南》

全參數微調&#xff08;Full Parameter Fine-Tuning&#xff09;是推動大模型適應垂直領域任務的核心技術&#xff0c;尤其對于Llama 3.0這類千億級參數模型而言&#xff0c;其性能優化與場景適配能力直接決定了實際應用價值。然而&#xff0c;全參數微調面臨計算成本高、內存占…