linkrs-core 0.1.0

Core data structures, types, and errors for Linkrs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Transport-independent vector payload types shared across crates.
//!
//! # Type categories
//!
//! This module contains two logically distinct groups of types:
//!
//! ## Core shared types (`PointId`, `Payload`, `PayloadValue`, `PayloadSchemaType`)
//! True foundational types used by the wire layer (`linkrs-wire`), the storage
//! engine, and the query layer. These must remain in `linkrs-core` because
//! `linkrs-wire` depends on `linkrs-core` but cannot depend on `simvec`
//! (it would drag in heavy transitive deps like rayon/memmap2 into a lightweight
//! wire crate).
//!
//! ## Vector filter DSL types (`VectorFilter`, `FilterCondition`, `ConditionType`, etc.)
//! Transport-semantics copies of the filter types. The index-semantics
//! canonical definitions live in the `simvec` crate (`simvec::filter_cond`);
//! this module keeps an identical transport-facing copy because
//! `linkrs-wire` depends on `linkrs-core` and cannot depend on `simvec`
//! (it would drag in heavy transitive deps like rayon/memmap2 into a
//! lightweight wire crate). The two copies are converted mechanically at
//! the sync-side backend enumeration boundary; keep them in sync when
//! changing the filter surface.

use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Core shared types
// ---------------------------------------------------------------------------

/// Payload attached to a vector point: a JSON object keyed by field name.
pub type Payload = HashMap<String, serde_json::Value>;

/// A scalar payload value (alias of `serde_json::Value`).
pub type PayloadValue = serde_json::Value;

/// Point identifier: numeric or UUID-shaped string.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum PointId {
    Num(u64),
    Uuid(String),
}

impl From<u64> for PointId {
    fn from(v: u64) -> Self {
        Self::Num(v)
    }
}

impl From<String> for PointId {
    fn from(v: String) -> Self {
        // Numeric strings normalize to `Num` so an id round-trips through
        // its string form regardless of the wire encoding.
        if let Ok(n) = v.parse::<u64>() {
            Self::Num(n)
        } else {
            Self::Uuid(v)
        }
    }
}

impl From<&str> for PointId {
    fn from(v: &str) -> Self {
        Self::from(v.to_string())
    }
}

impl std::fmt::Display for PointId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Num(n) => write!(f, "{n}"),
            Self::Uuid(s) => write!(f, "{s}"),
        }
    }
}

/// Declared schema of an indexed payload field.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema,
)]
pub enum PayloadSchemaType {
    Keyword,
    Integer,
    Float,
    Text,
    Bool,
    Geo,
    Datetime,
}

impl PayloadSchemaType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Keyword => "keyword",
            Self::Integer => "integer",
            Self::Float => "float",
            Self::Text => "text",
            Self::Bool => "bool",
            Self::Geo => "geo",
            Self::Datetime => "datetime",
        }
    }
}

// ---------------------------------------------------------------------------
// Vector filter DSL types
//
// These are logically part of `simvec` but live in core due to the
// dependency DAG constraint. The filter evaluation logic is in
// `simvec::filter`. Downstream crates may import these from either
// `linkrs_core::vector` or `simvec::types`.
// ---------------------------------------------------------------------------

/// Geographic point (`lat`, `lon` in degrees).
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct GeoPoint {
    pub lat: f64,
    pub lon: f64,
}

impl GeoPoint {
    pub fn new(lat: f64, lon: f64) -> Self {
        Self { lat, lon }
    }
}

/// Radius filter around a geographic center.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct GeoRadius {
    pub center: GeoPoint,
    /// Radius in meters.
    pub radius: f64,
}

impl GeoRadius {
    pub fn new(center: GeoPoint, radius: f64) -> Self {
        Self { center, radius }
    }
}

/// Lat/lon bounding-box filter.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct GeoBoundingBox {
    pub top_left: GeoPoint,
    pub bottom_right: GeoPoint,
}

impl GeoBoundingBox {
    pub fn new(top_left: GeoPoint, bottom_right: GeoPoint) -> Self {
        Self {
            top_left,
            bottom_right,
        }
    }
}

/// Range bound on the number of values an array field holds.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct ValuesCountCondition {
    pub gt: Option<u64>,
    pub gte: Option<u64>,
    pub lt: Option<u64>,
    pub lte: Option<u64>,
}

impl ValuesCountCondition {
    pub fn new() -> Self {
        Self {
            gt: None,
            gte: None,
            lt: None,
            lte: None,
        }
    }

    pub fn gt(mut self, value: u64) -> Self {
        self.gt = Some(value);
        self
    }

    pub fn gte(mut self, value: u64) -> Self {
        self.gte = Some(value);
        self
    }

    pub fn lt(mut self, value: u64) -> Self {
        self.lt = Some(value);
        self
    }

    pub fn lte(mut self, value: u64) -> Self {
        self.lte = Some(value);
        self
    }
}

impl Default for ValuesCountCondition {
    fn default() -> Self {
        Self::new()
    }
}

/// Top-level payload filter with Qdrant-style clause groups.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[schema(no_recursion)]
pub struct VectorFilter {
    pub must: Option<Vec<FilterCondition>>,
    pub must_not: Option<Vec<FilterCondition>>,
    pub should: Option<Vec<FilterCondition>>,
    pub min_should: Option<MinShouldCondition>,
}

