use std::collections::BTreeSet;
use std::sync::Arc;
use crate::commands::ctx::Ctx;
use crate::resp::write::*;
use crate::vector::{FieldType, LiveIndex, VectorAlgo};
fn takes_index_name(name: &str) -> bool {
matches!(
name,
"FT.INFO"
| "FT.DROPINDEX"
| "FT.SEARCH"
| "FT.AGGREGATE"
| "FT.ALTER"
| "FT.EXPLAIN"
| "FT.EXPLAINCLI"
| "FT.PROFILE"
| "FT.TAGVALS"
| "FT.SYNUPDATE"
| "FT.SYNDUMP"
| "FT.SPELLCHECK"
| "FT.HYBRID"
| "FT.ALIASLIST"
)
}
#[derive(Clone, Copy)]
enum Elsewhere {
Index,
Alias,
AliasTaken,
}
fn index_name_positions(name: &str, cmd: &[&[u8]]) -> &'static [(usize, Elsewhere)] {
match name {
"FT.ALIASUPDATE" => &[(1, Elsewhere::AliasTaken), (2, Elsewhere::Index)],
"FT.ALIASADD" | "FT.CURSOR" => &[(2, Elsewhere::Index)],
"FT.ALIASDEL" => &[(1, Elsewhere::Alias)],
"FT.DEBUG"
if cmd.get(1).is_some_and(|sub| {
[&b"COMPACT"[..], b"POSTINGS", b"PAGE"]
.iter()
.any(|known| sub.eq_ignore_ascii_case(known))
}) =>
{
&[(2, Elsewhere::Index)]
}
_ if takes_index_name(name) => &[(1, Elsewhere::Index)],
_ => &[],
}
}
fn in_another_database(ctx: &Ctx, given: &[u8]) -> bool {
let Ok(given) = std::str::from_utf8(given) else {
return false;
};
ctx.index_store
.read()
.get(given)
.is_some_and(|def| def.db_index != *ctx.selected_db)
}
pub fn handle(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
if !name.starts_with("FT.") {
return None;
}
for &(at, elsewhere) in index_name_positions(name, &ctx.cmd) {
let Some(given) = ctx.cmd.get(at).copied() else {
continue;
};
if in_another_database(ctx, given) {
let given = String::from_utf8_lossy(given);
return Some(resp_error(&match elsewhere {
Elsewhere::Index => crate::commands::search::no_such_index(&given),
Elsewhere::Alias => "ERR Alias does not exist".to_string(),
Elsewhere::AliasTaken => "ERR Alias already exists".to_string(),
}));
}
}
let alias_target = if takes_index_name(name) {
ctx.cmd
.get(1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|given| crate::vector::alias_target(&ctx.index_store.read(), given))
} else {
None
};
if let Some(real) = alias_target {
let original = ctx.cmd[1];
let erased: &'static [u8] = unsafe { std::mem::transmute(real.as_bytes()) };
ctx.cmd[1] = erased;
let reply = dispatch(ctx, name);
ctx.cmd[1] = original;
return reply;
}
dispatch(ctx, name)
}
fn dispatch(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
match name {
"FT.CREATE" => crate::commands::search::ft_create(ctx),
"FT._LIST" => ft_list(ctx),
"FT.INFO" => crate::commands::search::ft_info(ctx),
"FT.DROPINDEX" => ft_dropindex(ctx),
"FT.SEARCH" => crate::commands::search::ft_search(ctx),
"FT.AGGREGATE" => ft_aggregate(ctx),
"FT.ALIASADD" => ft_alias_add(ctx),
"FT.ALIASDEL" => ft_alias_del(ctx),
"FT.ALIASUPDATE" => ft_alias_update(ctx),
"FT.ALIASLIST" => ft_alias_list(ctx),
"FT.ALTER" => ft_alter(ctx),
"FT.DICTADD" => ft_dictadd(ctx),
"FT.DICTDEL" => ft_dictdel(ctx),
"FT.DICTDUMP" => ft_dictdump(ctx),
"FT.EXPLAIN" => crate::commands::search_tools::ft_explain(ctx, false),
"FT.EXPLAINCLI" => crate::commands::search_tools::ft_explain(ctx, true),
"FT.PROFILE" => crate::commands::search_tools::ft_profile(ctx),
"FT.CONFIG" => crate::commands::search_tools::ft_config(ctx),
"FT.CURSOR" => crate::commands::search_tools::ft_cursor(ctx),
"FT.TAGVALS" => ft_tagvals(ctx),
"FT.SYNUPDATE" => ft_synupdate(ctx),
"FT.SYNDUMP" => ft_syndump(ctx),
"FT.SPELLCHECK" => ft_spellcheck(ctx),
"FT.DEBUG" => ft_debug(ctx),
"FT.HYBRID" => crate::commands::hybrid::ft_hybrid(ctx),
_ => None,
}
}
fn ft_list(ctx: &mut Ctx) -> Option<Vec<u8>> {
let store = ctx.index_store.read();
let db = *ctx.selected_db;
let items: Vec<Vec<u8>> = store
.iter()
.filter(|(key, def)| !crate::vector::is_alias(key, def) && def.db_index == db)
.map(|(key, _)| resp_bulk_str(key))
.collect();
Some(resp_array(items))
}
fn ft_dropindex(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() < 2 {
return Some(resp_error(
"ERR wrong number of arguments for 'ft.dropindex' command",
));
}
let name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let relaxed = std::sync::atomic::Ordering::Relaxed;
let delete_documents = match &cmd[2..] {
[] => false,
[dd] if dd.eq_ignore_ascii_case(b"DD") => {
!ctx.apply_replication
|| (!crate::vector::DEFER_INDEXING.load(relaxed)
&& ctx.repl_state.master_dd_deletes.load(relaxed))
}
_ => return Some(resp_error("SEARCH_ARG_UNRECOGNIZED Unknown argument")),
};
let found = ctx
.index_store
.read()
.get(&name)
.filter(|def| !crate::vector::is_alias(&name, def))
.map(|def| (def.db_index, def.on.clone(), def.prefixes.clone()));
let Some((db, on, prefixes)) = found else {
return Some(resp_error(&crate::commands::search::no_such_index(&name)));
};
let mut documents = Vec::new();
if delete_documents {
for shard in ctx.store[db].iter() {
let map = shard.read();
for (key, value) in map.iter() {
let covered =
prefixes.is_empty() || prefixes.iter().any(|p| key.starts_with(p.as_bytes()));
if covered && crate::vector::is_document(&on, value) {
documents.push(crate::store::Key::new(key));
}
}
}
}
let propagate = crate::replication::write_is_observed(ctx);
let by_slot = propagate && ctx.cluster.enabled;
let slot_of = |key: &[u8]| {
if by_slot {
crate::cluster::key_hash_slot(key)
} else {
0
}
};
if by_slot {
documents.sort_by_cached_key(|key| slot_of(key));
}
crate::aof::failpoint("dropindex-collected");
let nested = crate::write_gate::held_by_this_thread();
let mut deleted = 0usize;
let mut del: Vec<Vec<u8>> = Vec::new();
for chunk in documents.chunks(DROPINDEX_DOCUMENTS_PER_WRITE) {
let _gate = dropindex_write_gate(ctx, nested);
let _order = crate::write_order::lock_keys(db, chunk.iter().map(|k| k.as_bytes()));
let mut slot = chunk.first().map(|key| slot_of(key));
for key in chunk {
if by_slot && slot != Some(slot_of(key)) {
slot = Some(slot_of(key));
send_dels(ctx, db, &mut del);
}
if crate::commands::helpers::is_expired(ctx.store, db, key) {
crate::commands::helpers::delete_key_if_expired(ctx.store, db, key);
continue;
}
if !delete_document(ctx.store, db, key, &on) {
continue;
}
deleted += 1;
crate::vector::maybe_unindex(ctx.index_store, db, key);
crate::stats::record_rdb_change();
crate::keyspace_events::notify(
ctx.pubsub,
db,
crate::keyspace_events::KS_GENERIC,
"del",
key,
);
ctx.watch_registry.notify(db, key);
crate::commands::handler::invalidate_tracked_key(ctx, key, false);
if propagate {
if del.is_empty() {
del.push(b"DEL".to_vec());
}
del.push(key.as_bytes().to_vec());
}
}
send_dels(ctx, db, &mut del);
}
let _gate = dropindex_write_gate(ctx, nested);
if !crate::vector::remove_index(&mut ctx.index_store.write(), &name) {
if deleted == 0 {
return Some(resp_error(&crate::commands::search::no_such_index(&name)));
}
return Some(resp_simple("OK"));
}
if propagate {
propagate_in_db(ctx, db, &[b"FT.DROPINDEX".to_vec(), name.into_bytes()]);
}
Some(resp_simple("OK"))
}
const DROPINDEX_DOCUMENTS_PER_WRITE: usize = 256;
fn delete_document(
store: &crate::store::Store,
db: usize,
key: &[u8],
on: &crate::vector::IndexOn,
) -> bool {
let shard = crate::store::get_shard(&store[db], key);
let removal = shard
.write()
.remove_if(key, |value| crate::vector::is_document(on, value));
matches!(removal, crate::store::Removal::Taken(_))
}
fn dropindex_write_gate(ctx: &Ctx, nested: bool) -> crate::write_gate::WriteGuard {
let mut gate = crate::write_gate::enter();
while !nested && !ctx.apply_replication && crate::pause::handoff() {
drop(gate);
crate::pause::wait_out_handoff();
gate = crate::write_gate::enter();
}
gate
}
fn send_dels(ctx: &mut Ctx, db: usize, del: &mut Vec<Vec<u8>>) {
if del.len() > 1 {
propagate_in_db(ctx, db, del);
}
del.clear();
}
fn propagate_in_db(ctx: &mut Ctx, db: usize, parts: &[Vec<u8>]) {
let selected = *ctx.selected_db;
*ctx.selected_db = db;
crate::replication::replicate_one_write(ctx, parts);
*ctx.selected_db = selected;
}
fn ft_alter(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() < 6 {
return Some(resp_error(
"ERR wrong number of arguments for 'ft.alter' command",
));
}
let index_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let mut i = 2usize;
let mut skip_initial_scan = false;
while i < cmd.len() {
let tok = match std::str::from_utf8(cmd[i]) {
Ok(s) => s.to_ascii_uppercase(),
Err(_) => return Some(resp_error("ERR invalid argument")),
};
match tok.as_str() {
"SKIPINITIALSCAN" => {
skip_initial_scan = true;
i += 1;
}
"SCHEMA" => {
i += 1;
break;
}
_ => {
i += 1;
}
}
}
let add_tok = cmd
.get(i)
.and_then(|b| std::str::from_utf8(b).ok())
.map(|s| s.to_ascii_uppercase());
match add_tok.as_deref() {
Some("ADD") => {
i += 1;
}
_ => {
return Some(resp_error(
"ERR syntax: FT.ALTER index SCHEMA ADD field type ...",
));
}
}
let new_fields = match crate::commands::search::parse_schema_fields(cmd, &mut i) {
Ok(fields) => fields,
Err(e) => return Some(resp_error(&e)),
};
if new_fields.is_empty() {
return Some(resp_error("ERR no fields specified"));
}
let mut store = ctx.index_store.write();
let def = match store.get_mut(&index_name) {
Some(d) => d,
None => {
return Some(resp_error(&crate::commands::search::no_such_index(
&index_name,
)));
}
};
for nf in &new_fields {
if def
.fields
.iter()
.any(|f| f.name == nf.name || f.attribute() == nf.attribute())
{
return Some(resp_error(&format!(
"Duplicate field in schema - {}",
nf.attribute()
)));
}
}
let mut newly_added_vector_fields: Vec<String> = Vec::new();
let mut newly_added_text_fields: Vec<String> = Vec::new();
let added_filter_fields: Vec<crate::vector::SchemaField> = new_fields
.iter()
.filter(|f| matches!(f.field_type, FieldType::Tag | FieldType::Numeric))
.cloned()
.collect();
for field in &new_fields {
match &field.field_type {
FieldType::Vector { algo, .. } => {
let live = match algo {
VectorAlgo::Flat => {
LiveIndex::Flat(Arc::new(crate::vector::VectorIndex::new()))
}
VectorAlgo::Hnsw {
m, ef_construction, ..
} => LiveIndex::Hnsw(Arc::new(crate::vector::HnswIndex::new(
*m,
*ef_construction,
))),
};
def.indexes.insert(field.name.clone(), live);
newly_added_vector_fields.push(field.name.clone());
}
FieldType::Text if !field.options.noindex => {
newly_added_text_fields.push(field.name.clone());
}
_ => {}
}
}
def.fields.extend(new_fields);
let altered = def.clone();
drop(store);
if !skip_initial_scan && !newly_added_vector_fields.is_empty() {
backfill_new_vector_fields(ctx, &index_name, &newly_added_vector_fields);
}
if !skip_initial_scan && !newly_added_text_fields.is_empty() {
crate::vector::backfill_text_fields(
&ctx.store[altered.db_index],
&altered,
&newly_added_text_fields,
);
}
if !added_filter_fields.is_empty() {
crate::vector::backfill_postings(
&ctx.store[altered.db_index],
&altered,
&added_filter_fields,
!skip_initial_scan,
);
}
Some(resp_simple("OK"))
}
type Row = ahash::AHashMap<String, String>;
pub(crate) fn ft_aggregate(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() < 3 {
return Some(resp_error(
"ERR wrong number of arguments for 'ft.aggregate' command",
));
}
let index_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let query_str = match std::str::from_utf8(cmd[2]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR query must be valid UTF-8")),
};
let index_store = ctx.index_store.read();
let def = match index_store.get(&index_name) {
Some(d) => d.clone(), None => {
return Some(resp_error(&crate::commands::search::no_such_index(
&index_name,
)));
}
};
drop(index_store);
let mut params = crate::vector::filter::Params::new();
if let Some(at) = cmd.iter().position(|a| a.eq_ignore_ascii_case(b"PARAMS")) {
let n = cmd
.get(at + 1)
.and_then(|a| std::str::from_utf8(a).ok())
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(0);
let values: Vec<&[u8]> = cmd.iter().skip(at + 2).take(n).copied().collect();
for pair in values.chunks(2) {
if let [name, value] = pair {
params.insert(String::from_utf8_lossy(name).into_owned(), value.to_vec());
}
}
}
let option = |name: &str| crate::commands::aggregate_pipeline::option_at(cmd, 3, name);
let value_of = |at: usize| cmd.get(at + 1).and_then(|a| std::str::from_utf8(a).ok());
let mut options = crate::vector::filter::QueryOptions {
verbatim: option("VERBATIM").is_some(),
language: None,
};
if let Some(at) = option("LANGUAGE") {
match value_of(at).and_then(crate::vector::stem::Language::parse) {
Some(language) => options.language = Some(language),
None => return Some(resp_error("No such language")),
}
}
let scorer = match option("SCORER") {
Some(at) => match value_of(at).and_then(crate::vector::score::Scorer::parse) {
Some(scorer) => scorer,
None => {
return Some(resp_error(&format!(
"No such scorer {}",
value_of(at).unwrap_or_default()
)));
}
},
None => crate::vector::score::Scorer::default_scorer(),
};
let (filter, knn) =
match crate::vector::filter::parse_query_with(&query_str, ¶ms, &def, options) {
Ok(query) => (query.filter, query.knn),
Err(e) => return Some(resp_error(&e)),
};
let addscores = cmd.iter().any(|a| a.eq_ignore_ascii_case(b"ADDSCORES"));
let scoring = crate::vector::score::Scoring::new(&def, &filter, scorer);
let cursor = match crate::commands::search_tools::cursor_options(cmd) {
Ok(cursor) => cursor,
Err(e) => return Some(resp_error(&e)),
};
let mut timeout_ms = None;
if let Some(at) = crate::commands::aggregate_pipeline::option_at(cmd, 3, "TIMEOUT") {
match cmd
.get(at + 1)
.and_then(|a| std::str::from_utf8(a).ok())
.and_then(|s| s.parse::<u64>().ok())
{
Some(ms) => timeout_ms = Some(ms),
None => {
return Some(resp_error(
"Bad arguments for TIMEOUT: expected a non-negative integer",
));
}
}
}
let deadline = crate::commands::search::search_deadline(timeout_ms);
let mut rows: Vec<Row> = Vec::new();
let db_ref = &ctx.store[*ctx.selected_db];
let served = ctx
.cluster
.enabled
.then(|| crate::cluster::search::served_slots(ctx.cluster));
let not_served = |key: &str| {
served.as_deref().is_some_and(|s| {
!crate::cluster::search::in_served(s, &*crate::key_bytes::bytes_of(key))
})
};
let json = matches!(def.on, crate::vector::IndexOn::Json);
let mut add_row = |key: &str,
inner: &crate::vector::Fields,
json_doc: Option<&serde_json::Value>| {
let mut row: Row = ahash::AHashMap::new();
if addscores {
let score = crate::commands::search::relevance(&def, key, inner, &scoring, json_doc);
if score == f64::NEG_INFINITY {
return;
}
row.insert(
"__score".to_string(),
crate::commands::search::number_text(score),
);
}
row.insert("__key".to_string(), key.to_string());
for (field, val) in inner.iter() {
let Ok(s) = std::str::from_utf8(val) else {
continue;
};
let shown = match def.fields.iter().find(|f| json && &f.name == field) {
Some(f) => f.attribute().to_string(),
None => field.clone(),
};
row.insert(shown, s.to_string());
}
rows.push(row);
};
let timed_out_scan = match crate::commands::search::plan(ctx, &def, &filter, None) {
Some(plan) => {
let mut seen = 0u32;
let mut cut = false;
for key in crate::commands::search::keys_of(&def, &plan.ids) {
if crate::commands::search::deadline_due(deadline, &mut seen) {
cut = true;
break;
}
if not_served(&key) {
continue;
}
crate::commands::search::with_doc(db_ref, &def, &key, |inner, json| {
if plan.exact || crate::vector::filter::eval(&filter, inner) {
add_row(&key, inner, json);
}
});
}
cut
}
None => crate::commands::search::scan_docs(db_ref, deadline, |key, value| {
if !def.covers(&crate::key_bytes::bytes_of(key)) {
return;
}
if not_served(key) {
return;
}
let Some(inner) = crate::vector::doc_fields(&def.on, &def.fields, value) else {
return;
};
if crate::vector::filter::eval(&filter, &*inner) {
let json = inner.json();
add_row(key, &inner, json);
}
}),
};
let mut timed_out = timed_out_scan;
if let Some(knn) = &knn {
let Some(field) = def.fields.iter().find(|f| f.name == knn.field) else {
return Some(resp_error("The vector field is gone from the index"));
};
let FieldType::Vector { metric, .. } = &field.field_type else {
return Some(resp_error("The vector field is gone from the index"));
};
let Some(live) = def.indexes.get(&knn.field) else {
return Some(resp_error("The vector field has no index"));
};
let candidates = rows
.iter()
.filter_map(|row| row.get("__key").map(String::as_str));
let (nearest, cut) = knn_filtered(live, &knn.vector, knn.k, metric, candidates, deadline);
timed_out |= cut;
let rank: ahash::AHashMap<String, (usize, f32)> = nearest
.into_iter()
.enumerate()
.map(|(i, found)| (found.key, (i, found.score)))
.collect();
rows.retain(|row| row.get("__key").is_some_and(|key| rank.contains_key(key)));
for row in &mut rows {
let (_, distance) = rank[&row["__key"]];
row.insert(
knn.alias.clone(),
crate::commands::search::distance_text(distance),
);
}
rows.sort_by_key(|row| rank[&row["__key"]].0);
}
if crate::cluster::search::is_forwarded(ctx) {
let flag = crate::cluster::search::wants_timeout_flag(cmd).then_some(timed_out);
return Some(crate::cluster::search::encode_rows(&rows, flag));
}
if crate::cluster::search::coordinates(ctx) {
let mut owned: Vec<Vec<u8>> = cmd.iter().map(|a| a.to_vec()).collect();
crate::cluster::search::ask_for_timeout_flag(&mut owned);
match crate::cluster::search::fan_out(ctx, &owned) {
Ok(replies) => {
for reply in replies {
let (more, shard_timed_out) = crate::cluster::search::decode_rows(reply);
rows.extend(more);
timed_out |= shard_timed_out;
}
}
Err(e) => return Some(resp_error(&e)),
}
if let Some(knn) = &knn {
let distance = |row: &Row| {
row.get(&knn.alias)
.and_then(|d| d.parse::<f64>().ok())
.unwrap_or(f64::INFINITY)
};
rows.sort_by(|a, b| distance(a).total_cmp(&distance(b)));
rows.truncate(knn.k);
}
}
if timed_out && crate::commands::search::on_timeout_fails() {
return Some(resp_error("Timeout limit was reached"));
}
let (rows, cut) = crate::commands::aggregate_pipeline::run_within(rows, cmd, 3, deadline);
timed_out |= cut;
if cut && crate::commands::search::on_timeout_fails() {
return Some(resp_error("Timeout limit was reached"));
}
let word = |i: usize| -> String {
cmd.get(i)
.map(|a| String::from_utf8_lossy(a).to_ascii_uppercase())
.unwrap_or_default()
};
let name = |i: usize| -> String {
cmd.get(i)
.map(|a| {
String::from_utf8_lossy(a)
.trim_start_matches('@')
.to_string()
})
.unwrap_or_default()
};
let count = |i: usize| -> usize { word(i).parse::<usize>().unwrap_or(0) };
let mut everything = false;
let mut grouped = false;
let mut shown: Vec<(String, String)> = Vec::new();
if addscores {
shown.push(("__score".to_string(), "__score".to_string()));
}
let mut i = 3usize;
while i < cmd.len() {
match word(i).as_str() {
"LOAD" if word(i + 1) == "*" => {
everything = true;
i += 2;
}
"LOAD" => {
let end = (i + 2 + count(i + 1)).min(cmd.len());
let mut at = i + 2;
while at < end {
let field = name(at);
at += 1;
let mut label = field.clone();
if at + 1 < end && word(at) == "AS" {
label = name(at + 1);
at += 2;
}
shown.push((field, label));
}
i = end;
}
"GROUPBY" => {
grouped = true;
i += 1;
}
"APPLY" => {
let label = if word(i + 2) == "AS" {
name(i + 3)
} else {
cmd.get(i + 1)
.map(|a| String::from_utf8_lossy(a).into_owned())
.unwrap_or_default()
};
shown.push((label.clone(), label));
i += 2;
}
"SORTBY" => {
let end = (i + 2 + count(i + 1)).min(cmd.len());
for arg in &cmd[(i + 2).min(end)..end] {
if let Some(field) = arg.strip_prefix(b"@") {
let field = String::from_utf8_lossy(field).into_owned();
shown.push((field.clone(), field));
}
}
i = end;
}
_ => i += 1,
}
}
let rows_out: Vec<crate::commands::search_tools::ShownRow> = rows
.into_iter()
.map(|row| {
let mut pairs: Vec<(String, String)> = Vec::new();
if everything || grouped {
if let Some(score) = row.get("__score").filter(|_| addscores && !grouped) {
pairs.push(("__score".to_string(), score.clone()));
}
let mut fields: Vec<(&String, &String)> =
row.iter().filter(|(k, _)| !k.starts_with("__")).collect();
fields.sort();
for (k, v) in fields {
pairs.push((k.clone(), v.clone()));
}
} else {
let mut seen: Vec<&str> = Vec::new();
for (field, label) in &shown {
if seen.contains(&label.as_str()) {
continue;
}
if let Some(value) = row.get(field) {
seen.push(label);
pairs.push((label.clone(), value.clone()));
}
}
}
pairs
})
.collect();
if let Some((count, max_idle)) = cursor {
return Some(crate::commands::search_tools::open_cursor(
ctx.resp,
&index_name,
rows_out,
count,
max_idle,
timed_out,
));
}
Some(crate::commands::search_tools::rows_reply(
ctx.resp,
rows_out.len(),
&rows_out,
timed_out,
))
}
pub(crate) fn format_f64(v: f64) -> String {
if v.fract() == 0.0 && v.abs() < 1e15 {
format!("{}", v as i64)
} else {
format!("{:.6}", v)
}
}
fn ft_tagvals(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() != 3 {
return Some(resp_error("ERR syntax: FT.TAGVALS index field"));
}
let index_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s,
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let field_name = match std::str::from_utf8(cmd[2]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR field name must be valid UTF-8")),
};
let (prefixes, tag_field, doc_on, doc_schema, db) = {
let store = ctx.index_store.read();
let def = match store.get(index_name) {
Some(d) => d,
None => {
return Some(resp_error(&crate::commands::search::no_such_index(
index_name,
)));
}
};
let tag_field = def
.field_by_attribute(&field_name)
.filter(|f| matches!(f.field_type, FieldType::Tag))
.map(|f| {
(
f.name.clone(),
f.options.separator,
f.options.case_sensitive,
)
});
(
def.prefixes.clone(),
tag_field,
def.on.clone(),
def.fields.clone(),
def.db_index,
)
};
let Some((stored_as, separator, case_sensitive)) = tag_field else {
return Some(resp_error(
"ERR field is not a TAG field or does not exist in index",
));
};
let mut distinct: ahash::AHashSet<String> = ahash::AHashSet::new();
let db_ref = &ctx.store[db];
for shard in db_ref.iter() {
let map = shard.read();
for (key, value) in map.iter() {
let matches =
prefixes.is_empty() || prefixes.iter().any(|p| key.starts_with(p.as_bytes()));
if !matches {
continue;
}
let Some(inner) = crate::vector::doc_fields(&doc_on, &doc_schema, value) else {
continue;
};
let Some(s) = inner
.get(&stored_as)
.and_then(|v| std::str::from_utf8(v).ok())
else {
continue;
};
for tag in crate::vector::filter::split_tags(s, separator) {
distinct.insert(if case_sensitive {
tag.to_string()
} else {
tag.to_lowercase()
});
}
}
}
if crate::cluster::search::coordinates(ctx) {
let owned: Vec<Vec<u8>> = ctx.cmd.iter().map(|a| a.to_vec()).collect();
match crate::cluster::search::fan_out(ctx, &owned) {
Ok(replies) => {
for reply in replies {
if let crate::cluster::search::Reply::Array(items) = reply {
distinct.extend(items.iter().filter_map(|v| v.text()));
}
}
}
Err(e) => return Some(resp_error(&e)),
}
}
let mut values: Vec<String> = distinct.into_iter().collect();
values.sort_unstable();
let items: Vec<Vec<u8>> = values.iter().map(|v| resp_bulk_str(v)).collect();
Some(resp_array(items))
}
fn ft_synupdate(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() < 4 {
return Some(resp_error(
"ERR syntax: FT.SYNUPDATE index group_id term [term ...]",
));
}
let index_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let group_id = match std::str::from_utf8(cmd[2]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR group ID must be valid UTF-8")),
};
let terms: Vec<String> = cmd[3..]
.iter()
.filter_map(|b| std::str::from_utf8(b).ok())
.filter(|s| !s.eq_ignore_ascii_case("SKIPINITIALSCAN"))
.map(|s| s.to_lowercase())
.collect();
if terms.is_empty() {
return Some(resp_error("ERR at least one term is required"));
}
let mut store = ctx.index_store.write();
let def = match store.get_mut(&index_name) {
Some(d) => d,
None => {
return Some(resp_error(&crate::commands::search::no_such_index(
&index_name,
)));
}
};
let group = def.synonyms.entry(group_id).or_insert_with(Vec::new);
for term in terms {
if !group.contains(&term) {
group.push(term);
}
}
drop(store);
Some(resp_simple("OK"))
}
fn ft_syndump(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() != 2 {
return Some(resp_error("ERR syntax: FT.SYNDUMP index"));
}
let index_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s,
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let store = ctx.index_store.read();
let def = match store.get(index_name) {
Some(d) => d,
None => {
return Some(resp_error(&crate::commands::search::no_such_index(
index_name,
)));
}
};
if def.synonyms.is_empty() {
return Some(resp_array(vec![]));
}
let mut term_to_groups: std::collections::BTreeMap<&str, Vec<&str>> =
std::collections::BTreeMap::new();
for (group_id, terms) in &def.synonyms {
for term in terms {
term_to_groups
.entry(term.as_str())
.or_default()
.push(group_id.as_str());
}
}
let mut out: Vec<Vec<u8>> = Vec::new();
for (term, mut groups) in term_to_groups {
groups.sort_unstable(); out.push(resp_bulk_str(term));
let group_items: Vec<Vec<u8>> = groups.iter().map(|g| resp_bulk_str(g)).collect();
out.push(resp_array(group_items));
}
Some(resp_array(out))
}
fn levenshtein(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
let (na, nb) = (a.len(), b.len());
if na == 0 {
return nb;
}
if nb == 0 {
return na;
}
let mut prev: Vec<usize> = (0..=nb).collect();
let mut curr: Vec<usize> = vec![0; nb + 1];
for i in 1..=na {
curr[0] = i; for j in 1..=nb {
let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
curr[j] = (prev[j] + 1) .min(curr[j - 1] + 1) .min(prev[j - 1] + cost); }
std::mem::swap(&mut prev, &mut curr);
}
prev[nb] }
fn ft_spellcheck(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() < 3 {
return Some(resp_error(
"ERR syntax: FT.SPELLCHECK index query [DISTANCE n]",
));
}
let index_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let query = match std::str::from_utf8(cmd[2]) {
Ok(s) => s.to_lowercase(),
Err(_) => return Some(resp_error("ERR query must be valid UTF-8")),
};
let mut max_distance: usize = 1; let mut i = 3;
while i < cmd.len() {
let tok = match std::str::from_utf8(cmd[i]) {
Ok(s) => s.to_ascii_uppercase(),
Err(_) => {
i += 1;
continue;
}
};
if tok == "DISTANCE" {
if let Some(d) = cmd
.get(i + 1)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|s| s.parse().ok())
{
max_distance = d;
}
i += 2;
} else {
i += 1;
}
}
let Some(def) = ctx.index_store.read().get(&index_name).cloned() else {
return Some(resp_error(&crate::commands::search::no_such_index(
&index_name,
)));
};
let mut include_dicts: Vec<String> = Vec::new();
let mut exclude_dicts: Vec<String> = Vec::new();
let mut j = 3usize;
while j < cmd.len() {
let tok = match std::str::from_utf8(cmd[j]) {
Ok(s) => s.to_ascii_uppercase(),
Err(_) => {
j += 1;
continue;
}
};
if tok == "TERMS" {
j += 1;
let mode = match std::str::from_utf8(cmd.get(j).unwrap_or(&b"".as_ref())) {
Ok(s) => s.to_ascii_uppercase(),
Err(_) => {
j += 1;
continue;
}
};
j += 1;
while j < cmd.len() {
let next = match std::str::from_utf8(cmd[j]) {
Ok(s) => s.to_ascii_uppercase(),
Err(_) => break,
};
if next == "TERMS" || next == "DISTANCE" || next == "DIALECT" {
break;
}
let dict_name = std::str::from_utf8(cmd[j]).unwrap_or("").to_string();
match mode.as_str() {
"INCLUDE" => include_dicts.push(dict_name),
"EXCLUDE" => exclude_dicts.push(dict_name),
_ => {}
}
j += 1;
}
} else {
j += 1;
}
}
let mut included: BTreeSet<String> = BTreeSet::new();
let mut excluded: BTreeSet<String> = BTreeSet::new();
{
let dict_store = ctx.dict_store.read();
for (names, into) in [
(&include_dicts, &mut included),
(&exclude_dicts, &mut excluded),
] {
for dict_name in names {
match dict_store.get(dict_name) {
Some(dict) => into.extend(dict.iter().cloned()),
None => {
return Some(resp_error(&format!("Dict does not exist: {dict_name}")));
}
}
}
}
}
let vocab: std::collections::BTreeMap<String, usize> = {
let text = def.text.read();
text.live_words()
.map(|(id, word)| (word.to_string(), text.df(id)))
.collect()
};
let cluster = ctx.cluster.enabled.then_some(&**ctx.cluster);
let total_docs =
crate::commands::search::count_docs(&ctx.store[def.db_index], &def, cluster).max(1) as f64;
let resp3 = ctx.resp == 3;
let score = |docs: usize| -> Vec<u8> {
let digits = crate::commands::helpers::format_score(docs as f64 / total_docs);
if resp3 {
format!(",{digits}\r\n").into_bytes()
} else {
resp_bulk_str(&digits)
}
};
let mut out: Vec<Vec<u8>> = Vec::new();
for token_clean in crate::vector::tokenize_for_vocab(&query) {
if token_clean.is_empty()
|| vocab.contains_key(&token_clean)
|| excluded.contains(&token_clean)
{
continue; }
let near = |word: &str| levenshtein(&token_clean, word) <= max_distance;
let mut candidates: Vec<(usize, &str)> = vocab
.iter()
.filter(|(word, _)| near(word))
.map(|(word, &docs)| (docs, word.as_str()))
.collect();
for word in &included {
if !vocab.contains_key(word) && near(word) {
candidates.push((0, word.as_str()));
}
}
candidates.sort_unstable_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
let suggestions: Vec<Vec<u8>> = candidates
.iter()
.map(|&(docs, word)| {
if resp3 {
resp_map(vec![resp_bulk_str(word), score(docs)])
} else {
resp_array(vec![score(docs), resp_bulk_str(word)])
}
})
.collect();
if resp3 {
out.push(resp_bulk_str(&token_clean));
out.push(resp_array(suggestions));
} else {
out.push(resp_array(vec![
resp_bulk_str("TERM"),
resp_bulk_str(&token_clean),
resp_array(suggestions),
]));
}
}
if resp3 {
return Some(resp_map(vec![resp_bulk_str("results"), resp_map(out)]));
}
Some(resp_array(out))
}
pub(crate) struct FilteredKnn<'a> {
live: &'a LiveIndex,
query: crate::vector::PreparedQuery<'a>,
best: Best,
}
impl<'a> FilteredKnn<'a> {
pub(crate) fn new(
live: &'a LiveIndex,
query: &'a [f32],
k: usize,
metric: &'a crate::vector::DistanceMetric,
) -> Self {
Self {
live,
query: crate::vector::PreparedQuery::new(metric, query),
best: Best::new(k),
}
}
#[inline]
pub(crate) fn offer(&mut self, key: &str) {
let dim = self.query.vector().len();
let distance = match self.live {
LiveIndex::Flat(idx) => {
let vectors = idx.vectors.read();
match vectors.get(key) {
Some(v) if v.len() == dim => self.query.to_raw(v),
_ => return,
}
}
LiveIndex::Hnsw(idx) => {
let Some(id) = idx.key_to_id.read().get(key).copied() else {
return;
};
let nodes = idx.nodes.read();
match idx.vector_of(&nodes, id, key) {
Some(v) if v.len() == dim => self.query.to_unit(v),
_ => return,
}
}
};
self.best.offer(distance, key);
}
pub(crate) fn nearest(self) -> Vec<crate::vector::KnnResult> {
self.best.into_sorted()
}
}
pub(crate) struct Best {
k: usize,
heap: std::collections::BinaryHeap<Far>,
}
struct Far(f32, String);
impl PartialEq for Far {
fn eq(&self, other: &Self) -> bool {
self.0.total_cmp(&other.0).is_eq()
}
}
impl Eq for Far {}
impl PartialOrd for Far {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Far {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.total_cmp(&other.0)
}
}
impl Best {
fn new(k: usize) -> Self {
Self {
k,
heap: std::collections::BinaryHeap::with_capacity(k.min(4096) + 1),
}
}
#[inline]
fn offer(&mut self, distance: f32, key: &str) {
if self.heap.len() < self.k {
self.heap.push(Far(distance, key.to_string()));
} else if let Some(mut top) = self.heap.peek_mut()
&& distance.total_cmp(&top.0).is_lt()
{
top.0 = distance;
top.1.clear();
top.1.push_str(key);
}
}
fn into_sorted(self) -> Vec<crate::vector::KnnResult> {
self.heap
.into_sorted_vec()
.into_iter()
.map(|Far(score, key)| crate::vector::KnnResult { key, score })
.collect()
}
}
pub(crate) fn measure_up_to(ef: usize, graph_size: usize) -> usize {
const C: f64 = 12.0;
let crossing = (C * ef as f64 * graph_size as f64).sqrt() as usize;
crossing.max(2000)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn knn_planned(
ctx: &Ctx,
def: &crate::vector::IndexDef,
filter: &crate::vector::filter::Filter,
only: Option<&ahash::AHashSet<String>>,
knn: &crate::vector::filter::Knn,
field: &crate::vector::SchemaField,
deadline: Option<std::time::Instant>,
) -> Option<(Vec<crate::vector::KnnResult>, bool)> {
let FieldType::Vector { metric, algo, .. } = &field.field_type else {
return None;
};
let live = def.indexes.get(&knn.field)?;
let mut plan = crate::commands::search::plan(ctx, def, filter, only)?;
if !plan.exact {
return None;
}
let ef = knn
.ef_runtime
.unwrap_or(match algo {
VectorAlgo::Hnsw { ef_runtime, .. } => *ef_runtime,
VectorAlgo::Flat => knn.k * 2,
})
.max(knn.k)
.max(50);
let db = &ctx.store[def.db_index];
for _ in 0..4 {
let (nearest, cut) = knn_among(def, &plan.ids, knn, live, metric, ef, deadline);
let gone: Vec<&str> = nearest
.iter()
.map(|r| r.key.as_str())
.filter(|key| {
let raw = crate::key_bytes::bytes_of(key);
!crate::store::get_shard(db, &*raw)
.read()
.get(&*raw)
.is_some_and(|v| crate::vector::is_document(&def.on, v))
})
.collect();
if gone.is_empty() || cut {
return Some((nearest, cut));
}
for key in gone {
if let Some(id) = def.postings.peek().id(key) {
plan.ids.unset(id);
}
crate::vector::maybe_unindex(
ctx.index_store,
def.db_index,
&*crate::key_bytes::bytes_of(key),
);
}
}
None
}
fn knn_among(
def: &crate::vector::IndexDef,
ids: &crate::vector::postings::Bits,
knn: &crate::vector::filter::Knn,
live: &LiveIndex,
metric: &crate::vector::DistanceMetric,
ef: usize,
deadline: Option<std::time::Instant>,
) -> (Vec<crate::vector::KnnResult>, bool) {
use crate::vector::filter::HybridPolicy;
use std::sync::atomic::Ordering::Relaxed;
let n = ids.count();
if let LiveIndex::Hnsw(graph) = live {
let size = graph.live_count.load(Relaxed);
let search = match knn.policy {
Some(HybridPolicy::AdhocBf) => false,
Some(HybridPolicy::Batches) => size >= 500,
None => size >= 500 && n > measure_up_to(ef, size),
};
if search {
let budget = if knn.policy == Some(HybridPolicy::Batches) {
usize::MAX
} else {
n
};
let prepared = crate::vector::PreparedQuery::new(metric, &knn.vector);
let mut admit = |node: &crate::vector::HnswNode| {
let mut doc = node.doc.load(Relaxed);
if doc == crate::vector::postings::NO_DOC {
match def.postings.peek().id(&node.key) {
Some(id) => {
node.doc.store(id, Relaxed);
doc = id;
}
None => return false,
}
}
ids.get(doc)
};
if let Some(found) = crate::vector::knn_hnsw_admitting(
graph,
prepared.vector(),
knn.k,
ef,
metric,
&mut admit,
budget,
deadline,
) {
return found;
}
}
}
knn_measured(def, ids, knn, live, metric, deadline)
}
fn knn_measured(
def: &crate::vector::IndexDef,
ids: &crate::vector::postings::Bits,
knn: &crate::vector::filter::Knn,
live: &LiveIndex,
metric: &crate::vector::DistanceMetric,
deadline: Option<std::time::Instant>,
) -> (Vec<crate::vector::KnnResult>, bool) {
let keys = crate::commands::search::keys_of(def, ids);
let query = crate::vector::PreparedQuery::new(metric, &knn.vector);
let dim = knn.vector.len();
let mut best = Best::new(knn.k);
const RUN: usize = 256;
let mut cut = false;
for (i, run) in keys.chunks(RUN).enumerate() {
if i > 0 && i % 4 == 0 && crate::commands::search::past_deadline(deadline) {
cut = true;
break;
}
match live {
LiveIndex::Flat(idx) => {
let vectors = idx.vectors.read();
for key in run {
if let Some(v) = vectors.get(&**key)
&& v.len() == dim
{
best.offer(query.to_raw(v), key);
}
}
}
LiveIndex::Hnsw(graph) => {
let found: Vec<(usize, &Arc<str>)> = {
let key_to_id = graph.key_to_id.read();
run.iter()
.filter_map(|key| key_to_id.get(&**key).map(|&id| (id, key)))
.collect()
};
let nodes = graph.nodes.read();
for (id, key) in found {
if let Some(v) = graph.vector_of(&nodes, id, key)
&& v.len() == dim
{
best.offer(query.to_unit(v), key);
}
}
}
}
}
(best.into_sorted(), cut)
}
pub(crate) fn knn_filtered<'k>(
live_index: &crate::vector::LiveIndex,
query: &[f32],
k: usize,
metric: &crate::vector::DistanceMetric,
candidates: impl IntoIterator<Item = &'k str>,
deadline: Option<std::time::Instant>,
) -> (Vec<crate::vector::KnnResult>, bool) {
let mut scorer = FilteredKnn::new(live_index, query, k, metric);
let mut seen = 0u32;
let mut cut = false;
for key in candidates {
if crate::commands::search::deadline_due(deadline, &mut seen) {
cut = true;
break;
}
scorer.offer(key);
}
(scorer.nearest(), cut)
}
fn backfill_new_vector_fields(ctx: &Ctx, index_name: &str, new_field_names: &[String]) {
use crate::vector::FieldType;
let store = ctx.index_store.read();
let def = match store.get(index_name) {
Some(d) => d,
None => return, };
struct FieldWork {
name: String,
dim: usize,
data_type: crate::vector::VectorType,
metric: crate::vector::DistanceMetric,
live: LiveIndex,
}
let mut work: Vec<FieldWork> = Vec::with_capacity(new_field_names.len());
for name in new_field_names {
let vf = match def.vector_field_by_name(name) {
Some(f) => f,
None => continue,
};
let (dim, data_type, metric) = match &vf.field_type {
FieldType::Vector {
dim,
data_type,
metric,
..
} => (*dim, *data_type, metric.clone()),
_ => continue,
};
let live = match def.indexes.get(name) {
Some(LiveIndex::Flat(a)) => LiveIndex::Flat(Arc::clone(a)),
Some(LiveIndex::Hnsw(a)) => LiveIndex::Hnsw(Arc::clone(a)),
None => continue,
};
work.push(FieldWork {
name: name.clone(),
dim,
data_type,
metric,
live,
});
}
let def = def.clone();
drop(store);
if work.is_empty() {
return;
}
crate::vector::walk_documents(&ctx.store[def.db_index], &def, |key, inner| {
for w in &work {
let raw_bytes = match inner.get(&w.name) {
Some(b) => b,
None => continue,
};
let Some(vec) = w.data_type.decode(raw_bytes, w.dim) else {
continue;
};
match &w.live {
LiveIndex::Flat(idx) => idx.insert(key.to_string(), vec),
LiveIndex::Hnsw(idx) => {
crate::vector::hnsw_insert(idx, key.to_string(), vec, &w.metric);
}
}
}
});
}
fn alias_args(ctx: &Ctx, command: &str) -> Result<(String, String), Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() != 3 {
return Err(resp_error(&format!(
"ERR wrong number of arguments for '{command}' command"
)));
}
let alias =
std::str::from_utf8(cmd[1]).map_err(|_| resp_error("ERR alias must be valid UTF-8"))?;
let index = std::str::from_utf8(cmd[2])
.map_err(|_| resp_error("ERR index name must be valid UTF-8"))?;
Ok((alias.to_string(), index.to_string()))
}
fn ft_alias_add(ctx: &mut Ctx) -> Option<Vec<u8>> {
let (alias, index) = match alias_args(ctx, "FT.ALIASADD") {
Ok(args) => args,
Err(e) => return Some(e),
};
let mut store = ctx.index_store.write();
if store.contains_key(&alias) {
return Some(resp_error("ERR Alias already exists"));
}
let Some(real) = crate::vector::resolve_index_name(&store, &index) else {
return Some(resp_error(&crate::commands::search::no_such_index(&index)));
};
let def = store[&real].clone();
crate::vector::set_alias(&mut store, &alias, &def);
Some(resp_simple("OK"))
}
fn ft_alias_del(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() != 2 {
return Some(resp_error(
"ERR wrong number of arguments for 'FT.ALIASDEL' command",
));
}
let alias = match std::str::from_utf8(cmd[1]) {
Ok(s) => s,
Err(_) => return Some(resp_error("ERR alias must be valid UTF-8")),
};
let mut store = ctx.index_store.write();
if !store
.get(alias)
.is_some_and(|def| crate::vector::is_alias(alias, def))
{
return Some(resp_error("ERR Alias does not exist"));
}
store.remove(alias);
Some(resp_simple("OK"))
}
fn ft_alias_update(ctx: &mut Ctx) -> Option<Vec<u8>> {
let (alias, index) = match alias_args(ctx, "FT.ALIASUPDATE") {
Ok(args) => args,
Err(e) => return Some(e),
};
let mut store = ctx.index_store.write();
if store
.get(&alias)
.is_some_and(|def| !crate::vector::is_alias(&alias, def))
{
return Some(resp_error("ERR Alias already exists as an index name"));
}
let Some(real) = crate::vector::resolve_index_name(&store, &index) else {
return Some(resp_error(&crate::commands::search::no_such_index(&index)));
};
let def = store[&real].clone();
crate::vector::set_alias(&mut store, &alias, &def);
Some(resp_simple("OK"))
}
fn ft_alias_list(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() != 2 {
return Some(resp_error(
"ERR wrong number of arguments for 'FT.ALIASLIST' command",
));
}
let index = match std::str::from_utf8(cmd[1]) {
Ok(s) => s,
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let store = ctx.index_store.read();
if store
.get(index)
.is_none_or(|def| crate::vector::is_alias(index, def))
{
return Some(resp_error(&crate::commands::search::no_such_index(index)));
}
let aliases: Vec<Vec<u8>> = crate::vector::index_aliases(&store, index)
.iter()
.map(|alias| resp_bulk_str(alias))
.collect();
let resp = crate::commands::handler::effective_resp_for_reply(ctx);
Some(resp_set_for(resp, aliases))
}
fn ft_dictadd(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() < 3 {
return Some(resp_error("ERR syntax: FT.DICTADD dict term [term ...]"));
}
let dict_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR dict name must be valid UTF-8")),
};
let terms: Vec<String> = cmd[2..]
.iter()
.filter_map(|b| std::str::from_utf8(b).ok())
.map(|s| s.to_lowercase())
.collect();
let mut store = ctx.dict_store.write();
let dict = store.entry(dict_name).or_default();
let mut added = 0i64;
for term in terms {
if dict.insert(term) {
added += 1;
}
}
drop(store);
Some(resp_integer(added))
}
fn ft_dictdel(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() < 3 {
return Some(resp_error("ERR syntax: FT.DICTDEL dict term [term ...]"));
}
let dict_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s,
Err(_) => return Some(resp_error("ERR dict name must be valid UTF-8")),
};
let mut store = ctx.dict_store.write();
let dict = match store.get_mut(dict_name) {
Some(d) => d,
None => return Some(resp_integer(0)), };
let mut removed = 0i64;
for term_bytes in &cmd[2..] {
if let Ok(term) = std::str::from_utf8(term_bytes)
&& dict.remove(&term.to_lowercase())
{
removed += 1;
}
}
drop(store);
Some(resp_integer(removed))
}
fn ft_dictdump(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() != 2 {
return Some(resp_error("ERR syntax: FT.DICTDUMP dict"));
}
let dict_name = match std::str::from_utf8(cmd[1]) {
Ok(s) => s,
Err(_) => return Some(resp_error("ERR dict name must be valid UTF-8")),
};
let store = ctx.dict_store.read();
let dict = match store.get(dict_name) {
Some(d) => d,
None => return Some(resp_array(vec![])),
};
let mut words: Vec<&str> = dict.iter().map(|s| s.as_str()).collect();
words.sort_unstable();
let items: Vec<Vec<u8>> = words.iter().map(|w| resp_bulk_str(w)).collect();
Some(resp_array(items))
}
fn ft_debug(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() < 2 {
return Some(resp_error("ERR syntax: FT.DEBUG <subcommand> [args...]"));
}
let sub = std::str::from_utf8(cmd[1])
.map(|s| s.to_ascii_uppercase())
.unwrap_or_default();
match sub.as_str() {
"COMPACT" => ft_debug_compact(ctx),
"POSTINGS" => ft_debug_postings(ctx),
"PAGE" => ft_debug_page(ctx),
"HELP" if cmd.len() == 2 => Some(resp_array(
["COMPACT", "POSTINGS", "PAGE", "HELP"]
.iter()
.map(|name| resp_bulk_str(name))
.collect(),
)),
_ => Some(resp_error(&format!(
"ERR unknown FT.DEBUG subcommand '{sub}'"
))),
}
}
fn ft_debug_postings(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
let on = match cmd.get(3) {
Some(w) if cmd.len() == 4 && w.eq_ignore_ascii_case(b"ON") => true,
Some(w) if cmd.len() == 4 && w.eq_ignore_ascii_case(b"OFF") => false,
_ => return Some(resp_error("ERR syntax: FT.DEBUG POSTINGS <index> ON|OFF")),
};
let name = String::from_utf8_lossy(cmd[2]).into_owned();
let Some(def) = ctx.index_store.read().get(&name).cloned() else {
return Some(resp_error(&crate::commands::search::no_such_index(&name)));
};
def.postings.write().unused = !on;
Some(resp_simple("OK"))
}
fn ft_debug_page(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
let on = match cmd.get(3) {
Some(w) if cmd.len() == 4 && w.eq_ignore_ascii_case(b"ON") => true,
Some(w) if cmd.len() == 4 && w.eq_ignore_ascii_case(b"OFF") => false,
_ => return Some(resp_error("ERR syntax: FT.DEBUG PAGE <index> ON|OFF")),
};
let name = String::from_utf8_lossy(cmd[2]).into_owned();
let Some(def) = ctx.index_store.read().get(&name).cloned() else {
return Some(resp_error(&crate::commands::search::no_such_index(&name)));
};
def.postings.write().read_all = !on;
Some(resp_simple("OK"))
}
fn ft_debug_compact(ctx: &mut Ctx) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
if cmd.len() != 4 {
return Some(resp_error("ERR syntax: FT.DEBUG COMPACT <index> <field>"));
}
let index_name = match std::str::from_utf8(cmd[2]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR index name must be valid UTF-8")),
};
let field_name = match std::str::from_utf8(cmd[3]) {
Ok(s) => s.to_string(),
Err(_) => return Some(resp_error("ERR field name must be valid UTF-8")),
};
{
let store = ctx.index_store.read();
let def = match store.get(&index_name) {
Some(d) => d,
None => {
return Some(resp_error(&crate::commands::search::no_such_index(
&index_name,
)));
}
};
match def.indexes.get(&field_name) {
Some(crate::vector::LiveIndex::Hnsw(_)) => {}
Some(_) => {
return Some(resp_error(
"ERR FT.DEBUG COMPACT only supported on HNSW fields",
));
}
None => {
return Some(resp_error("ERR no such vector field on index"));
}
}
}
let req = crate::vector::CompactionRequest {
index_name,
field_name,
};
let _ = ctx.compaction_tx.try_send(req);
Some(resp_simple("OK"))
}
#[cfg(test)]
mod filtered_knn_tests {
use super::*;
fn vector(dim: usize, seed: u64) -> Vec<f32> {
let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
(0..dim)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
((state >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
})
.collect()
}
fn exact(
data: &[(String, Vec<f32>)],
keys: &[&str],
q: &[f32],
k: usize,
metric: &crate::vector::DistanceMetric,
) -> Vec<String> {
let mut scored: Vec<(f32, &str)> = data
.iter()
.filter(|(key, _)| keys.contains(&key.as_str()))
.map(|(key, v)| (crate::vector::distance(metric, q, v), key.as_str()))
.collect();
scored.sort_by(|a, b| a.0.total_cmp(&b.0));
scored
.into_iter()
.take(k)
.map(|(_, key)| key.to_string())
.collect()
}
#[test]
fn the_scorer_keeps_the_exact_nearest_of_the_keys_offered() {
use crate::vector::{DistanceMetric, HnswIndex, VectorIndex};
let dim = 37;
let data: Vec<(String, Vec<f32>)> = (0..600)
.map(|i| (format!("doc:{i}"), vector(dim, i as u64 + 1)))
.collect();
let mut keys: Vec<&str> = data.iter().step_by(3).map(|(k, _)| k.as_str()).collect();
keys.push("doc:none");
for metric in [
DistanceMetric::Cosine,
DistanceMetric::L2,
DistanceMetric::InnerProduct,
] {
let flat = Arc::new(VectorIndex::new());
let graph = Arc::new(HnswIndex::new(16, 64));
for (key, v) in &data {
flat.insert(key.clone(), v.clone());
crate::vector::hnsw_insert(&graph, key.clone(), v.clone(), &metric);
}
let q = vector(dim, 9_999);
for k in [0usize, 1, 10, 500] {
let want = exact(&data, &keys, &q, k, &metric);
for live in [
LiveIndex::Flat(flat.clone()),
LiveIndex::Hnsw(graph.clone()),
] {
let (got, cut) =
knn_filtered(&live, &q, k, &metric, keys.iter().copied(), None);
assert!(!cut);
let got_keys: Vec<String> = got.iter().map(|r| r.key.clone()).collect();
assert_eq!(got_keys.len(), want.len(), "{metric:?} k={k}");
let mut a = got_keys.clone();
let mut b = want.clone();
a.sort();
b.sort();
assert_eq!(a, b, "{metric:?} k={k}");
assert!(got.windows(2).all(|w| w[0].score <= w[1].score));
}
}
}
}
}