gpt4 book ai didi

swift - 如何使用 IN 条件访问 SQLite.swift 中的 FTS 表

转载 作者:搜寻专家 更新时间:2023-10-31 22:59:28 24 4
gpt4 key购买 nike

我正在尝试使用 SQLite.swift 查询 FTS 表。 Previously I have done it in Android .我要做的事情的实质是 this :

SELECT *
FROM t2
WHERE id IN (SELECT docid
FROM fts_table
WHERE col_text MATCH 'something')

来自SQLite.swift documentation我看到 IN condition可以写成this :

users.filter([1, 2, 3, 4, 5].contains(id))
// SELECT * FROM "users" WHERE ("id" IN (1, 2, 3, 4, 5))

并且虚拟表可以像this一样被查询:

let wonderfulEmails = emails.match("wonder*")
// SELECT * FROM "emails" WHERE "emails" MATCH 'wonder*'

let replies = emails.filter(subject.match("Re:*"))
// SELECT * FROM "emails" WHERE "subject" MATCH 'Re:*'

但是,我不知道如何将它们结合起来。我真的不想execute arbitrary SQL (虽然这要归功于 this answer 的帮助)。

更新

这是我最近的尝试,但没有成功:

let tableText = Table("t2")
let id = Expression<Int64>("id")
let someColumn = Expression<String>("someColumn")

let tableFts = VirtualTable("fts_table")
let columnDocId = Expression<Int64>("docId")


let ftsQuery = tableFts
.select(columnDocId)
.filter(tableFts.match("something"))
let tableQuery = tableText
.filter((try db.prepare(ftsQuery))
.contains(id)) // <-- error

for row in try db.prepare(tableQuery) {
print(row[someColumn])
}

contains(id) 的行抛出错误:

Cannot convert value of type 'Expression' to expected argument type '@noescape (Row) throws -> Bool'

最佳答案

我最终只运行了原始 SQL 命令。这并不能完全回答我在问题中提出的问题(因为它不使用纯 SQLite.swift API)但是对于那些只需要让某些东西正常工作的人来说,......它有效。

这是我从我的一些源代码中提取的修改示例。

static func findLinesContaining(_ searchTerms: String, forSearchScope scope: SearchScope) throws -> [TextLines] {

guard let db = SQLiteDataStore.sharedInstance.TextDB else {
throw DataAccessError.datastore_Connection_Error
}

// TODO: convert to SQLite.swift syntax rather than using a SQL string
var statement: Statement? = nil
switch scope {
case .wholeCollection:
statement = try db.run("SELECT bookId, chapterId, lineId, lineText" +
" FROM lines" +
" WHERE rowid IN (SELECT docid FROM fts_table" +
" WHERE fts_table MATCH ?);", searchTerms)

case .singleBook(let chosenBookId):
statement = try db.run("SELECT bookId, chapterId, lineId, lineText" +
" FROM lines" +
" WHERE rowid IN (SELECT docid FROM fts_table" +
" WHERE fts_table MATCH ?) AND bookId = ?;", [searchTerms, chosenBookId])
}


var returnList: [TextLine] = []
for row in statement! {

let line = TextLine()
if let bookId = row[0] as? Int64,
let chapterId = row[1] as? Int64,
let lineId = row[2] as? Int64,
let text = row[3] as? String {

line.bookId = Int(bookId)
line.chapterId = Int(chapterId)
line.lineId = Int(lineId)
line.lineText = text
}

returnList.append(line)
}

return returnList
}

以上代码在重命名变量和类以供在 SO 上使用后未经测试。如果您发现错误,我允许您编辑代码。

关于swift - 如何使用 IN 条件访问 SQLite.swift 中的 FTS 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38936230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com