中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

b2c的電子信息網(wǎng)站系統(tǒng)清理優(yōu)化工具

b2c的電子信息網(wǎng)站,系統(tǒng)清理優(yōu)化工具,工業(yè)設(shè)計(jì)優(yōu)秀作品,濟(jì)南做網(wǎng)站建設(shè)整理不易,請不要吝嗇你的贊和收藏。 1. 前言 寫這篇文章挺不容易的,網(wǎng)絡(luò)上對(duì)于 SpringBoot 實(shí)現(xiàn) Redis 向量相似性搜索的文章總體來說篇幅較少,并且這些文章很多都寫得很粗糙,或者不是我想要的實(shí)現(xiàn)方式,所以我不得不閱…

整理不易,請不要吝嗇你的贊和收藏。

1. 前言

寫這篇文章挺不容易的,網(wǎng)絡(luò)上對(duì)于 SpringBoot 實(shí)現(xiàn) Redis 向量相似性搜索的文章總體來說篇幅較少,并且這些文章很多都寫得很粗糙,或者不是我想要的實(shí)現(xiàn)方式,所以我不得不閱讀大量官方文檔,邊試錯(cuò),邊修改,這花費(fèi)了不少時(shí)間,不過好在結(jié)果還不錯(cuò)。
話不多說,下面說下這篇文章。這篇文章將介紹兩種實(shí)現(xiàn)方式, 第一種為使用 Jedis 中的 UnifiedJedis 類實(shí)現(xiàn), 第二種為使用 SpringAI 中的 VectorStore 實(shí)現(xiàn)。通過這邊文章你將收獲,如何使用阿里百煉 Embedding 模型實(shí)現(xiàn)文本向量化,如何通過連接池獲取 UnifiedJedis 對(duì)象,如何在 SpringBoot 中實(shí)現(xiàn)向量數(shù)據(jù)的存儲(chǔ)以及使用 fTSearch 進(jìn)行向量相似性搜索,如何使用 SpringAI 的 VecotStore。

2. 前提條件

  • 已安裝 Redis Stack ,如何安裝請參考?docker compose 安裝 Redis Stack?。
  • 已對(duì) Redis 作為向量庫有了解,如不了解請參考 Redis 作為向量庫入門指南。
  • 項(xiàng)目中引入了 Spring AI Alibaba ,如何引入請參考 Spring AI Alibaba 的簡單使用 。
  • 項(xiàng)目中引入了 Redis ,如何引入請參考 SpringBoot 引入 redis 。

3. 使用 UnifiedJedis 實(shí)現(xiàn)

:這個(gè)方式需要你先創(chuàng)建向量索引,如果不了解請參考 Redis 作為向量庫入門指南 。需要注意的是這個(gè)方式基于創(chuàng)建的索引數(shù)據(jù)類型為 Hash

3.1 引入依賴

我的 SpringBoot 版本為3.2.4,spring-ai-alibaba-starter 版本升級(jí)為了 1.0.0-M3.2,jdk 版本為17。
:需要注意我之前文章使用的 Redis 客戶端為 lettuce,但因其對(duì) RedisSearch 語法支持較差,所以我改為使用 Jedis。Jedis 中的 UnifiedJedis 類對(duì) RedisSeach 語法有很好的支持。

3.1.1 引入 Redis 客戶端

我們使用 spring-boot-starter-data-redis 來集成和管理 Redis, 使用 Jedis 作為 Java 中 Redis 的客戶端,注意 SpringBoot2.0 默認(rèn)使用 lettuce 作為客戶端,需要排除 lettuce-core 包。
我的 spring-boot-starter-data-redis 版本為 3.2.4,jedis 的版本為 5.2.0。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions>
</dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId>
</dependency>
:建議引入 spring-boot-starter-parent 用來管理 SpringBoot 項(xiàng)目的依賴版本和構(gòu)建配置。
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.4</version>
</parent>

?3.1.2?引入 Spring AI Alibaba

這個(gè)實(shí)現(xiàn)方式中,項(xiàng)目中引入 spring-ai-alibaba 主要是為了調(diào)用阿里百煉 Embedding 模型實(shí)現(xiàn)文本向量化,如果你有其它的文本向量化包,可以改為引用其它的。
我使用的版本是 1.0.0-M3.2,對(duì)應(yīng) Spring AI 的版本為 1.0.0-M3。
<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId>
</dependency>

