OceanBaseはV4.3.3からベクトル型データの格納、ベクトルインデックス、そしてembeddingベクトル検索機能をサポートしています。これにより、ベクトル化したデータをOceanBaseに保存し、次の検索処理で利用することが可能です。
Spring AI Alibabaは、Spring AIを基盤として構築されたオープンソースプロジェクトであり、Alibaba CloudのTongyiシリーズモデルおよびサービスをJava AIアプリケーション開発で活用するためのベストプラクティスです。このプロジェクトはAIアプリケーションの開発プロセスを簡素化し、クラウドネイティブなインフラに適応させることで、開発者が迅速にAIアプリケーションを構築できるよう支援します。
本記事では、Spring AI AlibabaとOB Cloudのベクトル検索機能を連携させ、データのインポートと類似性検索を実現する方法を紹介します。ベクトルストレージと検索サービスを設定することで、開発者はOceanBaseを基盤としたAIアプリケーションシナリオを容易に構築でき、テキスト類似度検索やコンテンツ推薦などの高度な機能をサポートできます。
前提条件
- 環境に利用可能なトランザクション型(MySQL)のクラスタインスタンスがあります。
テナントの作成は、テナントの作成を参照して完了してください。その後、以下の手順に従って操作を進めてください。
環境に使用可能なMySQL互換モードのテナント、MySQLデータベース、およびデータベースアカウントが既に存在し、データベースアカウントに読み書き権限が付与されていること。作成が必要な場合は、詳細については アカウントの作成および データベースの作成(MySQL専用)をご参照ください。
プロジェクト管理者またはインスタンス管理者ロールを持ち、プロジェクト内のインスタンスに対する読み書き操作を実行できること。権限がない場合は、組織管理者に連絡して権限の追加を依頼してください。
JDK 17+をダウンロードします。Java 17をインストールし、環境変数を設定してください。
Mavenをダウンロードします。プロジェクトのビルドと依存関係の管理のため、Maven 3.6+ をインストールしてください。
IntelliJ IDEAまたは Eclipseをダウンロードし、ご使用のOSに合わせたバージョンを選択してインストールします。
ステップ1:データベース接続情報を取得する
ドロップダウンリストから、ID **クラスタインスタンスを選択**します。
**概要**ページに移動します。
接続をクリックし、**接続文字列を取得**を選択します。
ポップアップウィンドウで、**パブリックネットワークを使用**を選択します。
アクセスアドレスを取得し、**現在のブラウザIPアドレスを追加**を選択します。
データベース関連情報を入力し、**接続文字列をコピー**します。
ステップ2:Mavenプロジェクトを構築する
Mavenは、本記事で使用されるプロジェクト管理およびビルドツールです。このステップでは、Mavenプロジェクトを作成し、pom.xmlファイルを設定してプロジェクトの依存関係を追加します。
プロジェクトの作成
Mavenコマンドを使用してプロジェクトを作成します。
mvn archetype:generate -DgroupId=com.alibaba.cloud.ai.example -DartifactId=vector-oceanbase-example -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=falseプロジェクトディレクトリに移動します。
cd vector-oceanbase-example
pom.xmlファイルの設定
pom.xmlファイルはMavenプロジェクトの中心的な設定ファイルであり、プロジェクトの依存関係、プラグイン、ビルド設定などの情報を管理します。次に、pom.xmlファイルを修正し、Spring AI Alibaba、OceanBaseベクトルストレージ、およびその他の必要な依存関係を追加する必要があります。
pom.xmlファイルを開き、既存の内容を以下の内容に置き換えます。
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.alibaba.cloud.ai.example</groupId>
<artifactId>spring-ai-alibaba-vector-databases-example</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>vector-oceanbase-example</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Alibaba Cloud AI Starter -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
</dependency>
<!-- Spring Boot Web support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring AI autoconfiguration -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-spring-boot-autoconfigure</artifactId>
</dependency>
<!-- Spring JDBC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!-- Transformers model support -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-transformers</artifactId>
</dependency>
<!-- OceanBase ベクトルデータベース Starter -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-oceanbase-store</artifactId>
<version>1.0.0-M6.2-SNAPSHOT</version>
</dependency>
<!-- OceanBase JDBC ドライバ -->
<dependency>
<groupId>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.14</version>
</dependency>
</dependencies>
<!-- SNAPSHOTリポジトリ設定 -->
<repositories>
<repository>
<id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>
ステップ3:OceanBaseデータベース接続情報の設定
このステップでは、application.yml ファイルを設定し、OceanBaseデータベースの接続情報を追加します。
プロジェクトの src/main/resources ディレクトリに application.yml ファイルを作成し、以下の内容を追加します:
server:
port: 8080
spring:
application:
name: oceanbase-example
ai:
dashscope:
api-key: ${DASHSCOPE_API_KEY} # あなたのDashScope APIキーに置き換えてください
vectorstore:
oceanbase:
enabled: true
url: jdbc:oceanbase://xxx:xxx/xxx # OceanBase接続URL
username: xxx # OceanBaseユーザー名
password: xxx # OceanBaseパスワード
tableName: vector_table # ベクトルテーブル名(自動作成)
defaultTopK: 2 # デフォルトで返す類似結果数
defaultSimilarityThreshold: 0.8 # 類似度しきい値(0~1、値が小さいほど類似)
ステップ4:メインアプリケーションクラスとコントローラーの作成
Spring Bootアプリケーションの起動クラスとコントローラークラスを作成し、データインポートと類似性検索機能を実装します。
アプリケーション起動クラスの作成
プロジェクトの src/main/java/com/alibaba/cloud/ai/example/vector ディレクトリに OceanBaseApplication.java ファイルを作成し、以下の内容を追加します:
package com.alibaba.cloud.ai.example.vector; // パッケージ名はディレクトリ構造に合わせる
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // Spring Bootの自動設定を有効化
public class OceanBaseApplication {
public static void main(String[] args) {
SpringApplication.run(OceanBaseApplication.class, args); // Spring Bootアプリケーションを起動
}
}
サンプルコードは、プロジェクトの中核となる起動クラスであり、Spring Bootアプリケーションを起動するために使用されます。
ベクトルストレージコントローラーの作成
プロジェクトのsrc/main/java/com/alibaba/cloud/ai/example/vectorディレクトリにOceanBaseController.javaファイルを作成し、以下の内容を追加します。
package com.alibaba.cloud.ai.example.vector.controller; // パッケージ名はディレクトリ構造に合わせる
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.cloud.ai.vectorstore.oceanbase.OceanBaseVectorStore;
@RestController // RESTコントローラーとしてマーク
@RequestMapping("/oceanbase") // ベースパスを /oceanbase に設定
public class OceanBaseController {
private static final Logger logger = LoggerFactory.getLogger(OceanBaseController.class); // ロガー
@Autowired // OceanBaseベクトルストレージサービスの自動注入
private OceanBaseVectorStore oceanBaseVectorStore;
// データをインポートするエンドポイント
@GetMapping("/import")
public void importData() {
logger.info("Start importing data");
// サンプルデータを作成
HashMap<String, Object> map = new HashMap<>();
map.put("id", "12345");
map.put("year", "2025");
map.put("name", "yingzi");
// 3つのドキュメントを含むリストを作成
List<Document> documents = List.of(
new Document("The World is Big and Salvation Lurks Around the Corner"),
new Document("You walk forward facing the past and you turn back toward the future.", Map.of("year", 2024)),
new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", map)
);
// ドキュメントをベクトルストアに追加する
oceanBaseVectorStore.add(documents);
}
// 類似ドキュメントを検索するエンドポイント
@GetMapping("/search")
public List<Document> search() {
logger.info("Start searching data");
// 類似性検索を実行し、「Spring」を含むドキュメントを検索し、最も類似した上位2件の結果を返す
return oceanBaseVectorStore.similaritySearch(SearchRequest.builder()
.query("Spring")
.topK(2)
.build());
}
}
ステップ5:Mavenプロジェクトの起動とテスト
IDEを使用してプロジェクトを起動する
本記事ではIntelliJ IDEAを例に、IDEを使用してプロジェクトを起動する方法を説明します。
具体的な手順は以下の通りです:
- プロジェクトを開く:
File->Open->pom.xmlを選択します。 プロジェクトとして開くを選択します。- メインクラス
OceanBaseApplication.javaを見つけます。 - 右クリックして
Run 'OceanBaseApplication.main()'を選択します。
プロジェクトのテスト
以下のURLにアクセスしてテストデータをインポートします:
http://localhost:8080/oceanbase/import以下のURLにアクセスしてベクトル検索を実行します:
http://localhost:8080/oceanbase/search期待される戻り値:
[ { "id": "03fe9aad-13cc-4d25-807b-ca1bc314f571", "text": "Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", "metadata": { "name": "yingzi", "id": "12345", "year": "2025", "distance": "7.274442499114312" } }, { "id": "75864954-0a23-4fa1-8e18-b78fd870d474", "text": "Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", "metadata": { "name": "yingzi", "id": "12345", "year": "2025", "distance": "7.274442499114312" } } ]
よくある質問
OceanBase接続失敗
- 原因:URL、ユーザー名、またはパスワードが誤っています。
- 解決策:
application.ymlのOceanBase設定を確認し、データベースサービスが起動していることを確保します。
依存関係の競合
- 原因:複数のSpring Bootバージョンが競合しています。
- 解決策:
mvn dependency:treeを使用して依存関係ツリーを確認し、競合するバージョンを除外します。
SNAPSHOT依存関係のダウンロード失敗
- 原因:SNAPSHOTリポジトリが設定されていません。
- 解決策:
pom.xmlにsonatype-snapshotsリポジトリが追加されていることを確認します。