caio.co/de/cantine


Expose CustomScoreTopCollector via `with_custom_scorer` by Caio 5 years ago (log)

Blob tique/src/conditional_collector/custom_score.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
use std::marker::PhantomData;

use tantivy::{
    collector::{Collector, CustomScorer, CustomSegmentScorer, SegmentCollector},
    DocId, Result, Score, SegmentLocalId, SegmentReader,
};

use super::{
    top_collector::TopSegmentCollector,
    topk::{TopK, TopKProvider},
    traits::{CheckCondition, ConditionForSegment},
    CollectionResult,
};

pub(crate) struct CustomScoreTopCollector<T, P, C, S>
where
    T: PartialOrd,
    P: TopKProvider<T, DocId>,
    C: ConditionForSegment<T>,
{
    limit: usize,
    scorer_for_segment: S,
    condition_for_segment: C,
    _score: PhantomData<T>,
    _provider: PhantomData<P>,
}

impl<T, P, C, S> CustomScoreTopCollector<T, P, C, S>
where
    T: PartialOrd,
    P: TopKProvider<T, DocId>,
    C: ConditionForSegment<T>,
{
    pub fn new(limit: usize, condition_for_segment: C, scorer_for_segment: S) -> Self {
        Self {
            limit,
            scorer_for_segment,
            condition_for_segment,
            _score: PhantomData,
            _provider: PhantomData,
        }
    }
}

impl<T, P, C, S> Collector for CustomScoreTopCollector<T, P, C, S>
where
    T: 'static + PartialOrd + Copy + Send + Sync,
    P: 'static + Send + Sync + TopKProvider<T, DocId>,
    C: Sync + ConditionForSegment<T>,
    S: CustomScorer<T>,
{
    type Fruit = CollectionResult<T>;
    type Child = CustomScoreTopSegmentCollector<T, C::Type, S::Child, P::Child>;

    fn requires_scoring(&self) -> bool {
        false
    }

    fn merge_fruits(&self, children: Vec<Self::Fruit>) -> Result<Self::Fruit> {
        Ok(P::merge_many(self.limit, children))
    }

    fn for_segment(
        &self,
        segment_id: SegmentLocalId,
        reader: &SegmentReader,
    ) -> Result<Self::Child> {
        let scorer = self.scorer_for_segment.segment_scorer(reader)?;
        Ok(CustomScoreTopSegmentCollector::new(
            segment_id,
            P::new_topk(self.limit),
            scorer,
            self.condition_for_segment.for_segment(reader),
        ))
    }
}

pub struct CustomScoreTopSegmentCollector<T, C, S, K>
where
    C: CheckCondition<T>,
    K: TopK<T, DocId>,
{
    scorer: S,
    collector: TopSegmentCollector<T, K, C>,
}

impl<T, C, S, K> CustomScoreTopSegmentCollector<T, C, S, K>
where
    T: Copy,
    C: CheckCondition<T>,
    K: TopK<T, DocId>,
{
    pub fn new(segment_id: SegmentLocalId, topk: K, scorer: S, condition: C) -> Self {
        Self {
            scorer,
            collector: TopSegmentCollector::new(segment_id, topk, condition),
        }
    }
}

impl<T, C, S, K> SegmentCollector for CustomScoreTopSegmentCollector<T, C, S, K>
where
    T: 'static + PartialOrd + Copy + Send + Sync,
    K: 'static + TopK<T, DocId>,
    C: CheckCondition<T>,
    S: CustomSegmentScorer<T>,
{
    type Fruit = CollectionResult<T>;

    fn collect(&mut self, doc: DocId, _: Score) {
        let score = self.scorer.score(doc);
        self.collector.collect(doc, score);
    }

    fn harvest(self) -> Self::Fruit {
        self.collector.into_unsorted_collection_result()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::conditional_collector::{topk::AscendingTopK, Descending};

    use tantivy::{query::AllQuery, schema::SchemaBuilder, Document, Index};

    #[test]
    fn custom_segment_scorer_gets_called() {
        let mut collector = CustomScoreTopSegmentCollector::new(
            0,
            AscendingTopK::new(1),
            // Use the doc_id as the score
            |doc_id| doc_id,
            true,
        );

        // So that whatever we provide as a score
        collector.collect(1, 42.0);
        let res = collector.harvest();
        assert_eq!(1, res.total);

        let got = &res.items[0];
        // Is disregarded and doc_id is used instead
        assert_eq!((got.1).1, got.0)
    }

    #[test]
    fn custom_top_scorer_integration() -> Result<()> {
        let builder = SchemaBuilder::new();
        let index = Index::create_in_ram(builder.build());

        let mut writer = index.writer_with_num_threads(1, 3_000_000)?;

        // We add 100 documents to our index
        for _ in 0..100 {
            writer.add_document(Document::new());
        }

        writer.commit()?;

        let reader = index.reader()?;
        let searcher = reader.searcher();

        let colletor =
            CustomScoreTopCollector::<_, Descending, _, _>::new(2, true, |_: &SegmentReader| {
                |doc_id: DocId| u64::from(doc_id * 10)
            });

        let result = searcher.search(&AllQuery, &colletor)?;

        assert_eq!(100, result.total);
        assert_eq!(2, result.items.len());

        // So we expect that the highest score is 990
        assert_eq!(result.items[0].0, 990);
        assert_eq!(result.items[1].0, 980);

        Ok(())
    }
}