use super::{DocMeta, FieldType};
use crate::error::{NasaRedisError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumOp {
Gt,
Gte,
Lt,
Lte,
Eq,
}
#[derive(Debug, Clone)]
pub enum Cond {
TagEq {
field: String,
value: String,
},
TagIn {
field: String,
values: Vec<String>,
},
NumBetween {
field: String,
min: f64,
max: f64,
},
NumCmp {
field: String,
op: NumOp,
value: f64,
},
TextMatch {
field: String,
text: String,
},
TextPrefix {
field: String,
prefix: String,
},
TextSuffix {
field: String,
suffix: String,
},
TextContains {
field: String,
infix: String,
},
TextFuzzy {
field: String,
term: String,
distance: u8,
},
TextPhrase {
field: String,
phrase: String,
},
GeoWithin {
field: String,
lon: f64,
lat: f64,
radius: f64,
unit: GeoUnit,
},
Raw(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GeoUnit {
M,
Km,
Mi,
Ft,
}
impl GeoUnit {
fn as_str(&self) -> &'static str {
match self {
GeoUnit::M => "m",
GeoUnit::Km => "km",
GeoUnit::Mi => "mi",
GeoUnit::Ft => "ft",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Query {
conds: Vec<Cond>,
sort: Option<(String, bool)>, offset: usize,
limit: usize,
limit_explicit: bool,
}
impl Query {
pub fn new() -> Self {
Self {
conds: Vec::new(),
sort: None,
offset: 0,
limit: 10,
limit_explicit: false,
}
}
pub fn tag_eq(mut self, field: &str, value: &str) -> Self {
self.conds.push(Cond::TagEq {
field: field.into(),
value: value.into(),
});
self
}
pub fn tag_in(mut self, field: &str, values: &[&str]) -> Self {
self.conds.push(Cond::TagIn {
field: field.into(),
values: values.iter().map(|s| s.to_string()).collect(),
});
self
}
pub fn between(mut self, field: &str, min: f64, max: f64) -> Self {
self.conds.push(Cond::NumBetween {
field: field.into(),
min,
max,
});
self
}
fn num_cmp(mut self, field: &str, op: NumOp, value: f64) -> Self {
self.conds.push(Cond::NumCmp {
field: field.into(),
op,
value,
});
self
}
pub fn gt(self, field: &str, value: f64) -> Self {
self.num_cmp(field, NumOp::Gt, value)
}
pub fn gte(self, field: &str, value: f64) -> Self {
self.num_cmp(field, NumOp::Gte, value)
}
pub fn lt(self, field: &str, value: f64) -> Self {
self.num_cmp(field, NumOp::Lt, value)
}
pub fn lte(self, field: &str, value: f64) -> Self {
self.num_cmp(field, NumOp::Lte, value)
}
pub fn num_eq(self, field: &str, value: f64) -> Self {
self.num_cmp(field, NumOp::Eq, value)
}
pub fn text_match(mut self, field: &str, text: &str) -> Self {
self.conds.push(Cond::TextMatch {
field: field.into(),
text: text.into(),
});
self
}
pub fn text_prefix(mut self, field: &str, prefix: &str) -> Self {
self.conds.push(Cond::TextPrefix {
field: field.into(),
prefix: prefix.into(),
});
self
}
pub fn text_suffix(mut self, field: &str, suffix: &str) -> Self {
self.conds.push(Cond::TextSuffix {
field: field.into(),
suffix: suffix.into(),
});
self
}
pub fn text_contains(mut self, field: &str, infix: &str) -> Self {
self.conds.push(Cond::TextContains {
field: field.into(),
infix: infix.into(),
});
self
}
pub fn text_fuzzy(mut self, field: &str, term: &str, distance: u8) -> Self {
self.conds.push(Cond::TextFuzzy {
field: field.into(),
term: term.into(),
distance,
});
self
}
pub fn text_phrase(mut self, field: &str, phrase: &str) -> Self {
self.conds.push(Cond::TextPhrase {
field: field.into(),
phrase: phrase.into(),
});
self
}
pub fn geo_within(
mut self,
field: &str,
lon: f64,
lat: f64,
radius: f64,
unit: GeoUnit,
) -> Self {
self.conds.push(Cond::GeoWithin {
field: field.into(),
lon,
lat,
radius,
unit,
});
self
}
pub fn raw(mut self, expr: &str) -> Self {
self.conds.push(Cond::Raw(expr.into()));
self
}
pub fn sort_desc(mut self, field: &str) -> Self {
self.sort = Some((field.into(), true));
self
}
pub fn sort_asc(mut self, field: &str) -> Self {
self.sort = Some((field.into(), false));
self
}
pub fn limit(mut self, offset: usize, limit: usize) -> Self {
self.offset = offset;
self.limit = limit;
self.limit_explicit = true;
self
}
pub fn is_limit_explicit(&self) -> bool {
self.limit_explicit
}
pub fn effective_offset(&self) -> usize {
self.offset
}
pub fn effective_limit(&self) -> usize {
self.limit
}
pub fn render(&self, meta: &DocMeta) -> Result<String> {
if self.conds.is_empty() {
return Ok("*".into()); }
let mut parts = Vec::with_capacity(self.conds.len());
for c in &self.conds {
parts.push(match c {
Cond::TagEq { field, value } => {
let f = require_field(meta, field, "TagEq")?;
require_type(f, matches!(f.ftype, FieldType::Tag { .. }), "Tag")?;
format!("@{}:{{{}}}", f.alias_or_name(), escape_tag(value))
}
Cond::TagIn { field, values } => {
let f = require_field(meta, field, "TagIn")?;
require_type(f, matches!(f.ftype, FieldType::Tag { .. }), "Tag")?;
let alts: Vec<String> = values.iter().map(|v| escape_tag(v)).collect();
format!("@{}:{{{}}}", f.alias_or_name(), alts.join("|"))
}
Cond::NumBetween { field, min, max } => {
let f = require_field(meta, field, "NumBetween")?;
require_type(f, matches!(f.ftype, FieldType::Numeric { .. }), "Numeric")?;
if !min.is_finite() || !max.is_finite() {
return Err(NasaRedisError::Config(format!(
"NumBetween 字段 \"{field}\" 的 min/max 必须有限(min={min}, max={max})"
)));
}
if min > max {
return Err(NasaRedisError::Config(format!(
"NumBetween 字段 \"{field}\" min({min}) > max({max}),空区间"
)));
}
format!("@{}:[{} {}]", f.alias_or_name(), min, max)
}
Cond::NumCmp { field, op, value } => {
let f = require_field(meta, field, "NumCmp")?;
require_type(f, matches!(f.ftype, FieldType::Numeric { .. }), "Numeric")?;
if !value.is_finite() {
return Err(NasaRedisError::Config(format!(
"NumCmp 字段 \"{field}\" 的值必须有限(value={value})"
)));
}
let range = match op {
NumOp::Gt => format!("[({value} +inf]"),
NumOp::Gte => format!("[{value} +inf]"),
NumOp::Lt => format!("[-inf ({value}]"),
NumOp::Lte => format!("[-inf {value}]"),
NumOp::Eq => format!("[{value} {value}]"),
};
format!("@{}:{}", f.alias_or_name(), range)
}
Cond::TextMatch { field, text } => {
let f = require_field(meta, field, "TextMatch")?;
require_type(f, matches!(f.ftype, FieldType::Text { .. }), "Text")?;
let esc = escape_text(text);
if esc.trim().is_empty() {
return Ok(String::new()); }
format!("@{}:({})", f.alias_or_name(), esc)
}
Cond::TextPrefix { field, prefix } => {
let f = require_field(meta, field, "TextPrefix")?;
require_type(f, matches!(f.ftype, FieldType::Text { .. }), "Text")?;
let esc = escape_text(prefix);
if esc.trim().is_empty() {
return Ok(String::new());
}
format!("@{}:({}*)", f.alias_or_name(), esc)
}
Cond::TextSuffix { field, suffix } => {
let f = require_field(meta, field, "TextSuffix")?;
require_suffix_trie(f, "TextSuffix")?;
let esc = escape_text(suffix);
if esc.trim().is_empty() {
return Ok(String::new());
}
format!("@{}:(*{})", f.alias_or_name(), esc)
}
Cond::TextContains { field, infix } => {
let f = require_field(meta, field, "TextContains")?;
require_suffix_trie(f, "TextContains")?;
let esc = escape_text(infix);
if esc.trim().is_empty() {
return Ok(String::new());
}
format!("@{}:(*{}*)", f.alias_or_name(), esc)
}
Cond::TextFuzzy {
field,
term,
distance,
} => {
let f = require_field(meta, field, "TextFuzzy")?;
require_type(f, matches!(f.ftype, FieldType::Text { .. }), "Text")?;
let esc = escape_text(term);
if esc.trim().is_empty() {
return Ok(String::new());
}
let pct = "%".repeat((*distance).clamp(1, 3) as usize);
format!("@{}:({}{}{})", f.alias_or_name(), pct, esc, pct)
}
Cond::TextPhrase { field, phrase } => {
let f = require_field(meta, field, "TextPhrase")?;
require_type(f, matches!(f.ftype, FieldType::Text { .. }), "Text")?;
let esc: String = phrase
.chars()
.flat_map(|c| match c {
'"' => vec!['\\', '"'],
'\\' => vec!['\\', '\\'],
c => vec![c],
})
.collect();
format!("@{}:(\"{}\")", f.alias_or_name(), esc)
}
Cond::GeoWithin {
field,
lon,
lat,
radius,
unit,
} => {
let f = require_field(meta, field, "GeoWithin")?;
require_type(f, matches!(f.ftype, FieldType::Geo), "Geo")?;
if !lon.is_finite() || !lat.is_finite() || !radius.is_finite() || *radius < 0.0
{
return Err(NasaRedisError::Config(format!(
"GeoWithin 字段 \"{field}\":lon/lat/radius 必须有限且 radius≥0"
)));
}
format!(
"@{}:[{} {} {} {}]",
f.alias_or_name(),
lon,
lat,
radius,
unit.as_str()
)
}
Cond::Raw(expr) => format!("({expr})"),
});
}
Ok(parts.join(" ")) }
pub fn render_args(&self, meta: &DocMeta) -> Result<Vec<String>> {
let mut args = Vec::new();
if let Some((field, desc)) = &self.sort {
let f = require_field(meta, field, "sort")?;
let sortable = matches!(
f.ftype,
FieldType::Tag { sortable: true, .. }
| FieldType::Text { sortable: true, .. }
| FieldType::Numeric { sortable: true, .. }
);
if !sortable {
return Err(NasaRedisError::Config(format!(
"字段 \"{field}\" 未声明 SORTABLE,不能排序(metadata 构建期约束)"
)));
}
args.push("SORTBY".into());
args.push(f.alias_or_name().to_string());
args.push(if *desc {
"DESC".into()
} else {
"ASC".into()
});
}
args.push("LIMIT".into());
args.push(self.offset.to_string());
args.push(self.limit.to_string());
Ok(args)
}
}
fn require_field<'a>(meta: &'a DocMeta, alias: &str, ctx: &str) -> Result<&'a super::FieldMeta> {
meta.field(alias).ok_or_else(|| {
NasaRedisError::Config(format!(
"{ctx}: 字段 \"{alias}\" 不在 DocMeta(可用: {:?})",
meta.fields
.iter()
.map(|f| f.alias_or_name())
.collect::<Vec<_>>()
))
})
}
fn require_suffix_trie(f: &super::FieldMeta, ctx: &str) -> Result<()> {
let ok = matches!(
f.ftype,
FieldType::Text {
with_suffix_trie: true,
..
} | FieldType::Tag {
with_suffix_trie: true,
..
}
);
if !ok {
return Err(NasaRedisError::Config(format!(
"{ctx}: 字段 \"{}\" 需 Text/Tag 且建索引时 WITHSUFFIXTRIE(实际 {:?})",
f.alias_or_name(),
f.ftype
)));
}
Ok(())
}
fn require_type(f: &super::FieldMeta, ok: bool, want: &str) -> Result<()> {
if !ok {
return Err(NasaRedisError::Config(format!(
"字段 \"{}\" 类型 {:?} 与条件不符(需要 {want})",
f.alias_or_name(),
f.ftype
)));
}
Ok(())
}
impl Query {
pub fn render_json_path_filter(&self, meta: &DocMeta) -> Result<String> {
if self.sort.is_some() {
return Err(NasaRedisError::Config(
"ARRAY 模式不支持 sort(子文档级排序 RedisJSON 不支持;需排序用 DataType::Json)"
.into(),
));
}
if self.limit_explicit {
return Err(NasaRedisError::Config(
"ARRAY 模式不支持分页(子文档级 limit 不支持;需分页用 DataType::Json 或业务层补救)"
.into(),
));
}
if self.conds.is_empty() {
return Ok("$[*]".into());
}
let mut parts = Vec::with_capacity(self.conds.len());
for c in &self.conds {
parts.push(match c {
Cond::TagEq { field, value } => {
let f = require_field(meta, field, "TagEq")?;
require_type(f, matches!(f.ftype, FieldType::Tag { .. }), "Tag")?;
format!("@.{}=={}", f.alias_or_name(), json_path_literal(value)?)
}
Cond::TagIn { field, values } => {
let f = require_field(meta, field, "TagIn")?;
require_type(f, matches!(f.ftype, FieldType::Tag { .. }), "Tag")?;
let alias = f.alias_or_name();
let alts: Vec<String> = values
.iter()
.map(|v| Ok(format!("@.{alias}=={}", json_path_literal(v)?)))
.collect::<Result<Vec<_>>>()?;
format!("({})", alts.join(" || "))
}
Cond::NumBetween { field, min, max } => {
let f = require_field(meta, field, "NumBetween")?;
require_type(f, matches!(f.ftype, FieldType::Numeric { .. }), "Numeric")?;
if !min.is_finite() || !max.is_finite() {
return Err(NasaRedisError::Config(
"JSONPath 数值必须有限(NaN/Infinity 非法)".into(),
));
}
if min > max {
return Err(NasaRedisError::Config(format!(
"NumBetween 字段 \"{field}\" min({min}) > max({max}),空区间"
)));
}
let alias = f.alias_or_name();
format!("(@.{alias}>={min} && @.{alias}<={max})")
}
Cond::NumCmp { field, op, value } => {
let f = require_field(meta, field, "NumCmp")?;
require_type(f, matches!(f.ftype, FieldType::Numeric { .. }), "Numeric")?;
if !value.is_finite() {
return Err(NasaRedisError::Config(
"JSONPath 数值必须有限(NaN/Infinity 非法)".into(),
));
}
let alias = f.alias_or_name();
match op {
NumOp::Gt => format!("(@.{alias}>{value})"),
NumOp::Gte => format!("(@.{alias}>={value})"),
NumOp::Lt => format!("(@.{alias}<{value})"),
NumOp::Lte => format!("(@.{alias}<={value})"),
NumOp::Eq => format!("(@.{alias}=={value})"),
}
}
Cond::TextMatch { .. }
| Cond::TextPrefix { .. }
| Cond::TextSuffix { .. }
| Cond::TextContains { .. }
| Cond::TextFuzzy { .. }
| Cond::TextPhrase { .. }
| Cond::GeoWithin { .. } => {
return Err(NasaRedisError::Config(
"ARRAY 模式不支持 TEXT/GEO 查询(TextMatch/Prefix/Suffix/Contains/Fuzzy/Phrase/GeoWithin 是 FT 引擎语义,JSONPath 无对应)".into(),
))
}
Cond::Raw(_) => {
return Err(NasaRedisError::Config(
"ARRAY 模式不支持 Raw(FT 语法不能注入 JSONPath)".into(),
))
}
});
}
Ok(format!("$[?({})]", parts.join(" && ")))
}
}
#[derive(Debug, Clone)]
pub enum Reducer {
Count,
Sum(String),
Avg(String),
Min(String),
Max(String),
CountDistinct(String),
StdDev(String),
ToList(String),
Quantile(String, f64),
FirstValue(String),
}
#[derive(Debug, Clone, Default)]
pub struct Aggregate {
load: Vec<String>, group_by: Vec<String>,
reducers: Vec<(Reducer, String)>, applies: Vec<(String, String)>, filters: Vec<String>, sort_by: Vec<(String, bool)>, limit: Option<(usize, usize)>,
}
impl Aggregate {
pub fn new() -> Self {
Self::default()
}
pub fn load(mut self, fields: &[&str]) -> Self {
self.load.extend(fields.iter().map(|s| s.to_string()));
self
}
pub fn apply(mut self, expr: &str, as_alias: &str) -> Self {
self.applies.push((expr.into(), as_alias.into()));
self
}
pub fn filter(mut self, expr: &str) -> Self {
self.filters.push(expr.into());
self
}
pub fn group_by(mut self, field: &str) -> Self {
self.group_by.push(field.into());
self
}
pub fn reduce(mut self, r: Reducer, as_alias: &str) -> Self {
self.reducers.push((r, as_alias.into()));
self
}
pub fn sort_desc(mut self, alias: &str) -> Self {
self.sort_by.push((alias.into(), true));
self
}
pub fn sort_asc(mut self, alias: &str) -> Self {
self.sort_by.push((alias.into(), false));
self
}
pub fn limit(mut self, offset: usize, limit: usize) -> Self {
self.limit = Some((offset, limit));
self
}
pub fn render_args(&self, meta: &DocMeta) -> Result<Vec<String>> {
let mut args = Vec::new();
if !self.load.is_empty() {
args.push("LOAD".into());
args.push(self.load.len().to_string());
for f in &self.load {
let fm = require_field(meta, f, "LOAD")?;
args.push(format!("@{}", fm.alias_or_name()));
}
}
if !self.group_by.is_empty() || !self.reducers.is_empty() {
args.push("GROUPBY".into());
args.push(self.group_by.len().to_string()); for g in &self.group_by {
let f = require_field(meta, g, "GROUPBY")?;
args.push(format!("@{}", f.alias_or_name()));
}
for (r, alias) in &self.reducers {
args.push("REDUCE".into());
match r {
Reducer::Count => {
args.push("COUNT".into());
args.push("0".into());
}
Reducer::Quantile(field, q) => {
if !(0.0..=1.0).contains(q) {
return Err(NasaRedisError::Config(format!(
"QUANTILE q 必须 ∈ [0,1],得到 {q}"
)));
}
args.push("QUANTILE".into());
args.push("2".into());
let f = require_field(meta, field, "REDUCE")?;
args.push(format!("@{}", f.alias_or_name()));
args.push(q.to_string());
}
_ => {
let (kw, field) = match r {
Reducer::Sum(f) => ("SUM", f),
Reducer::Avg(f) => ("AVG", f),
Reducer::Min(f) => ("MIN", f),
Reducer::Max(f) => ("MAX", f),
Reducer::CountDistinct(f) => ("COUNT_DISTINCT", f),
Reducer::StdDev(f) => ("STDDEV", f),
Reducer::ToList(f) => ("TOLIST", f),
Reducer::FirstValue(f) => ("FIRST_VALUE", f),
Reducer::Count | Reducer::Quantile(..) => unreachable!(),
};
args.push(kw.into());
args.push("1".into());
let fm = require_field(meta, field, "REDUCE")?;
args.push(format!("@{}", fm.alias_or_name()));
}
}
args.push("AS".into());
args.push(alias.clone());
}
}
for (expr, alias) in &self.applies {
if expr.trim().is_empty() || alias.trim().is_empty() {
return Err(NasaRedisError::Config(format!(
"Aggregate APPLY 表达式/别名不能为空(expr={expr:?}, alias={alias:?})"
)));
}
args.push("APPLY".into());
args.push(expr.clone());
args.push("AS".into());
args.push(alias.clone());
}
for expr in &self.filters {
if expr.trim().is_empty() {
return Err(NasaRedisError::Config(
"Aggregate FILTER 表达式不能为空".into(),
));
}
args.push("FILTER".into());
args.push(expr.clone());
}
if !self.sort_by.is_empty() {
let mut valid: Vec<String> = self.reducers.iter().map(|(_, a)| a.clone()).collect();
valid.extend(self.applies.iter().map(|(_, a)| a.clone()));
for g in &self.group_by {
valid.push(
require_field(meta, g, "SORTBY")?
.alias_or_name()
.to_string(),
);
}
valid.extend(self.load.iter().cloned());
args.push("SORTBY".into());
args.push((self.sort_by.len() * 2).to_string());
for (alias, desc) in &self.sort_by {
if !valid.iter().any(|v| v == alias) {
return Err(NasaRedisError::Config(format!(
"Aggregate SORTBY 别名 \"{alias}\" 不在 GROUPBY 输出列/reducer/APPLY 别名中(可用: {valid:?})"
)));
}
args.push(format!("@{alias}"));
args.push(if *desc {
"DESC".into()
} else {
"ASC".into()
});
}
}
if let Some((offset, limit)) = self.limit {
args.push("LIMIT".into());
args.push(offset.to_string());
args.push(limit.to_string());
}
Ok(args)
}
}
pub(crate) fn json_path_literal(s: &str) -> Result<String> {
if let Some(c) = s.chars().find(|c| (*c as u32) < 0x20) {
return Err(NasaRedisError::Config(format!(
"ARRAY JSONPath 值含控制字符 U+{:04X},无法在 JSONPath 引号字面量中表达(改用 FT 索引模式)",
c as u32
)));
}
let quote = match (s.contains('\''), s.contains('"')) {
(true, true) => {
return Err(NasaRedisError::Config(
"ARRAY JSONPath 值同时含 ' 和 \":RedisJSON 不认引号内 `\\` 转义,无法用引号字面量表达——改 FT 索引模式或避免该值".into(),
))
}
(true, false) => '"', _ => '\'', };
Ok(format!("{quote}{s}{quote}"))
}
fn escape_tag(v: &str) -> String {
let mut out = String::with_capacity(v.len() + 4);
for ch in v.chars() {
let keep =
ch.is_ascii_alphanumeric() || ch == '_' || ('\u{4e00}'..='\u{9fa5}').contains(&ch);
if !keep {
out.push('\\');
}
out.push(ch);
}
out
}
fn escape_text(v: &str) -> String {
let mut out = String::with_capacity(v.len());
for ch in v.chars() {
let keep = ch == ' '
|| ch.is_ascii_alphanumeric()
|| ch == '_'
|| ('\u{4e00}'..='\u{9fa5}').contains(&ch);
out.push(if keep {
ch
} else {
' '
});
}
out
}