impl VectorFilter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn must(mut self, condition: FilterCondition) -> Self {
        self.must.get_or_insert_with(Vec::new).push(condition);
        self
    }

    pub fn must_not(mut self, condition: FilterCondition) -> Self {
        self.must_not.get_or_insert_with(Vec::new).push(condition);
        self
    }

    pub fn should(mut self, condition: FilterCondition) -> Self {
        self.should.get_or_insert_with(Vec::new).push(condition);
        self
    }
}

/// `should` clause with an explicit minimum match count.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[schema(no_recursion)]
pub struct MinShouldCondition {
    pub conditions: Vec<FilterCondition>,
    pub min_count: usize,
}

/// A single filter condition: field plus its predicate.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[schema(no_recursion)]
pub struct FilterCondition {
    pub field: String,
    pub condition: ConditionType,
}

impl FilterCondition {
    pub fn new(field: impl Into<String>, condition: ConditionType) -> Self {
        Self {
            field: field.into(),
            condition,
        }
    }

    pub fn match_value(field: impl Into<String>, value: impl Into<String>) -> Self {
        Self::new(
            field,
            ConditionType::Match {
                value: value.into(),
            },
        )
    }

    pub fn match_any(field: impl Into<String>, values: Vec<PayloadValue>) -> Self {
        Self::new(field, ConditionType::MatchAny { values })
    }

    pub fn range(field: impl Into<String>, range: RangeCondition) -> Self {
        Self::new(field, ConditionType::Range(range))
    }

    pub fn is_empty(field: impl Into<String>) -> Self {
        Self::new(field, ConditionType::IsEmpty)
    }

    pub fn is_null(field: impl Into<String>) -> Self {
        Self::new(field, ConditionType::IsNull)
    }

    pub fn has_id(ids: Vec<String>) -> Self {
        Self::new("_id", ConditionType::HasId { ids })
    }

    pub fn geo_radius(field: impl Into<String>, radius: GeoRadius) -> Self {
        Self::new(field, ConditionType::GeoRadius(radius))
    }

    pub fn geo_bounding_box(field: impl Into<String>, bbox: GeoBoundingBox) -> Self {
        Self::new(field, ConditionType::GeoBoundingBox(bbox))
    }

    pub fn values_count(field: impl Into<String>, count: ValuesCountCondition) -> Self {
        Self::new(field, ConditionType::ValuesCount(count))
    }

    pub fn contains(field: impl Into<String>, value: impl Into<String>) -> Self {
        Self::new(
            field,
            ConditionType::Contains {
                value: value.into(),
            },
        )
    }
}

/// Predicate of a [`FilterCondition`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[schema(no_recursion)]
pub enum ConditionType {
    /// Match a scalar field value.
    Match {
        value: String,
    },
    /// Match any of the given values (OR semantics).
    MatchAny {
        #[schema(value_type = Vec<serde_json::Value>)]
        values: Vec<PayloadValue>,
    },
    /// Numeric range over the field value.
    Range(RangeCondition),
    IsEmpty,
    IsNull,
    HasId {
        ids: Vec<String>,
    },
    Nested {
        filter: Box<VectorFilter>,
    },
    GeoRadius(GeoRadius),
    GeoBoundingBox(GeoBoundingBox),
    ValuesCount(ValuesCountCondition),
    Contains {
        value: String,
    },
}

/// Numeric range bounds; absent bounds are open.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct RangeCondition {
    pub gt: Option<f64>,
    pub gte: Option<f64>,
    pub lt: Option<f64>,
    pub lte: Option<f64>,
}

impl RangeCondition {
    pub fn new() -> Self {
        Self {
            gt: None,
            gte: None,
            lt: None,
            lte: None,
        }
    }

    pub fn gt(mut self, value: f64) -> Self {
        self.gt = Some(value);
        self
    }

    pub fn gte(mut self, value: f64) -> Self {
        self.gte = Some(value);
        self
    }

    pub fn lt(mut self, value: f64) -> Self {
        self.lt = Some(value);
        self
    }

    pub fn lte(mut self, value: f64) -> Self {
        self.lte = Some(value);
        self
    }
}

impl Default for RangeCondition {
    fn default() -> Self {
        Self::new()
    }
}

/// Returned-payload projection for search results.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct PayloadSelector {
    pub include: Option<Vec<String>>,
    pub exclude: Option<Vec<String>>,
}

impl PayloadSelector {
    /// Apply this selector to a payload map: include-list keeps only the
    /// listed fields, exclude-list removes them.
    pub fn apply(&self, payload: &Payload) -> Payload {
        let mut out = if let Some(include) = &self.include {
            include
                .iter()
                .filter_map(|k| payload.get(k).map(|v| (k.clone(), v.clone())))
                .collect::<Payload>()
        } else {
            payload.clone()
        };
        if let Some(exclude) = &self.exclude {
            for k in exclude {
                out.remove(k);
            }
        }
        out
    }

    pub fn include(fields: Vec<String>) -> Self {
        Self {
            include: Some(fields),
            exclude: None,
        }
    }

    pub fn exclude(fields: Vec<String>) -> Self {
        Self {
            include: None,
            exclude: Some(fields),
        }
    }

    pub fn all() -> Self {
        Self {
            include: None,
            exclude: None,
        }
    }
}