|
| 1 | +#include "vector_index.h" |
| 2 | + |
| 3 | +#include <format> |
| 4 | + |
| 5 | + |
| 6 | +void DropVectorTable(NYdb::NQuery::TQueryClient& client, const std::string& tableName) |
| 7 | +{ |
| 8 | + NYdb::NStatusHelpers::ThrowOnError(client.RetryQuerySync([&](NYdb::NQuery::TSession session) { |
| 9 | + return session.ExecuteQuery(std::format("DROP TABLE IF EXISTS {}", tableName), NYdb::NQuery::TTxControl::NoTx()).ExtractValueSync(); |
| 10 | + })); |
| 11 | + |
| 12 | + std::cout << "Vector table dropped: " << tableName << std::endl; |
| 13 | +} |
| 14 | + |
| 15 | +void CreateVectorTable(NYdb::NQuery::TQueryClient& client, const std::string& tableName) |
| 16 | +{ |
| 17 | + std::string query = std::format(R"( |
| 18 | + CREATE TABLE IF NOT EXISTS `{}` ( |
| 19 | + id Utf8, |
| 20 | + document Utf8, |
| 21 | + embedding String, |
| 22 | + PRIMARY KEY (id) |
| 23 | + ))", tableName); |
| 24 | + |
| 25 | + NYdb::NStatusHelpers::ThrowOnError(client.RetryQuerySync([&](NYdb::NQuery::TSession session) { |
| 26 | + return session.ExecuteQuery(query, NYdb::NQuery::TTxControl::NoTx()).ExtractValueSync(); |
| 27 | + })); |
| 28 | + |
| 29 | + std::cout << "Vector table created: " << tableName << std::endl; |
| 30 | +} |
| 31 | + |
| 32 | +void InsertItems( |
| 33 | + NYdb::NQuery::TQueryClient& client, |
| 34 | + const std::string& tableName, |
| 35 | + const std::vector<TItem>& items) |
| 36 | +{ |
| 37 | + std::string query = std::format(R"( |
| 38 | + DECLARE $items AS List<Struct< |
| 39 | + id: Utf8, |
| 40 | + document: Utf8, |
| 41 | + embedding: List<Float> |
| 42 | + >>; |
| 43 | +
|
| 44 | + UPSERT INTO `{0}` |
| 45 | + ( |
| 46 | + id, |
| 47 | + document, |
| 48 | + embedding |
| 49 | + ) |
| 50 | + SELECT |
| 51 | + id, |
| 52 | + document, |
| 53 | + Untag(Knn::ToBinaryStringFloat(embedding), "FloatVector"), |
| 54 | + FROM AS_TABLE($items); |
| 55 | + )", tableName); |
| 56 | + |
| 57 | + NYdb::TParamsBuilder paramsBuilder; |
| 58 | + auto& valueBuilder = paramsBuilder.AddParam("$items"); |
| 59 | + valueBuilder.BeginList(); |
| 60 | + for (const auto& item : items) { |
| 61 | + valueBuilder.AddListItem(); |
| 62 | + valueBuilder.BeginStruct(); |
| 63 | + valueBuilder.AddMember("id").Utf8(item.Id); |
| 64 | + valueBuilder.AddMember("document").Utf8(item.Document); |
| 65 | + valueBuilder.AddMember("embedding").BeginList(); |
| 66 | + for (const auto& value : item.Embedding) { |
| 67 | + valueBuilder.AddListItem().Float(value); |
| 68 | + } |
| 69 | + valueBuilder.EndList(); |
| 70 | + valueBuilder.EndStruct(); |
| 71 | + } |
| 72 | + valueBuilder.EndList(); |
| 73 | + valueBuilder.Build(); |
| 74 | + |
| 75 | + NYdb::NStatusHelpers::ThrowOnError(client.RetryQuerySync([params = paramsBuilder.Build(), &query](NYdb::NQuery::TSession session) { |
| 76 | + return session.ExecuteQuery(query, NYdb::NQuery::TTxControl::BeginTx(NYdb::NQuery::TTxSettings::SerializableRW()).CommitTx(), params).ExtractValueSync(); |
| 77 | + })); |
| 78 | + |
| 79 | + std::cout << items.size() << " items inserted" << std::endl; |
| 80 | +} |
| 81 | + |
| 82 | +void AddIndex( |
| 83 | + NYdb::TDriver& driver, |
| 84 | + NYdb::NQuery::TQueryClient& client, |
| 85 | + const std::string& database, |
| 86 | + const std::string& tableName, |
| 87 | + const std::string& indexName, |
| 88 | + const std::string& strategy, |
| 89 | + std::uint64_t dim, |
| 90 | + std::uint64_t levels, |
| 91 | + std::uint64_t clusters) |
| 92 | +{ |
| 93 | + std::string query = std::format(R"( |
| 94 | + ALTER TABLE `{0}` |
| 95 | + ADD INDEX {1}__temp |
| 96 | + GLOBAL USING vector_kmeans_tree |
| 97 | + ON (embedding) |
| 98 | + WITH ( |
| 99 | + {2}, |
| 100 | + vector_type="Float", |
| 101 | + vector_dimension={3}, |
| 102 | + levels={4}, |
| 103 | + clusters={5} |
| 104 | + ); |
| 105 | + )", tableName, indexName, strategy, dim, levels, clusters); |
| 106 | + |
| 107 | + NYdb::NStatusHelpers::ThrowOnError(client.RetryQuerySync([&](NYdb::NQuery::TSession session) { |
| 108 | + return session.ExecuteQuery(query, NYdb::NQuery::TTxControl::NoTx()).ExtractValueSync(); |
| 109 | + })); |
| 110 | + |
| 111 | + NYdb::NTable::TTableClient tableClient(driver); |
| 112 | + NYdb::NStatusHelpers::ThrowOnError(tableClient.RetryOperationSync([&](NYdb::NTable::TSession session) { |
| 113 | + return session.AlterTable(database + "/" + tableName, NYdb::NTable::TAlterTableSettings() |
| 114 | + .AppendRenameIndexes(NYdb::NTable::TRenameIndex{ |
| 115 | + .SourceName_ = indexName + "__temp", |
| 116 | + .DestinationName_ = indexName, |
| 117 | + .ReplaceDestination_ = true |
| 118 | + }) |
| 119 | + ).ExtractValueSync(); |
| 120 | + })); |
| 121 | + |
| 122 | + std::cout << "Table index `" << indexName << "` for table `" << tableName << "` added" << std::endl; |
| 123 | +} |
| 124 | + |
| 125 | +std::vector<TResultItem> SearchItems( |
| 126 | + NYdb::NQuery::TQueryClient& client, |
| 127 | + const std::string& tableName, |
| 128 | + const std::vector<float>& embedding, |
| 129 | + const std::string& strategy, |
| 130 | + std::uint64_t limit, |
| 131 | + const std::optional<std::string>& indexName) |
| 132 | +{ |
| 133 | + std::string viewIndex = indexName ? "VIEW " + *indexName : ""; |
| 134 | + std::string sortOrder = strategy.ends_with("Similarity") ? "DESC" : "ASC"; |
| 135 | + |
| 136 | + std::string query = std::format(R"( |
| 137 | + DECLARE $embedding as List<Float>; |
| 138 | +
|
| 139 | + $TargetEmbedding = Knn::ToBinaryStringFloat($embedding); |
| 140 | +
|
| 141 | + SELECT |
| 142 | + id, |
| 143 | + document, |
| 144 | + Knn::{2}(embedding, $TargetEmbedding) as score |
| 145 | + FROM {0} {1} |
| 146 | + ORDER BY score |
| 147 | + {3} |
| 148 | + LIMIT {4}; |
| 149 | + )", tableName, viewIndex, strategy, sortOrder, limit); |
| 150 | + |
| 151 | + NYdb::TParamsBuilder paramsBuilder; |
| 152 | + auto& valueBuilder = paramsBuilder.AddParam("$embedding"); |
| 153 | + valueBuilder.BeginList(); |
| 154 | + for (auto value : embedding) { |
| 155 | + valueBuilder.AddListItem().Float(value); |
| 156 | + } |
| 157 | + valueBuilder.EndList().Build(); |
| 158 | + |
| 159 | + std::vector<TResultItem> result; |
| 160 | + |
| 161 | + NYdb::NStatusHelpers::ThrowOnError(client.RetryQuerySync([params = paramsBuilder.Build(), &query, &result](NYdb::NQuery::TSession session) { |
| 162 | + auto execResult = session.ExecuteQuery(query, NYdb::NQuery::TTxControl::BeginTx(NYdb::NQuery::TTxSettings::SerializableRW()).CommitTx(), params).ExtractValueSync(); |
| 163 | + if (execResult.IsSuccess()) { |
| 164 | + auto parser = execResult.GetResultSetParser(0); |
| 165 | + while (parser.TryNextRow()) { |
| 166 | + result.push_back({ |
| 167 | + .Id = *parser.ColumnParser(0).GetOptionalUtf8(), |
| 168 | + .Document = *parser.ColumnParser(1).GetOptionalUtf8(), |
| 169 | + .Score = *parser.ColumnParser(2).GetOptionalFloat() |
| 170 | + }); |
| 171 | + } |
| 172 | + } |
| 173 | + return execResult; |
| 174 | + })); |
| 175 | + |
| 176 | + return result; |
| 177 | +} |
0 commit comments