Spaces:
Build error
Build error
File size: 36,539 Bytes
84d2a97 |
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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 |
//! Types used within `LocalShard` to represent a planned `ShardQueryRequest`
use common::types::ScoreType;
use segment::types::{Filter, SearchParams, WithPayloadInterface, WithVector};
use super::shard_query::{SampleInternal, ScoringQuery, ShardPrefetch, ShardQueryRequest};
use crate::operations::types::{
CollectionError, CollectionResult, CoreSearchRequest, QueryScrollRequestInternal, ScrollOrder,
};
const MAX_PREFETCH_DEPTH: usize = 64;
/// The planned representation of multiple [ShardQueryRequest]s, which flattens all the
/// leaf queries into a batch of searches and scrolls.
#[derive(Debug, Default)]
pub struct PlannedQuery {
/// References to the searches and scrolls, and how to merge them.
/// This retains the recursive structure of the original queries.
///
/// One per each query in the batch
pub root_plans: Vec<MergePlan>,
/// All the leaf core searches
pub searches: Vec<CoreSearchRequest>,
/// All the leaf scrolls
pub scrolls: Vec<QueryScrollRequestInternal>,
}
/// Defines how to merge multiple [sources](Source)
#[derive(Debug, PartialEq)]
pub struct RescoreParams {
/// Alter the scores before selecting the best limit
pub rescore: ScoringQuery,
/// Keep this many points from the top
pub limit: usize,
/// Keep only points with better score than this threshold
pub score_threshold: Option<ScoreType>,
/// The vector(s) to return
pub with_vector: WithVector,
/// The payload to return
pub with_payload: WithPayloadInterface,
/// Parameters for the rescore search request
pub params: Option<SearchParams>,
}
#[derive(Debug, PartialEq)]
pub enum Source {
/// A reference offset into the main search batch
SearchesIdx(usize),
/// A reference offset into the scrolls list
ScrollsIdx(usize),
/// A nested prefetch
Prefetch(Box<MergePlan>),
}
#[derive(Debug, PartialEq)]
pub struct MergePlan {
/// Gather all these sources
pub sources: Vec<Source>,
/// How to merge the sources
///
/// If this is [None], then it means one of two things:
/// 1. It is a top-level query without prefetches, so sources must be of length 1.
/// 2. It is a top-level fusion query, so sources will be returned as-is. They will be merged later at collection level
pub rescore_params: Option<RescoreParams>,
}
impl PlannedQuery {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, request: ShardQueryRequest) -> CollectionResult<()> {
let depth = request.prefetches_depth();
let ShardQueryRequest {
prefetches,
query,
filter,
score_threshold,
limit,
offset,
with_vector,
with_payload,
params,
} = request;
// Final offset is handled at collection level
let limit = limit + offset;
let merge_plan = if !prefetches.is_empty() {
if depth > MAX_PREFETCH_DEPTH {
return Err(CollectionError::bad_request(format!(
"prefetches depth {depth} exceeds max depth {MAX_PREFETCH_DEPTH}"
)));
}
let rescore = query.ok_or_else(|| {
CollectionError::bad_request("cannot have prefetches without a query".to_string())
})?;
if rescore.needs_intermediate_results() {
// pass `with_vector` and `with_payload` down one level, as the sources will be sent as intermediate results to the collection
let sources = recurse_prefetches(
&mut self.searches,
&mut self.scrolls,
prefetches,
offset,
&filter,
Some((with_payload, with_vector)),
)?;
MergePlan {
sources,
// We will propagate the intermediate results, the fusion will take place at collection level.
// It is fine to lose this rescore information here.
rescore_params: None,
}
} else {
let sources = recurse_prefetches(
&mut self.searches,
&mut self.scrolls,
prefetches,
offset,
&filter,
None,
)?;
MergePlan {
sources,
rescore_params: Some(RescoreParams {
rescore,
limit,
score_threshold,
with_vector,
with_payload,
params,
}),
}
}
} else {
let sources = match query {
Some(ScoringQuery::Vector(query)) => {
// Everything should come from 1 core search
let core_search = CoreSearchRequest {
query,
filter,
score_threshold,
with_vector: Some(with_vector),
with_payload: Some(with_payload),
offset: 0, // offset is handled at collection level
params,
limit,
};
let idx = self.searches.len();
self.searches.push(core_search);
vec![Source::SearchesIdx(idx)]
}
Some(ScoringQuery::Fusion(_)) => {
return Err(CollectionError::bad_request(
"cannot apply Fusion without prefetches".to_string(),
))
}
Some(ScoringQuery::OrderBy(order_by)) => {
// Everything should come from 1 scroll
let scroll = QueryScrollRequestInternal {
scroll_order: ScrollOrder::ByField(order_by),
limit,
filter,
with_vector,
with_payload,
};
let idx = self.scrolls.len();
self.scrolls.push(scroll);
vec![Source::ScrollsIdx(idx)]
}
Some(ScoringQuery::Sample(SampleInternal::Random)) => {
// Everything should come from 1 scroll
let scroll = QueryScrollRequestInternal {
scroll_order: ScrollOrder::Random,
limit,
filter,
with_vector,
with_payload,
};
let idx = self.scrolls.len();
self.scrolls.push(scroll);
vec![Source::ScrollsIdx(idx)]
}
None => {
// Everything should come from 1 scroll
let scroll = QueryScrollRequestInternal {
scroll_order: ScrollOrder::ById,
limit,
filter,
with_vector,
with_payload,
};
let idx = self.scrolls.len();
self.scrolls.push(scroll);
vec![Source::ScrollsIdx(idx)]
}
};
// Root-level query without prefetches is the only case where merge is `None`
MergePlan {
sources,
rescore_params: None,
}
};
self.root_plans.push(merge_plan);
Ok(())
}
}
/// Recursively construct a merge_plan for prefetches
fn recurse_prefetches(
core_searches: &mut Vec<CoreSearchRequest>,
scrolls: &mut Vec<QueryScrollRequestInternal>,
prefetches: Vec<ShardPrefetch>,
root_offset: usize, // Offset is added to all prefetches, so we make sure we have enough
propagate_filter: &Option<Filter>, // Global filter to apply to all prefetches
// Top-level fusion requests won't be merged on shard level, so we pass these params down one level to fetch on the sources.
// Otherwise we would miss to fetch the payload and vector.
with_payload_and_vector: Option<(WithPayloadInterface, WithVector)>,
) -> CollectionResult<Vec<Source>> {
let mut sources = Vec::with_capacity(prefetches.len());
let (with_payload, with_vector) = with_payload_and_vector
.unwrap_or((WithPayloadInterface::Bool(false), WithVector::Bool(false)));
for prefetch in prefetches {
let ShardPrefetch {
prefetches,
query,
limit: prefetch_limit,
params,
filter,
score_threshold,
} = prefetch;
// Offset is replicated at each step from the root to the leaves
let limit = prefetch_limit + root_offset;
// Filters are propagated into the leaves
let filter = Filter::merge_opts(propagate_filter.clone(), filter);
let source = if !prefetches.is_empty() {
// This has nested prefetches. Recurse into them
let inner_sources = recurse_prefetches(
core_searches,
scrolls,
prefetches,
root_offset,
&filter,
None,
)?;
let rescore = query.ok_or_else(|| {
CollectionError::bad_request("cannot have prefetches without a query".to_string())
})?;
let merge_plan = MergePlan {
sources: inner_sources,
rescore_params: Some(RescoreParams {
rescore,
limit,
score_threshold,
with_vector: with_vector.clone(),
with_payload: with_payload.clone(),
params,
}),
};
Source::Prefetch(Box::new(merge_plan))
} else {
// This is a leaf prefetch. Fetch this info from the segments
match query {
Some(ScoringQuery::Vector(query_enum)) => {
let core_search = CoreSearchRequest {
query: query_enum,
filter,
params,
limit,
offset: 0,
with_vector: Some(with_vector.clone()),
with_payload: Some(with_payload.clone()),
score_threshold,
};
let idx = core_searches.len();
core_searches.push(core_search);
Source::SearchesIdx(idx)
}
Some(ScoringQuery::Fusion(_)) => {
return Err(CollectionError::bad_request(
"cannot apply Fusion without prefetches".to_string(),
))
}
Some(ScoringQuery::OrderBy(order_by)) => {
let scroll = QueryScrollRequestInternal {
scroll_order: ScrollOrder::ByField(order_by),
filter,
with_vector: with_vector.clone(),
with_payload: with_payload.clone(),
limit,
};
let idx = scrolls.len();
scrolls.push(scroll);
Source::ScrollsIdx(idx)
}
Some(ScoringQuery::Sample(SampleInternal::Random)) => {
let scroll = QueryScrollRequestInternal {
scroll_order: ScrollOrder::Random,
filter,
with_vector: with_vector.clone(),
with_payload: with_payload.clone(),
limit,
};
let idx = scrolls.len();
scrolls.push(scroll);
Source::ScrollsIdx(idx)
}
None => {
let scroll = QueryScrollRequestInternal {
scroll_order: Default::default(),
filter,
with_vector: with_vector.clone(),
with_payload: with_payload.clone(),
limit,
};
let idx = scrolls.len();
scrolls.push(scroll);
Source::ScrollsIdx(idx)
}
}
};
sources.push(source);
}
Ok(sources)
}
impl TryFrom<Vec<ShardQueryRequest>> for PlannedQuery {
type Error = CollectionError;
fn try_from(requests: Vec<ShardQueryRequest>) -> Result<Self, Self::Error> {
let mut planned_query = Self::new();
for request in requests {
planned_query.add(request)?;
}
Ok(planned_query)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use segment::data_types::vectors::{
MultiDenseVectorInternal, NamedVectorStruct, VectorInternal,
};
use segment::json_path::JsonPath;
use segment::types::{
Condition, FieldCondition, Filter, Match, SearchParams, WithPayloadInterface, WithVector,
};
use sparse::common::sparse_vector::SparseVector;
use super::*;
use crate::operations::query_enum::QueryEnum;
use crate::operations::universal_query::shard_query::FusionInternal;
#[test]
fn test_try_from_double_rescore() {
let dummy_vector = vec![1.0, 2.0, 3.0];
let filter_inner_inner = Filter::new_must_not(Condition::IsNull(
JsonPath::try_from("apples").unwrap().into(),
));
let filter_inner = Filter::new_must(Condition::Field(FieldCondition::new_match(
"has_oranges".try_into().unwrap(),
true.into(),
)));
let filter_outer =
Filter::new_must(Condition::HasId(HashSet::from([1.into(), 2.into()]).into()));
let request = ShardQueryRequest {
prefetches: vec![ShardPrefetch {
prefetches: vec![ShardPrefetch {
prefetches: Default::default(),
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector.clone()),
"byte",
),
))),
limit: 1000,
params: None,
filter: Some(filter_inner_inner.clone()),
score_threshold: None,
}],
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector.clone()),
"full",
),
))),
limit: 100,
params: None,
filter: Some(filter_inner.clone()),
score_threshold: None,
}],
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::MultiDense(MultiDenseVectorInternal::new_unchecked(vec![
dummy_vector.clone(),
])),
"multi",
),
))),
filter: Some(filter_outer.clone()),
score_threshold: None,
limit: 10,
offset: 0,
params: Some(SearchParams {
exact: true,
..Default::default()
}),
with_vector: WithVector::Bool(true),
with_payload: WithPayloadInterface::Bool(true),
};
let planned_query = PlannedQuery::try_from(vec![request]).unwrap();
assert_eq!(
planned_query.searches,
vec![CoreSearchRequest {
query: QueryEnum::Nearest(NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector.clone()),
"byte",
)),
filter: Some(
filter_outer
.merge_owned(filter_inner)
.merge_owned(filter_inner_inner)
),
params: None,
limit: 1000,
offset: 0,
with_payload: Some(WithPayloadInterface::Bool(false)),
with_vector: Some(WithVector::Bool(false)),
score_threshold: None,
}]
);
assert_eq!(
planned_query.root_plans,
vec![MergePlan {
sources: vec![Source::Prefetch(Box::from(MergePlan {
sources: vec![Source::SearchesIdx(0)],
rescore_params: Some(RescoreParams {
rescore: ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector.clone()),
"full",
)
)),
limit: 100,
score_threshold: None,
with_vector: WithVector::Bool(false),
with_payload: WithPayloadInterface::Bool(false),
params: None,
})
}))],
rescore_params: Some(RescoreParams {
rescore: ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::MultiDense(MultiDenseVectorInternal::new_unchecked(
vec![dummy_vector]
)),
"multi"
)
)),
limit: 10,
score_threshold: None,
with_vector: WithVector::Bool(true),
with_payload: WithPayloadInterface::Bool(true),
params: Some(SearchParams {
exact: true,
..Default::default()
})
})
}]
);
}
#[test]
fn test_try_from_no_prefetch() {
let dummy_vector = vec![1.0, 2.0, 3.0];
let request = ShardQueryRequest {
prefetches: vec![], // No prefetch
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector.clone()),
"full",
),
))),
filter: Some(Filter::default()),
score_threshold: Some(0.5),
limit: 10,
offset: 12,
params: Some(SearchParams::default()),
with_vector: WithVector::Bool(true),
with_payload: WithPayloadInterface::Bool(true),
};
let planned_query = PlannedQuery::try_from(vec![request]).unwrap();
assert_eq!(
planned_query.searches,
vec![CoreSearchRequest {
query: QueryEnum::Nearest(NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector),
"full",
)),
filter: Some(Filter::default()),
params: Some(SearchParams::default()),
limit: 22,
offset: 0,
with_vector: Some(WithVector::Bool(true)),
with_payload: Some(WithPayloadInterface::Bool(true)),
score_threshold: Some(0.5),
}]
);
assert_eq!(
planned_query.root_plans,
vec![MergePlan {
sources: vec![Source::SearchesIdx(0)],
rescore_params: None,
}]
);
}
#[test]
fn test_try_from_hybrid_query() {
let dummy_vector = vec![1.0, 2.0, 3.0];
let dummy_sparse = SparseVector::new(vec![100, 123, 2000], vec![0.2, 0.3, 0.4]).unwrap();
let filter_inner1 = Filter::new_must(Condition::Field(FieldCondition::new_match(
"city".try_into().unwrap(),
"Berlin".to_string().into(),
)));
let filter_inner2 = Filter::new_must(Condition::Field(FieldCondition::new_match(
"city".try_into().unwrap(),
"Munich".to_string().into(),
)));
let filter_outer = Filter::new_must(Condition::Field(FieldCondition::new_match(
"country".try_into().unwrap(),
"Germany".to_string().into(),
)));
let request = ShardQueryRequest {
prefetches: vec![
ShardPrefetch {
prefetches: Vec::new(),
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector.clone()),
"dense",
),
))),
limit: 100,
params: None,
filter: Some(filter_inner1.clone()),
score_threshold: None,
},
ShardPrefetch {
prefetches: Vec::new(),
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Sparse(dummy_sparse.clone()),
"sparse",
),
))),
limit: 100,
params: None,
filter: Some(filter_inner2.clone()),
score_threshold: None,
},
],
query: Some(ScoringQuery::Fusion(FusionInternal::Rrf)),
filter: Some(filter_outer.clone()),
score_threshold: None,
limit: 50,
offset: 0,
params: None,
with_payload: WithPayloadInterface::Bool(false),
with_vector: WithVector::Bool(true),
};
let planned_query = PlannedQuery::try_from(vec![request]).unwrap();
assert_eq!(
planned_query.searches,
vec![
CoreSearchRequest {
query: QueryEnum::Nearest(NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector),
"dense",
)),
filter: Some(filter_outer.merge(&filter_inner1)),
params: None,
limit: 100,
offset: 0,
with_payload: Some(WithPayloadInterface::Bool(false)),
with_vector: Some(WithVector::Bool(true)),
score_threshold: None,
},
CoreSearchRequest {
query: QueryEnum::Nearest(NamedVectorStruct::new_from_vector(
VectorInternal::Sparse(dummy_sparse),
"sparse",
)),
filter: Some(filter_outer.merge(&filter_inner2)),
params: None,
limit: 100,
offset: 0,
with_payload: Some(WithPayloadInterface::Bool(false)),
with_vector: Some(WithVector::Bool(true)),
score_threshold: None,
}
]
);
assert_eq!(
planned_query.root_plans,
vec![MergePlan {
sources: vec![Source::SearchesIdx(0), Source::SearchesIdx(1)],
rescore_params: None
}]
);
}
#[test]
fn test_try_from_rrf_without_source() {
let request = ShardQueryRequest {
prefetches: vec![],
query: Some(ScoringQuery::Fusion(FusionInternal::Rrf)),
filter: Some(Filter::default()),
score_threshold: None,
limit: 50,
offset: 0,
params: None,
with_vector: WithVector::Bool(true),
with_payload: WithPayloadInterface::Bool(false),
};
let planned_query = PlannedQuery::try_from(vec![request]);
assert!(planned_query.is_err())
}
#[test]
fn test_base_params_mapping_in_try_from() {
let dummy_vector = vec![1.0, 2.0, 3.0];
let dummy_params = Some(SearchParams {
indexed_only: true,
..Default::default()
});
let dummy_filter = Some(Filter::new_must(Condition::Field(
FieldCondition::new_match(
"my_key".try_into().unwrap(),
Match::new_value(segment::types::ValueVariants::String("hello".to_string())),
),
)));
let request = ShardQueryRequest {
prefetches: vec![ShardPrefetch {
prefetches: Vec::new(),
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector.clone()),
"dense",
),
))),
limit: 37,
params: dummy_params,
filter: dummy_filter.clone(),
score_threshold: Some(0.1),
}],
query: Some(ScoringQuery::Fusion(FusionInternal::Rrf)),
filter: Some(Filter::default()),
score_threshold: Some(0.666),
limit: 50,
offset: 49,
// these params will be ignored because we have a prefetch
params: Some(SearchParams {
exact: true,
..Default::default()
}),
with_payload: WithPayloadInterface::Bool(true),
with_vector: WithVector::Bool(false),
};
let planned_query = PlannedQuery::try_from(vec![request]).unwrap();
assert_eq!(
planned_query.root_plans,
vec![MergePlan {
sources: vec![Source::SearchesIdx(0)],
rescore_params: None
}]
);
assert_eq!(
planned_query.searches,
vec![CoreSearchRequest {
query: QueryEnum::Nearest(NamedVectorStruct::new_from_vector(
VectorInternal::Dense(dummy_vector),
"dense",
),),
filter: dummy_filter,
params: dummy_params,
limit: 37 + 49, // limit + offset
offset: 0,
with_payload: Some(WithPayloadInterface::Bool(true)),
with_vector: Some(WithVector::Bool(false)),
score_threshold: Some(0.1)
}]
)
}
pub fn make_prefetches_at_depth(depth: usize) -> ShardPrefetch {
// recursive helper for accumulation
pub fn make_prefetches_at_depth_acc(depth: usize, acc: ShardPrefetch) -> ShardPrefetch {
if depth == 0 {
acc
} else {
make_prefetches_at_depth_acc(
depth - 1,
ShardPrefetch {
prefetches: vec![acc],
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(vec![1.0, 2.0, 3.0]),
"dense",
),
))),
limit: 10,
params: None,
filter: None,
score_threshold: None,
},
)
}
}
// lowest prefetch
let prefetch = ShardPrefetch {
prefetches: Vec::new(),
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(vec![1.0, 2.0, 3.0]),
"dense",
),
))),
limit: 100,
params: None,
filter: None,
score_threshold: None,
};
make_prefetches_at_depth_acc(depth - 1, prefetch)
}
#[test]
fn test_detect_max_depth() {
// depth 0
let mut request = ShardQueryRequest {
prefetches: vec![],
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(vec![1.0, 2.0, 3.0]),
"dense",
),
))),
filter: None,
score_threshold: None,
limit: 10,
offset: 0,
params: None,
with_vector: WithVector::Bool(true),
with_payload: WithPayloadInterface::Bool(false),
};
assert_eq!(request.prefetches_depth(), 0);
// depth 3
request.prefetches = vec![ShardPrefetch {
prefetches: vec![ShardPrefetch {
prefetches: vec![ShardPrefetch {
prefetches: vec![],
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(vec![1.0, 2.0, 3.0]),
"dense",
),
))),
limit: 10,
params: None,
filter: None,
score_threshold: None,
}],
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(vec![1.0, 2.0, 3.0]),
"dense",
),
))),
limit: 10,
params: None,
filter: None,
score_threshold: None,
}],
query: Some(ScoringQuery::Vector(QueryEnum::Nearest(
NamedVectorStruct::new_from_vector(
VectorInternal::Dense(vec![1.0, 2.0, 3.0]),
"dense",
),
))),
limit: 10,
params: None,
filter: None,
score_threshold: None,
}];
assert_eq!(request.prefetches_depth(), 3);
// use with helper for less boilerplate
request.prefetches = vec![make_prefetches_at_depth(3)];
assert_eq!(request.prefetches_depth(), 3);
let _planned_query = PlannedQuery::try_from(vec![request.clone()]).unwrap();
request.prefetches = vec![make_prefetches_at_depth(64)];
assert_eq!(request.prefetches_depth(), 64);
let _planned_query = PlannedQuery::try_from(vec![request.clone()]).unwrap();
request.prefetches = vec![make_prefetches_at_depth(65)];
assert_eq!(request.prefetches_depth(), 65);
// assert error
let err_description = "prefetches depth 65 exceeds max depth 64".to_string();
matches!(PlannedQuery::try_from(vec![request]), Err(CollectionError::BadRequest { description}) if description == err_description);
}
fn dummy_core_prefetch(limit: usize) -> ShardPrefetch {
ShardPrefetch {
prefetches: vec![],
query: Some(nearest_query()),
filter: None,
params: None,
limit,
score_threshold: None,
}
}
fn dummy_scroll_prefetch(limit: usize) -> ShardPrefetch {
ShardPrefetch {
prefetches: vec![],
query: None,
limit,
params: None,
filter: None,
score_threshold: None,
}
}
fn nearest_query() -> ScoringQuery {
ScoringQuery::Vector(QueryEnum::Nearest(NamedVectorStruct::Default(vec![
0.1, 0.2, 0.3, 0.4,
])))
}
#[test]
fn test_from_batch_of_requests() {
let requests = vec![
// A no-prefetch core_search query
ShardQueryRequest {
prefetches: vec![],
query: Some(nearest_query()),
filter: None,
score_threshold: None,
limit: 10,
offset: 0,
params: None,
with_payload: WithPayloadInterface::Bool(false),
with_vector: WithVector::Bool(false),
},
// A no-prefetch scroll query
ShardQueryRequest {
prefetches: vec![],
query: None,
filter: None,
score_threshold: None,
limit: 20,
offset: 0,
params: None,
with_payload: WithPayloadInterface::Bool(false),
with_vector: WithVector::Bool(false),
},
// A double fusion query
ShardQueryRequest {
prefetches: vec![
ShardPrefetch {
prefetches: vec![dummy_core_prefetch(30), dummy_core_prefetch(40)],
query: Some(ScoringQuery::Fusion(FusionInternal::Rrf)),
filter: None,
params: None,
score_threshold: None,
limit: 10,
},
dummy_scroll_prefetch(50),
],
query: Some(ScoringQuery::Fusion(FusionInternal::Rrf)),
filter: None,
score_threshold: None,
limit: 10,
offset: 0,
params: None,
with_payload: WithPayloadInterface::Bool(true),
with_vector: WithVector::Bool(true),
},
];
let planned_query = PlannedQuery::try_from(requests).unwrap();
assert_eq!(planned_query.searches.len(), 3);
assert_eq!(planned_query.scrolls.len(), 2);
assert_eq!(planned_query.root_plans.len(), 3);
assert_eq!(
planned_query.root_plans,
vec![
MergePlan {
sources: vec![Source::SearchesIdx(0)],
rescore_params: None,
},
MergePlan {
sources: vec![Source::ScrollsIdx(0)],
rescore_params: None,
},
MergePlan {
sources: vec![
Source::Prefetch(Box::from(MergePlan {
sources: vec![Source::SearchesIdx(1), Source::SearchesIdx(2),],
rescore_params: Some(RescoreParams {
rescore: ScoringQuery::Fusion(FusionInternal::Rrf),
limit: 10,
score_threshold: None,
with_vector: WithVector::Bool(true),
with_payload: WithPayloadInterface::Bool(true),
params: None,
}),
})),
Source::ScrollsIdx(1),
],
rescore_params: None,
},
]
);
// assert the payload and vector settings were propagated to the other source too
assert_eq!(planned_query.scrolls[1].with_vector, WithVector::Bool(true));
assert_eq!(
planned_query.scrolls[1].with_payload,
WithPayloadInterface::Bool(true)
);
assert_eq!(planned_query.searches[0].limit, 10);
assert_eq!(planned_query.searches[1].limit, 30);
assert_eq!(planned_query.searches[2].limit, 40);
assert_eq!(planned_query.scrolls[0].limit, 20);
assert_eq!(planned_query.scrolls[1].limit, 50);
}
}
|