Swift で iOS アプリに seekdb を組み込む
SwiftUI アプリのプロセス内で seekdb を起動し、Unix ソケットで接続します。アプリは Swift SDK で seekdb を開き、MySQLNIO で全文検索とベクトル検索を組み合わせる SQL クエリを実行します。
前提条件
- Xcode 16 以降、iOS 18 以降の Simulator ランタイム、Git、Homebrew がインストールされた Mac。
- seekdb V1.4.1 エンジンに対応する Swift SDK 1.4.1。Swift Package Manager は依存関係の解決時に XCFramework をダウンロードして検証します。Xcode は実機用または Simulator 用のスライスをアプリに組み込みます。
配布ファイルは Swift SDK のリリース一覧 を参照してください。
サンプルプロジェクトを準備する
XcodeGen をインストールし、Swift SDK の 1.4.1 タグを指定してクローンします。クローンしたリポジトリに SeekDB Shell サンプルが含まれています。
SeekDB Shell のソース
brew install xcodegen
git clone --branch 1.4.1 --depth 1 https://github.com/oceanbase/seekdb-swift.git
cd seekdb-swift/example
共通の SQL サンプルを、現在の
example ディレクトリに hybrid-search.sql として保存します。
project.yml の targets.SeekDBShell にある sources リストを編集し、
SQL ファイルをアプリのリソースに追加します。
sources:
- App
- path: hybrid-search.sql
buildPhase: resources
ハイブリッド検索を実行する
App/SeekDBShellApp.swift のライセンスヘッダーを残し、インポート文以降を以下のコードに置き換えます。
App/QueryCommand.swift はターゲットに残します。サーバーが EOF パケットを使う場合、サンプルの QueryCommand が MySQL のテキスト形式の結果を読み取ります。
QueryCommand のソースコード
初回実行時は、アプリのサンドボックス内で未使用のデータディレクトリを使います。コードでは Documents/seekdb-hybrid-search を使用します。アプリは test データベースに接続し、SQL 文を 1 つずつ送信します。セミコロンで SQL 文を分割する処理は、このサンプルファイル専用です。
アプリは SQL 接続を閉じ、NIO イベントループグループを停止してから、seekdb ハンドルを閉じます。エンジンはアプリのプロセスが終了するまで動作します。初期化をやり直すには、アプリを停止し、コード内の seekdb-hybrid-search を新しいディレクトリ名に変更します。
import Foundation
import MySQLNIO
import NIOCore
import NIOPosix
import SeekDB
import ShellCore
import SwiftUI
@main
struct SeekDBShellApp: App {
var body: some Scene {
WindowGroup {
HybridSearchView()
}
}
}
struct HybridSearchView: View {
@State private var output = "Running hybrid search..."
var body: some View {
ScrollView {
Text(output)
.font(.system(.body, design: .monospaced))
.textSelection(.enabled)
.padding()
}
.task {
output = await Task.detached {
do {
return try runHybridSearch()
} catch {
return "Hybrid search failed: \(error)"
}
}.value
print(output)
}
}
}
enum ExampleError: Error {
case missingSQLFile
case expectedFourStatements
case missingUnixSocket
case missingResults
}
func runHybridSearch() throws -> String {
guard let file = Bundle.main.url(forResource: "hybrid-search", withExtension: "sql") else {
throw ExampleError.missingSQLFile
}
let script = try String(contentsOf: file, encoding: .utf8)
let statements = script.split(separator: ";")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
guard statements.count == 4 else {
throw ExampleError.expectedFourStatements
}
let documents = try FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
let directory = documents.appendingPathComponent("seekdb-hybrid-search", isDirectory: true)
let db = try SeekDB.open(directory.path)
defer { try? db.close() }
let options = try db.connectionOptions()
guard options.transport == "unix_socket", let socket = options.unix_socket else {
throw ExampleError.missingUnixSocket
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer { try? group.syncShutdownGracefully() }
let connection = try MySQLConnection.connect(
to: try SocketAddress(unixDomainSocketPath: socket),
username: options.user ?? "root",
database: "test",
password: nil,
tlsConfiguration: nil,
on: group.next()
).wait()
defer { try? connection.close().wait() }
for statement in statements {
let command = QueryCommand(sql: statement)
try connection.send(command, logger: connection.logger).wait()
if case let .rows(columns, rows)? = command.results.first,
columns.count == 1, columns[0].name == "results",
rows.count == 1, let cell = rows[0].first, let result = cell {
return result
}
}
throw ExampleError.missingResults
}
example ディレクトリで Xcode プロジェクトを生成して開きます。
xcodegen generate
open SeekDBShell.xcodeproj
Xcode で SeekDBShell スキームと iOS Simulator を選択し、Product > Run を選択します。
アプリは results 列の JSON を画面に表示し、Xcode のデバッグコンソールにも出力します。
共通の SQL サンプルでは、結果の ID が 1、3、2 の順に並ぶ想定です。
[
{
"id": 1,
"body": "SeekDB hybrid search",
"_score": 0.0325
},
{
"id": 3,
"body": "Combine keyword queries with vector retrieval",
"_score": 0.0164
},
{
"id": 2,
"body": "SeekDB installation guide for local application development",
"_score": 0.0161
}
]