3.2 添加配置

3.2.1 添加 redis 配置

application.yml 文件中添加redis相關(guān)配置,包含 host、port、password、連接池信息等。
spring:data:redis:database: 0host: 127.0.0.1port: 6379password: gusy1234jedis:pool:# 連接池最大連接數(shù)max-active: 8# 連接池最大空閑連接數(shù)max-idle: 8# 連接池最大阻塞等待時(shí)間,負(fù)值表示沒有限制max-wait: 0# 連接池最小空閑連接數(shù)min-idle: 2# 連接超時(shí)時(shí)間(毫秒)timeout: 1000

3.3 配置連接池

3.3.1 使用自定連接池

這個(gè)是我讀 Jedis 代碼摸索出來的,也用了一些時(shí)間琢磨,在此做個(gè)記錄吧,更推薦使用 第二種。使用自定義連接池管理 UnifiedJedis:
@Bean
public UnifiedJedis unifiedJedis() {HostAndPort hostAndPort = new HostAndPort(host, port);// 設(shè)置 Jedis 客戶端配置DefaultJedisClientConfig jedisClientConfig = DefaultJedisClientConfig.builder().password(password).database(database).build();// 設(shè)置連接池參數(shù)ConnectionPoolConfig poolConfig = new ConnectionPoolConfig();poolConfig.setMaxTotal(maxActive);poolConfig.setMaxIdle(maxIdle);poolConfig.setMinIdle(minIdle);PooledConnectionProvider provider = new PooledConnectionProvider(hostAndPort, jedisClientConfig, poolConfig);return new UnifiedJedis(provider);
}

3.3.2 (推薦)使用 JedisPooled

比較意外的是,在嘗試使用 Spring AI 的 Redis VectorStore 實(shí)現(xiàn)時(shí),閱讀源碼,發(fā)現(xiàn)了一個(gè)更好的創(chuàng)建 UnifiedJedis 連接池的方式,并且是 Redis 推薦的方式( Redis 官方文檔),就是使用 JedidsPooled。 JedisPooled 繼承自 UnifiedJedis。JedisPooled 在 Jedis 版本 4.0.0 中添加,提供了 類似JedisPool 的功能,但具有更直接的 API。相比于 JedisPool ,JedisPooled 作為連接池更為簡單,其不需要為每個(gè)命令添加一個(gè) try-with-resources 塊。?
@Bean
public JedisPooled jedisPooled() throws URISyntaxException {ConnectionPoolConfig poolConfig = new ConnectionPoolConfig();// 池中最大活躍連接數(shù),默認(rèn) 8poolConfig.setMaxTotal(maxActive);// 池中最大空閑連接數(shù),默認(rèn) 8poolConfig.setMaxIdle(maxIdle);// 池中的最小空閑連接數(shù),默認(rèn) 0poolConfig.setMinIdle(minIdle);// 啟用等待連接變?yōu)榭捎胮oolConfig.setBlockWhenExhausted(true);// 等待連接變?yōu)榭捎玫淖畲竺霐?shù),jdk17 以上支持,低版本可用 setMaxWaitMillispoolConfig.setMaxWait(Duration.ofSeconds(1));// 控制檢查池中空閑連接的間隔時(shí)間,jdk17 以上支持,低版本可用 setTimeBetweenEvictionRunsMillispoolConfig.setTimeBetweenEvictionRuns(Duration.ofSeconds(1));return new JedisPooled(poolConfig, new URI(redisUri));
}

3.4 Text Embedding

3.4.1 調(diào)用百煉 Embedding Model

