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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::core::index::index_reader_context::IndexReaderContext;
use crate::core::search::index_searcher::IndexSearcher;
use crate::core::search::similarities_impl::similarities::Similarity;
use crate::core::search::sort_field::{SortField, SortFiledBase};
use crate::core::search::sort_field_enum::SortFieldEnum;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use std::fmt;
use std::fmt::Display;
use std::hash::Hash;
/// Encapsulates sort criteria for returned hits.
///
/// A [`Sort`] can be created with no fields, yielding a value
/// that instructs searches to return hits sorted by relevance; or it can be
/// created with one or more [`SortField`]s.
///
/// See also: [`SortField`].
#[derive(Clone)]
pub struct Sort {
pub(crate) fields: Vec<SortFieldEnum>,
}
impl Sort {
/// Represents sorting by index order.
pub fn get_index_order() -> Result<Self> {
let sort_field = SortFieldEnum::Sorter(SortField::get_field_doc()?);
Self::with_fields(vec![sort_field])
}
/// Represents sorting by computed relevance. Using this sort criteria returns the same results as
/// calling [`IndexSearcher::search(Query, i32)`](crate::core::search::index_searcher::IndexSearcher::search) without a sort criteria,
/// only with slightly more overhead.
pub fn get_relevance() -> Result<Self> {
Self::new()
}
/// Returns true if the relevance score is needed to sort documents.
pub fn needs_scores(&self) -> bool {
for sort_field in &self.fields {
if sort_field.needs_scores() {
return true;
}
}
false
}
}
impl Sort {
/// Sorts by computed relevance.
///
/// This is the same sort criteria as calling [`IndexSearcher::search`](crate::core::search::index_searcher::IndexSearcher::search)
/// without a sort criteria, only with slightly more overhead.
pub fn new() -> Result<Self> {
let sort_field = SortFieldEnum::Sorter(SortField::get_field_score()?);
Self::with_fields(vec![sort_field])
}
/// Sets the sort to the given criteria in succession.
///
/// The first [`SortField`] is checked first, but if it produces a tie, then
/// the second [`SortField`] is used to break the tie, and so on. Finally,
/// if there is still a tie after all [`SortField`]s are checked, the
/// internal Lucene doc ID is used to break it.
///
/// # Arguments
/// - `fields`: Sort criteria in priority order, from an array, vector or iterator.
/// Use [`sort_fields!`](crate::sort_fields) to combine different sort field types.
///
/// # Errors
/// Returns an error if the provided collection is empty.
pub fn with_fields<T, I>(fields: I) -> Result<Self>
where
T: Into<SortFieldEnum>,
I: IntoIterator<Item = T>,
{
let fields: Vec<SortFieldEnum> = fields.into_iter().map(Into::into).collect();
if fields.is_empty() {
Err(LuceneError::illegal_argument(
"There must be at least 1 sort field".to_string(),
))
} else {
Ok(Self { fields })
}
}
/// Representation of the sort criteria.
///
/// # Returns
/// Array (Vec) of [`SortField`] objects used in this sort criteria.
pub fn get_sort(&self) -> &[SortFieldEnum] {
&self.fields
}
pub fn take_sort(&mut self) -> Vec<SortFieldEnum> {
std::mem::take(&mut self.fields)
}
/// Rewrites the sort fields in this sort, returning a new sort if any field
/// changes during rewriting.
pub fn rewrite<IRC, SIM>(&self, searcher: &IndexSearcher<IRC, SIM>) -> Result<Option<Self>>
where
SIM: Similarity,
IRC: IndexReaderContext,
IndexSearcher<IRC, SIM>: Sync,
{
let mut rewritten_fields = None;
for (i, field) in self.fields.iter().enumerate() {
if let Some(rewritten_field) = field.rewrite(searcher)? {
let fields = rewritten_fields.get_or_insert_with(|| {
let mut fields = Vec::with_capacity(self.fields.len());
fields.extend_from_slice(&self.fields[..i]);
fields
});
fields.push(rewritten_field);
} else if let Some(fields) = &mut rewritten_fields {
fields.push(field.clone());
}
}
if let Some(rewritten_fields) = rewritten_fields {
Ok(Some(Self::with_fields(rewritten_fields)?))
} else {
Ok(None)
}
}
}
impl Display for Sort {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (index, field) in self.fields.iter().enumerate() {
if index != 0 {
f.write_str(",")?;
}
write!(f, "{field}")?;
}
Ok(())
}
}
impl PartialEq for Sort {
fn eq(&self, other: &Self) -> bool {
self.fields == other.fields
}
}
impl Eq for Sort {}
impl Hash for Sort {
fn hash<H>(&self, state: &mut H)
where
H: std::hash::Hasher,
{
self.fields.hash(state);
}
}