qdrant_client/filters.rs
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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
use crate::qdrant::condition::ConditionOneOf;
use crate::qdrant::points_selector::PointsSelectorOneOf;
use crate::qdrant::r#match::MatchValue;
use crate::qdrant::{
self, Condition, DatetimeRange, FieldCondition, Filter, GeoBoundingBox, GeoPolygon, GeoRadius,
HasIdCondition, IsEmptyCondition, IsNullCondition, MinShould, NestedCondition, PointId,
PointsSelector, Range, ValuesCount,
};
impl From<Filter> for PointsSelector {
fn from(filter: Filter) -> Self {
PointsSelector {
points_selector_one_of: Some(PointsSelectorOneOf::Filter(filter)),
}
}
}
impl From<FieldCondition> for Condition {
fn from(field_condition: FieldCondition) -> Self {
Condition {
condition_one_of: Some(ConditionOneOf::Field(field_condition)),
}
}
}
impl From<IsEmptyCondition> for Condition {
fn from(is_empty_condition: IsEmptyCondition) -> Self {
Condition {
condition_one_of: Some(ConditionOneOf::IsEmpty(is_empty_condition)),
}
}
}
impl From<IsNullCondition> for Condition {
fn from(is_null_condition: IsNullCondition) -> Self {
Condition {
condition_one_of: Some(ConditionOneOf::IsNull(is_null_condition)),
}
}
}
impl From<HasIdCondition> for Condition {
fn from(has_id_condition: HasIdCondition) -> Self {
Condition {
condition_one_of: Some(ConditionOneOf::HasId(has_id_condition)),
}
}
}
impl From<Filter> for Condition {
fn from(filter: Filter) -> Self {
Condition {
condition_one_of: Some(ConditionOneOf::Filter(filter)),
}
}
}
impl From<NestedCondition> for Condition {
fn from(nested_condition: NestedCondition) -> Self {
debug_assert!(
!&nested_condition
.filter
.as_ref()
.map_or(false, |f| f.check_has_id()),
"Filters containing a `has_id` condition are not supported for nested filtering."
);
Condition {
condition_one_of: Some(ConditionOneOf::Nested(nested_condition)),
}
}
}
impl qdrant::Filter {
/// Checks if the filter, or any of its nested conditions containing filters,
/// have a `has_id` condition, which is not allowed for nested object filters.
fn check_has_id(&self) -> bool {
self.should
.iter()
.chain(self.must.iter())
.chain(self.must_not.iter())
.any(|cond| match &cond.condition_one_of {
Some(ConditionOneOf::HasId(_)) => true,
Some(ConditionOneOf::Nested(nested)) => nested
.filter
.as_ref()
.map_or(false, |filter| filter.check_has_id()),
Some(ConditionOneOf::Filter(filter)) => filter.check_has_id(),
_ => false,
})
}
/// Create a [`Filter`] where all the conditions must be satisfied.
pub fn must(conds: impl IntoIterator<Item = qdrant::Condition>) -> Self {
Self {
must: conds.into_iter().collect(),
..Default::default()
}
}
/// Create a [`Filter`] where at least one of the conditions should be satisfied.
pub fn should(conds: impl IntoIterator<Item = qdrant::Condition>) -> Self {
Self {
should: conds.into_iter().collect(),
..Default::default()
}
}
/// Create a [`Filter`] where at least a minimum amount of given conditions should be statisfied.
pub fn min_should(min_count: u64, conds: impl IntoIterator<Item = qdrant::Condition>) -> Self {
Self {
min_should: Some(MinShould {
min_count,
conditions: conds.into_iter().collect(),
}),
..Default::default()
}
}
/// Create a [`Filter`] where none of the conditions must be satisfied.
pub fn must_not(conds: impl IntoIterator<Item = qdrant::Condition>) -> Self {
Self {
must_not: conds.into_iter().collect(),
..Default::default()
}
}
/// Alias for [`should`](Self::should).
///
/// Create a [`Filter`] that matches if any of the conditions match.
pub fn any(conds: impl IntoIterator<Item = qdrant::Condition>) -> Self {
Self::should(conds)
}
/// Alias for [`must`](Self::must).
///
/// Create a [`Filter`] that matches if all of the conditions match.
pub fn all(conds: impl IntoIterator<Item = qdrant::Condition>) -> Self {
Self::must(conds)
}
/// Alias for [`must_not`](Self::must_not).
///
/// Create a [`Filter`] that matches if none of the conditions match.
pub fn none(conds: impl IntoIterator<Item = qdrant::Condition>) -> Self {
Self::must_not(conds)
}
}
impl qdrant::Condition {
/// Create a [`Condition`] to check if a field is empty.
///
/// # Examples:
/// ```
/// qdrant_client::qdrant::Condition::is_empty("field");
/// ```
pub fn is_empty(key: impl Into<String>) -> Self {
Self::from(qdrant::IsEmptyCondition { key: key.into() })
}
/// Create a [`Condition`] to check if the point has a null key.
///
/// # Examples:
/// ```
/// qdrant_client::qdrant::Condition::is_empty("remark");
/// ```
pub fn is_null(key: impl Into<String>) -> Self {
Self::from(qdrant::IsNullCondition { key: key.into() })
}
/// Create a [`Condition`] to check if the point has one of the given ids.
///
/// # Examples:
/// ```
/// qdrant_client::qdrant::Condition::has_id([0, 8, 15]);
/// ```
pub fn has_id(ids: impl IntoIterator<Item = impl Into<PointId>>) -> Self {
Self::from(qdrant::HasIdCondition {
has_id: ids.into_iter().map(Into::into).collect(),
})
}
/// Create a [`Condition`] that matches a field against a certain value.
///
/// # Examples:
/// ```
/// qdrant_client::qdrant::Condition::matches("number", 42);
/// qdrant_client::qdrant::Condition::matches("tag", vec!["i".to_string(), "em".into()]);
/// ```
pub fn matches(field: impl Into<String>, r#match: impl Into<MatchValue>) -> Self {
Self {
condition_one_of: Some(ConditionOneOf::Field(qdrant::FieldCondition {
key: field.into(),
r#match: Some(qdrant::Match {
match_value: Some(r#match.into()),
}),
..Default::default()
})),
}
}
/// Create a [`Condition`] to initiate full text match.
///
/// # Examples:
/// ```
/// qdrant_client::qdrant::Condition::matches_text("description", "good cheap");
/// ```
pub fn matches_text(field: impl Into<String>, query: impl Into<String>) -> Self {
Self {
condition_one_of: Some(ConditionOneOf::Field(qdrant::FieldCondition {
key: field.into(),
r#match: Some(qdrant::Match {
match_value: Some(MatchValue::Text(query.into())),
}),
..Default::default()
})),
}
}
/// Create a [`Condition`] that checks numeric fields against a range.
///
/// # Examples:
///
/// ```
/// use qdrant_client::qdrant::Range;
/// qdrant_client::qdrant::Condition::range("number", Range {
/// gte: Some(42.),
/// ..Default::default()
/// });
/// ```
pub fn range(field: impl Into<String>, range: Range) -> Self {
Self {
condition_one_of: Some(ConditionOneOf::Field(qdrant::FieldCondition {
key: field.into(),
range: Some(range),
..Default::default()
})),
}
}
/// Create a [`Condition`] that checks datetime fields against a range.
///
/// # Examples:
///
/// ```
/// use qdrant_client::qdrant::{DatetimeRange, Timestamp};
/// qdrant_client::qdrant::Condition::datetime_range("timestamp", DatetimeRange {
/// gte: Some(Timestamp::date(2023, 2, 8).unwrap()),
/// ..Default::default()
/// });
/// ```
pub fn datetime_range(field: impl Into<String>, range: DatetimeRange) -> Self {
Self {
condition_one_of: Some(ConditionOneOf::Field(qdrant::FieldCondition {
key: field.into(),
datetime_range: Some(range),
..Default::default()
})),
}
}
/// Create a [`Condition`] that checks geo fields against a radius.
///
/// # Examples:
///
/// ```
/// use qdrant_client::qdrant::{GeoPoint, GeoRadius};
/// qdrant_client::qdrant::Condition::geo_radius("location", GeoRadius {
/// center: Some(GeoPoint { lon: 42., lat: 42. }),
/// radius: 42.,
/// });
pub fn geo_radius(field: impl Into<String>, geo_radius: GeoRadius) -> Self {
Self {
condition_one_of: Some(ConditionOneOf::Field(qdrant::FieldCondition {
key: field.into(),
geo_radius: Some(geo_radius),
..Default::default()
})),
}
}
/// Create a [`Condition`] that checks geo fields against a bounding box.
///
/// # Examples:
///
/// ```
/// use qdrant_client::qdrant::{GeoPoint, GeoBoundingBox};
/// qdrant_client::qdrant::Condition::geo_bounding_box("location", GeoBoundingBox {
/// top_left: Some(GeoPoint { lon: 42., lat: 42. }),
/// bottom_right: Some(GeoPoint { lon: 42., lat: 42. }),
/// });
pub fn geo_bounding_box(field: impl Into<String>, geo_bounding_box: GeoBoundingBox) -> Self {
Self {
condition_one_of: Some(ConditionOneOf::Field(qdrant::FieldCondition {
key: field.into(),
geo_bounding_box: Some(geo_bounding_box),
..Default::default()
})),
}
}
/// Create a [`Condition`] that checks geo fields against a geo polygons.
///
/// # Examples:
///
/// ```
/// use qdrant_client::qdrant::{GeoLineString, GeoPoint, GeoPolygon};
/// let polygon = GeoPolygon {
/// exterior: Some(GeoLineString { points: vec![GeoPoint { lon: 42., lat: 42. }]}),
/// interiors: vec![],
/// };
/// qdrant_client::qdrant::Condition::geo_polygon("location", polygon);
pub fn geo_polygon(field: impl Into<String>, geo_polygon: GeoPolygon) -> Self {
Self {
condition_one_of: Some(ConditionOneOf::Field(qdrant::FieldCondition {
key: field.into(),
geo_polygon: Some(geo_polygon),
..Default::default()
})),
}
}
/// Create a [`Condition`] that checks count of values in a field.
///
/// # Examples:
///
/// ```
/// use qdrant_client::qdrant::ValuesCount;
/// qdrant_client::qdrant::Condition::values_count("tags", ValuesCount {
/// gte: Some(42),
/// ..Default::default()
/// });
pub fn values_count(field: impl Into<String>, values_count: ValuesCount) -> Self {
Self {
condition_one_of: Some(ConditionOneOf::Field(qdrant::FieldCondition {
key: field.into(),
values_count: Some(values_count),
..Default::default()
})),
}
}
/// Create a [`Condition`] that applies a per-element filter to a nested array
///
/// The `field` parameter should be a key-path to a nested array of objects.
/// You may specify it as both `array_field` or `array_field[]`.
///
/// For motivation and further examples,
/// see [API documentation](https://qdrant.tech/documentation/concepts/filtering/#nested-object-filter).
///
/// # Panics:
///
/// If debug assertions are enabled, this will panic if the filter, or any its subfilters,
/// contain a [`HasIdCondition`] (equivalently, a condition created with `Self::has_id`),
/// as these are unsupported for nested object filters.
///
/// # Examples:
///
/// ```
/// use qdrant_client::qdrant::Filter;
/// qdrant_client::qdrant::Condition::nested("array_field[]", Filter::any([
/// qdrant_client::qdrant::Condition::is_null("element_field")
/// ]));
pub fn nested(field: impl Into<String>, filter: Filter) -> Self {
Self::from(NestedCondition {
key: field.into(),
filter: Some(filter),
})
}
}
impl From<bool> for MatchValue {
fn from(value: bool) -> Self {
Self::Boolean(value)
}
}
impl From<i64> for MatchValue {
fn from(value: i64) -> Self {
Self::Integer(value)
}
}
impl From<String> for MatchValue {
fn from(value: String) -> Self {
if value.contains(char::is_whitespace) {
Self::Text(value)
} else {
Self::Keyword(value)
}
}
}
impl From<Vec<i64>> for MatchValue {
fn from(integers: Vec<i64>) -> Self {
Self::Integers(qdrant::RepeatedIntegers { integers })
}
}
impl From<Vec<String>> for MatchValue {
fn from(strings: Vec<String>) -> Self {
Self::Keywords(qdrant::RepeatedStrings { strings })
}
}
impl std::ops::Not for MatchValue {
type Output = Self;
fn not(self) -> Self::Output {
match self {
Self::Keyword(s) => Self::ExceptKeywords(qdrant::RepeatedStrings { strings: vec![s] }),
Self::Integer(i) => {
Self::ExceptIntegers(qdrant::RepeatedIntegers { integers: vec![i] })
}
Self::Boolean(b) => Self::Boolean(!b),
Self::Keywords(ks) => Self::ExceptKeywords(ks),
Self::Integers(is) => Self::ExceptIntegers(is),
Self::ExceptKeywords(ks) => Self::Keywords(ks),
Self::ExceptIntegers(is) => Self::Integers(is),
Self::Text(_) => panic!("cannot negate a MatchValue::Text"),
}
}
}
#[cfg(test)]
mod tests {
use crate::qdrant::{Condition, Filter, NestedCondition};
#[test]
fn test_nested_has_id() {
assert!(!Filter::any([]).check_has_id());
assert!(Filter::any([Condition::has_id([0])]).check_has_id());
// nested filter
assert!(Filter::any([Filter::any([Condition::has_id([0])]).into()]).check_has_id());
// nested filter where only the innermost has a `has_id`
assert!(
Filter::any([Filter::any([Filter::any([Condition::has_id([0])]).into()]).into()])
.check_has_id()
);
// `has_id` itself nested in a nested condition
assert!(Filter::any([Condition {
condition_one_of: Some(crate::qdrant::condition::ConditionOneOf::Nested(
NestedCondition {
key: "test".to_string(),
filter: Some(Filter::any([Condition::has_id([0])]))
}
))
}])
.check_has_id());
}
#[test]
#[should_panic]
fn test_nested_condition_validation() {
let _ = Filter::any([Condition::nested(
"test",
Filter::any([Condition::has_id([0])]),
)]);
}
}