使用百煉 Embedding 模型實(shí)現(xiàn)將文本轉(zhuǎn)成向量數(shù)組,并且自定義了使用的 模型和向量維度等參數(shù)。
    public List<Embedding> textEmbedding(List<String> texts) {// 調(diào)用百煉 Embedding 模型EmbeddingResponse embeddingResponse = dashScopeEmbeddingModel.call(new EmbeddingRequest(texts,DashScopeEmbeddingOptions.builder().withModel(DashScopeApi.EmbeddingModel.EMBEDDING_V3.getValue()) // 設(shè)置使用的模型.withTextType(DashScopeApi.DEFAULT_EMBEDDING_TEXT_TYPE) // 設(shè)置文本類型.withDimensions(1024)   // 設(shè)置向量維度,可選768、1024、1536.build()));List<Embedding> results = embeddingResponse.getResults();// 打印向量
//        if (CollectionUtils.isEmpty(results)) {
//            int tempSize = results.size();
//            for (int i = 0; i < tempSize; i++) {
//                float[] embeddingValue = results.get(i).getOutput();
//                log.info("embeddingValue:{}", embeddingValue.toString());
//            }
//        }return results;}

3.5 向量數(shù)據(jù)入庫

3.5.1 主要代碼

向量數(shù)據(jù)入庫,存入 Hash 類型數(shù)據(jù)。
@Autowired
private RedisTemplate redisTemplate;/*** 存入向量信息** @param key          redis KEY* @param vectorField  向量存儲(chǔ)字段名* @param vectorValue  向量值* @param contentField 向量文本內(nèi)容存儲(chǔ)字段名* @param content      向量文本內(nèi)容,增加存儲(chǔ)文本內(nèi)容,方便查看向量的內(nèi)容*/
public void addDocument(String key, String vectorField, float[] vectorValue, String contentField, String content) {// 將向量值轉(zhuǎn)為二進(jìn)制byte[] vectorByte = CommonUtil.floatArrayToByteArray(vectorValue);// 組裝字段mapMap<String, Object> fieldMap = new LinkedMap<>();fieldMap.put(contentField, content.getBytes(StandardCharsets.UTF_8));fieldMap.put(vectorField, vectorByte);// 入庫redisTemplate.opsForHash().putAll(key, fieldMap);
}

3.5.2 存儲(chǔ)數(shù)據(jù)展示

可以看到存儲(chǔ)的數(shù)據(jù)類型為 Hash ,其中 vector_filed 為存儲(chǔ)的向量值, content 為向量文本內(nèi)容。

3.6 查詢相似度

3.6.1 主要代碼

執(zhí)行 FT.SEARCH 查詢相似度,基于 KNN 算法(k 近鄰算法),并且使用余弦相似度度量法作為 KNN 的距離度量方式。
@Autowired
private JedisPooled jedisPooled;/*** 相似度搜索** @param queryVector 查詢的向量內(nèi)容* @param k           返回 k 個(gè)最相似內(nèi)容* @param indexName   索引名稱* @param vectorField 向量存儲(chǔ)字段名* @return*/
public SearchResult similaritySearch(float[] queryVector, int k, String indexName, String vectorField) {// 組裝查詢// 同:FT.SEARCH embedding_index "* => [KNN 3 @vector_field $query_vector AS distance]"//              PARAMS 2 query_vector "\x12\xa9\xf5\x6c"//              SORTBY distance//              DIALECT 4Query q = new Query("*=>[KNN $K @" + vectorField + " $query_vector AS distance]").returnFields("content", "distance").addParam("K", k).addParam("query_vector", CommonUtil.floatArrayToByteArray(queryVector)).setSortBy("distance", true).dialect(4);// 使用 UnifiedJedis 執(zhí)行 FT.SEARCH 語句try {SearchResult result = jedisPooled.ftSearch(indexName, q);log.info("redis相似度搜索,result:{}", JSONObject.toJSONString(result));return result;}catch (Exception e) {log.warn("redis相似度搜索,異常:", e);throw new ErrorCodeException(e.getMessage());}
}

3.6.2 查詢結(jié)果展示

其中 distance 為兩向量的距離。

3.7 工具方法

3.7.1 float[] 轉(zhuǎn)二進(jìn)制

/*** float[] 轉(zhuǎn)二進(jìn)制** @param floats* @return*/
public static byte[] floatArrayToByteArray(float[] floats) {byte[] bytes = new byte[Float.BYTES * floats.length];ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer().put(floats);return bytes;
}

4 SpringAI VectorStore 實(shí)現(xiàn)

Spring AI VectorStore 的實(shí)現(xiàn)跟我上面的實(shí)現(xiàn)邏輯差不多,只不過 Spring AI 將向量入庫和查詢都封裝成通用的,減少代碼量,并且其它向量庫的 jar 也都實(shí)現(xiàn)了上述接口,可已更方便快捷的切換向量庫。
如果配置文件中 initialize-schema 值為 true,索引將在配置初始化的時(shí)候自動(dòng)被創(chuàng)建。
其代碼位置( RedisVectorStore. afterPropertiesSet),可以看到其創(chuàng)建的索引數(shù)據(jù)類型為 JSON,使用余弦計(jì)算相似度,下面的 schemaFields() 在我的另一篇文章 Redis 作為向量庫入門指南 中有介紹。

4.1 引入依賴

4.1.1 引入 Spring AI Alibaba

我使用的版本是 1.0.0-M3.2,對(duì)應(yīng) Spring AI 的版本為 1.0.0-M3。
<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId>
</dependency>

4.1.2 引入 Spring Ai Redis Store

這是 SpringAI 中 Redis 作為 VectorStore 的包,由 spring 提供,跟 SpringAI 版本相同。
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-redis-store-spring-boot-starter</artifactId>
</dependency>

4.2 添加配置

4.2.1 添加 Spring Ai Alibaba 配置

application.yml 中添加:
spring:ai:dashscope:# 阿里百煉平臺(tái)申請的 api_key -->api-key: your api_keychat:client:enabled: true

4.2.2 添加 Spring AI Redis Store 配置

這里我使用了手動(dòng)配置,與 Spring AI 中 自動(dòng)配置的參數(shù)稍有區(qū)別,請甄別( Spring AI Redis VectorStore 使用), application.yml 中添加:
spring:data:redis:# uri 為 spring ai 中使用 redis 作為 Vector Store 的配置uri: redis://:gusy1234@127.0.0.1:6379/0ai:# 這里我多包了一層 mine ,因?yàn)槿绻嗉右粚?#xff0c;spring 會(huì)自動(dòng)裝配mine:# redis 作為向量庫的配置    vectorstore:redis:# 是否初始化索引信息initialize-schema: true# 索引名稱,默認(rèn) spring-ai-indexindex-name: spring-ai-index# 向量字段 key 的前綴,默認(rèn) embedding:prefix: 'embedding-ai:'# 文檔批處理計(jì)算嵌入的策略。選項(xiàng)為 TOKEN_COUNT 或 FIXED_SIZEbatching-strategy: TOKEN_COUNT

4.3 配置 JedisPooled 連接池

3.3.2 。

4.4 配置 VectorSotre

新增 VectorStoreConfig 配置類, VectorSotre 配置之前你需要先配置 EmbeddingModel 和 JedisPooled 。
:官網(wǎng)文檔中的代碼已過時(shí),這是最新的實(shí)現(xiàn)方式。
    @Resourceprivate DashScopeEmbeddingModel dashScopeEmbeddingModel;@Resourceprivate JedisPooled jedisPooled;@Bean("vectorStoreWithDashScope")public VectorStore vectorStore() {return new RedisVectorStore(RedisVectorStore.RedisVectorStoreConfig.builder().withIndexName(indexName).withPrefix(prefix)
//                .withEmbeddingFieldName("embedding")  // 向量字段名,默認(rèn) embedding
//                .withContentFieldName("content")  // 文本字段名,默認(rèn) content.build(), embeddingModel, jedisPooled, initializeSchema); // initializeSchema 為是否初始化索引配置信息}

4.5 向量數(shù)據(jù)入庫

4.5.1 主要代碼

@Autowired
@Qualifier("vectorStoreWithDashScope")
private VectorStore vectorStore;// 向量入庫主要代碼
List<String> inputInfos = List.of("文本1","文本2");
List<Document> documentList = new ArrayList<>();
inputInfos.forEach(text -> {documentList.add(new Document(text));
});
vectorStore.add(documentList);

4.5.2 存儲(chǔ)數(shù)據(jù)展示

可以看到 Spring AI 存儲(chǔ)的向量為 JSON 格式,其 Redis 庫中的內(nèi)容如下,其中 embedding 為向量內(nèi)容, content 為向量文本:

4.6 查詢相似度

4.6.1 主要代碼

可以看到代碼實(shí)現(xiàn)很簡單,參數(shù)也都是熟悉的,這里不再贅述。
// 相似度查詢主要代碼
List<Document> result = vectorStore.similaritySearch(org.springframework.ai.vectorstore.SearchRequest.defaults().withQuery(inputInfos.get(0))    // 查詢的內(nèi)容.withTopK(3)// 一個(gè)值從 0 到 1 的雙精度數(shù),接近1的值表示更高的相似性。默認(rèn)為為0.75。.withSimilarityThreshold(0.6)
);

4.6.2 查詢結(jié)果展示

5. 參考文檔?????

  • Java 中使用 Jedis 客戶端庫執(zhí)行向量搜索
  • Spring AI Redis Vector Database 文檔
  • Spring AI Alibaba 向量存儲(chǔ)文檔
  • Jedis 官方教程

http://www.risenshineclean.com/news/22436.html

相關(guān)文章:

  • 泉州制作網(wǎng)站開發(fā)搜索引擎環(huán)境優(yōu)化
  • 企業(yè)網(wǎng)站建設(shè)和實(shí)現(xiàn) 論文關(guān)鍵詞推廣怎么做
  • 西京一師一優(yōu)課建設(shè)網(wǎng)站深圳優(yōu)化排名公司
  • 福州免費(fèi)企業(yè)網(wǎng)站建站更先進(jìn)的seo服務(wù)
  • 網(wǎng)站建設(shè)主題與建設(shè)目標(biāo)最火網(wǎng)站排名
  • 濱城區(qū)住房和城鄉(xiāng)建設(shè)局網(wǎng)站seo優(yōu)化的優(yōu)點(diǎn)
  • 透視圖在什么網(wǎng)站上可以做企業(yè)網(wǎng)站設(shè)計(jì)欣賞
  • 北京個(gè)人網(wǎng)站建設(shè)多少錢西安市seo排名按天優(yōu)化
  • 交流網(wǎng)站建設(shè)心得體會(huì)百度指數(shù)查詢?nèi)肟?/a>
  • 交互動(dòng)效庫 網(wǎng)站晨陽seo顧問
  • 網(wǎng)站 建設(shè)制作菜鳥教程建網(wǎng)站的流程
  • 金融做網(wǎng)站百度瀏覽器網(wǎng)頁
  • 日本人做爰過程網(wǎng)站南寧網(wǎng)站seo排名優(yōu)化
  • 揚(yáng)州學(xué)做網(wǎng)站培訓(xùn)多少錢軟件開發(fā)公司推薦
  • 民治營銷型網(wǎng)站費(fèi)用公眾號(hào)怎么做文章推廣
  • 關(guān)于建立網(wǎng)站的計(jì)劃寧波seo優(yōu)化流程
  • 建立一個(gè)網(wǎng)站的步驟廣州seo外包公司
  • 第三方b2c平臺(tái)有哪些aso如何優(yōu)化
  • 佛山網(wǎng)站建設(shè)哪個(gè)好點(diǎn)seo關(guān)鍵詞優(yōu)化提高網(wǎng)站排名
  • 服務(wù)器租用多少錢一個(gè)月南京關(guān)鍵詞seo公司
  • 哪些網(wǎng)站做的好處和壞處知道百度
  • 做手機(jī)網(wǎng)站的好處東莞優(yōu)化排名推廣
  • 順企網(wǎng)是什么網(wǎng)站百度免費(fèi)安裝下載
  • 東莞網(wǎng)站建設(shè)是什么意思網(wǎng)站seo診斷技巧
  • 滄州網(wǎng)站建設(shè)icp備win7優(yōu)化大師官方網(wǎng)站
  • 怎么做百度網(wǎng)站驗(yàn)證公司排名seo
  • 網(wǎng)站建設(shè)需要什么樣的內(nèi)容輸入關(guān)鍵詞自動(dòng)生成標(biāo)題
  • 南京房地產(chǎn)網(wǎng)站建設(shè)成都關(guān)鍵詞優(yōu)化平臺(tái)
  • 萊蕪做網(wǎng)站建設(shè)的公司自己如何優(yōu)化網(wǎng)站排名
  • 網(wǎng)站建設(shè)的主要功能有哪些圖片優(yōu)化