跳到主要内容
版本:V1.4.1

在 iOS 应用中使用 Swift 运行嵌入式 seekdb

本示例在 SwiftUI 应用进程内启动 seekdb,并通过 Unix Socket 连接数据库。应用使用 Swift SDK 打开 seekdb,再用 MySQLNIO 执行结合全文检索和向量检索的 SQL 查询。

环境要求​

  • 安装了 Xcode 16 或更高版本、iOS 18 或更高版本的模拟器运行时、Git 和 Homebrew 的 Mac。
  • Swift SDK 1.4.1,对应 seekdb V1.4.1 引擎。Swift Package Manager 在解析依赖时下载并校验 XCFramework,Xcode 将对应的真机或模拟器构建产物嵌入应用。

有关发布包,请参见 Swift SDK 发布页面。

准备示例项目​

安装 XcodeGen,并克隆 1.4.1 标签对应的 Swift SDK,以获取 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 语句。按分号拆分语句的做法仅用于此处的固定 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 模拟器,然后选择 Product > Run。

应用展示 results 列中的 JSON,并将其打印到 Xcode 调试控制台。 通用 SQL 示例预期按 1、3、2 的顺序返回文档 ID。

[
{
"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
}
]

API 参考​