2019-08-08 11:55:40 +00:00
|
|
|
#![allow(clippy::new_ret_no_self)]
|
|
|
|
|
2023-07-20 23:44:47 +00:00
|
|
|
use crate::{document::Document, query::Query, to_pyerr};
|
2023-08-04 07:23:31 +00:00
|
|
|
use pyo3::{basic::CompareOp, exceptions::PyValueError, prelude::*};
|
2023-08-26 12:13:29 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
2019-08-02 11:23:10 +00:00
|
|
|
use tantivy as tv;
|
2019-12-17 22:17:44 +00:00
|
|
|
use tantivy::collector::{Count, MultiCollector, TopDocs};
|
2024-05-03 21:35:19 +00:00
|
|
|
use tantivy::TantivyDocument;
|
|
|
|
// Bring the trait into scope. This is required for the `to_named_doc` method.
|
|
|
|
// However, tantivy-py declares its own `Document` class, so we need to avoid
|
|
|
|
// introduce the `Document` trait into the namespace.
|
|
|
|
use tantivy::Document as _;
|
2019-06-04 09:09:58 +00:00
|
|
|
|
|
|
|
/// Tantivy's Searcher class
|
|
|
|
///
|
|
|
|
/// A Searcher is used to search the index given a prepared Query.
|
2024-01-21 20:16:34 +00:00
|
|
|
#[pyclass(module = "tantivy.tantivy")]
|
2019-06-04 09:09:58 +00:00
|
|
|
pub(crate) struct Searcher {
|
2023-02-14 13:20:59 +00:00
|
|
|
pub(crate) inner: tv::Searcher,
|
2019-06-04 09:09:58 +00:00
|
|
|
}
|
|
|
|
|
2023-08-26 12:13:29 +00:00
|
|
|
#[derive(Clone, Deserialize, FromPyObject, PartialEq, Serialize)]
|
2020-04-19 10:26:08 +00:00
|
|
|
enum Fruit {
|
2023-08-26 12:13:29 +00:00
|
|
|
#[pyo3(transparent)]
|
2020-04-19 10:26:08 +00:00
|
|
|
Score(f32),
|
2023-08-26 12:13:29 +00:00
|
|
|
#[pyo3(transparent)]
|
2020-04-19 10:26:08 +00:00
|
|
|
Order(u64),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Debug for Fruit {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
2023-02-14 13:20:59 +00:00
|
|
|
Fruit::Score(s) => f.write_str(&format!("{s}")),
|
|
|
|
Fruit::Order(o) => f.write_str(&format!("{o}")),
|
2020-04-19 10:26:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToPyObject for Fruit {
|
|
|
|
fn to_object(&self, py: Python) -> PyObject {
|
|
|
|
match self {
|
|
|
|
Fruit::Score(s) => s.to_object(py),
|
|
|
|
Fruit::Order(o) => o.to_object(py),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-21 20:16:34 +00:00
|
|
|
#[pyclass(frozen, module = "tantivy.tantivy")]
|
2023-09-28 08:17:15 +00:00
|
|
|
#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)]
|
|
|
|
/// Enum representing the direction in which something should be sorted.
|
|
|
|
pub(crate) enum Order {
|
|
|
|
/// Ascending. Smaller values appear first.
|
|
|
|
Asc,
|
|
|
|
|
|
|
|
/// Descending. Larger values appear first.
|
|
|
|
Desc,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<Order> for tv::Order {
|
|
|
|
fn from(order: Order) -> Self {
|
|
|
|
match order {
|
|
|
|
Order::Asc => tv::Order::Asc,
|
|
|
|
Order::Desc => tv::Order::Desc,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-21 20:16:34 +00:00
|
|
|
#[pyclass(frozen, module = "tantivy.tantivy")]
|
2023-08-26 12:13:29 +00:00
|
|
|
#[derive(Clone, Default, Deserialize, PartialEq, Serialize)]
|
2019-12-17 22:17:44 +00:00
|
|
|
/// Object holding a results successful search.
|
2019-12-17 19:50:10 +00:00
|
|
|
pub(crate) struct SearchResult {
|
2020-04-19 10:26:08 +00:00
|
|
|
hits: Vec<(Fruit, DocAddress)>,
|
2019-12-17 22:17:44 +00:00
|
|
|
#[pyo3(get)]
|
|
|
|
/// How many documents matched the query. Only available if `count` was set
|
|
|
|
/// to true during the search.
|
|
|
|
count: Option<usize>,
|
|
|
|
}
|
|
|
|
|
2022-04-15 03:50:37 +00:00
|
|
|
#[pymethods]
|
|
|
|
impl SearchResult {
|
2023-08-26 12:13:29 +00:00
|
|
|
#[new]
|
|
|
|
fn new(
|
|
|
|
py: Python,
|
|
|
|
hits: Vec<(PyObject, DocAddress)>,
|
|
|
|
count: Option<usize>,
|
|
|
|
) -> PyResult<Self> {
|
|
|
|
let hits = hits
|
|
|
|
.iter()
|
|
|
|
.map(|(f, d)| Ok((f.extract(py)?, d.clone())))
|
|
|
|
.collect::<PyResult<Vec<_>>>()?;
|
|
|
|
Ok(Self { hits, count })
|
|
|
|
}
|
|
|
|
|
2020-04-19 10:26:08 +00:00
|
|
|
fn __repr__(&self) -> PyResult<String> {
|
|
|
|
if let Some(count) = self.count {
|
|
|
|
Ok(format!(
|
|
|
|
"SearchResult(hits: {:?}, count: {})",
|
|
|
|
self.hits, count
|
|
|
|
))
|
|
|
|
} else {
|
|
|
|
Ok(format!("SearchResult(hits: {:?})", self.hits))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-04 07:23:31 +00:00
|
|
|
fn __richcmp__(
|
|
|
|
&self,
|
|
|
|
other: &Self,
|
|
|
|
op: CompareOp,
|
|
|
|
py: Python<'_>,
|
|
|
|
) -> PyObject {
|
|
|
|
match op {
|
|
|
|
CompareOp::Eq => (self == other).into_py(py),
|
|
|
|
CompareOp::Ne => (self != other).into_py(py),
|
|
|
|
_ => py.NotImplemented(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-26 12:13:29 +00:00
|
|
|
fn __getnewargs__(
|
|
|
|
&self,
|
|
|
|
py: Python,
|
|
|
|
) -> PyResult<(Vec<(PyObject, DocAddress)>, Option<usize>)> {
|
|
|
|
Ok((self.hits(py)?, self.count))
|
|
|
|
}
|
|
|
|
|
2019-12-17 22:17:44 +00:00
|
|
|
#[getter]
|
|
|
|
/// The list of tuples that contains the scores and DocAddress of the
|
|
|
|
/// search results.
|
|
|
|
fn hits(&self, py: Python) -> PyResult<Vec<(PyObject, DocAddress)>> {
|
|
|
|
let ret: Vec<(PyObject, DocAddress)> = self
|
|
|
|
.hits
|
|
|
|
.iter()
|
2020-04-19 10:26:08 +00:00
|
|
|
.map(|(result, address)| (result.to_object(py), address.clone()))
|
2019-12-17 22:17:44 +00:00
|
|
|
.collect();
|
|
|
|
Ok(ret)
|
|
|
|
}
|
2019-12-17 19:50:10 +00:00
|
|
|
}
|
|
|
|
|
2019-06-04 09:09:58 +00:00
|
|
|
#[pymethods]
|
|
|
|
impl Searcher {
|
|
|
|
/// Search the index with the given query and collect results.
|
|
|
|
///
|
|
|
|
/// Args:
|
|
|
|
/// query (Query): The query that will be used for the search.
|
2019-12-17 22:17:44 +00:00
|
|
|
/// limit (int, optional): The maximum number of search results to
|
|
|
|
/// return. Defaults to 10.
|
|
|
|
/// count (bool, optional): Should the number of documents that match
|
2020-04-19 10:26:08 +00:00
|
|
|
/// the query be returned as well. Defaults to true.
|
|
|
|
/// order_by_field (Field, optional): A schema field that the results
|
|
|
|
/// should be ordered by. The field must be declared as a fast field
|
|
|
|
/// when building the schema. Note, this only works for unsigned
|
|
|
|
/// fields.
|
2020-09-06 10:26:17 +00:00
|
|
|
/// offset (Field, optional): The offset from which the results have
|
2020-09-06 10:07:05 +00:00
|
|
|
/// to be returned.
|
2023-09-28 08:17:15 +00:00
|
|
|
/// order (Order, optional): The order in which the results
|
|
|
|
/// should be sorted. If not specified, defaults to descending.
|
2019-06-04 09:09:58 +00:00
|
|
|
///
|
2019-12-17 22:17:44 +00:00
|
|
|
/// Returns `SearchResult` object.
|
2019-06-04 09:09:58 +00:00
|
|
|
///
|
|
|
|
/// Raises a ValueError if there was an error with the search.
|
2023-09-28 08:17:15 +00:00
|
|
|
#[pyo3(signature = (query, limit = 10, count = true, order_by_field = None, offset = 0, order = Order::Desc))]
|
2024-05-03 20:15:21 +00:00
|
|
|
#[allow(clippy::too_many_arguments)]
|
2019-06-04 09:09:58 +00:00
|
|
|
fn search(
|
|
|
|
&self,
|
2023-09-11 15:58:17 +00:00
|
|
|
py: Python,
|
2019-06-04 09:09:58 +00:00
|
|
|
query: &Query,
|
2019-10-01 18:05:38 +00:00
|
|
|
limit: usize,
|
2019-12-17 19:50:10 +00:00
|
|
|
count: bool,
|
2020-04-19 10:26:08 +00:00
|
|
|
order_by_field: Option<&str>,
|
2020-09-06 10:26:17 +00:00
|
|
|
offset: usize,
|
2023-09-28 08:17:15 +00:00
|
|
|
order: Order,
|
2019-12-17 19:50:10 +00:00
|
|
|
) -> PyResult<SearchResult> {
|
2023-09-11 15:58:17 +00:00
|
|
|
py.allow_threads(move || {
|
|
|
|
let mut multicollector = MultiCollector::new();
|
2019-12-17 19:50:10 +00:00
|
|
|
|
2023-09-11 15:58:17 +00:00
|
|
|
let count_handle = if count {
|
|
|
|
Some(multicollector.add_collector(Count))
|
2020-04-19 10:26:08 +00:00
|
|
|
} else {
|
2023-09-11 15:58:17 +00:00
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
let (mut multifruit, hits) = {
|
|
|
|
if let Some(order_by) = order_by_field {
|
|
|
|
let collector = TopDocs::with_limit(limit)
|
|
|
|
.and_offset(offset)
|
2023-09-28 08:17:15 +00:00
|
|
|
.order_by_fast_field(order_by, order.into());
|
2023-09-11 15:58:17 +00:00
|
|
|
let top_docs_handle =
|
|
|
|
multicollector.add_collector(collector);
|
|
|
|
let ret = self.inner.search(query.get(), &multicollector);
|
|
|
|
|
|
|
|
match ret {
|
|
|
|
Ok(mut r) => {
|
|
|
|
let top_docs = top_docs_handle.extract(&mut r);
|
|
|
|
let result: Vec<(Fruit, DocAddress)> = top_docs
|
|
|
|
.iter()
|
|
|
|
.map(|(f, d)| {
|
|
|
|
(Fruit::Order(*f), DocAddress::from(d))
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
(r, result)
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
return Err(PyValueError::new_err(e.to_string()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let collector =
|
|
|
|
TopDocs::with_limit(limit).and_offset(offset);
|
|
|
|
let top_docs_handle =
|
|
|
|
multicollector.add_collector(collector);
|
|
|
|
let ret = self.inner.search(query.get(), &multicollector);
|
|
|
|
|
|
|
|
match ret {
|
|
|
|
Ok(mut r) => {
|
|
|
|
let top_docs = top_docs_handle.extract(&mut r);
|
|
|
|
let result: Vec<(Fruit, DocAddress)> = top_docs
|
|
|
|
.iter()
|
|
|
|
.map(|(f, d)| {
|
|
|
|
(Fruit::Score(*f), DocAddress::from(d))
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
(r, result)
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
return Err(PyValueError::new_err(e.to_string()))
|
|
|
|
}
|
2020-04-19 10:26:08 +00:00
|
|
|
}
|
2019-12-17 19:50:10 +00:00
|
|
|
}
|
2023-09-11 15:58:17 +00:00
|
|
|
};
|
2019-12-17 19:50:10 +00:00
|
|
|
|
2023-09-11 15:58:17 +00:00
|
|
|
let count = count_handle.map(|h| h.extract(&mut multifruit));
|
2019-10-01 18:05:38 +00:00
|
|
|
|
2023-09-11 15:58:17 +00:00
|
|
|
Ok(SearchResult { hits, count })
|
|
|
|
})
|
2019-06-04 09:09:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the overall number of documents in the index.
|
|
|
|
#[getter]
|
|
|
|
fn num_docs(&self) -> u64 {
|
|
|
|
self.inner.num_docs()
|
|
|
|
}
|
|
|
|
|
2023-07-22 19:57:30 +00:00
|
|
|
/// Returns the number of segments in the index.
|
|
|
|
#[getter]
|
|
|
|
fn num_segments(&self) -> usize {
|
|
|
|
self.inner.segment_readers().len()
|
|
|
|
}
|
|
|
|
|
2019-06-04 09:09:58 +00:00
|
|
|
/// Fetches a document from Tantivy's store given a DocAddress.
|
|
|
|
///
|
|
|
|
/// Args:
|
|
|
|
/// doc_address (DocAddress): The DocAddress that is associated with
|
|
|
|
/// the document that we wish to fetch.
|
|
|
|
///
|
|
|
|
/// Returns the Document, raises ValueError if the document can't be found.
|
|
|
|
fn doc(&self, doc_address: &DocAddress) -> PyResult<Document> {
|
2024-05-03 21:35:19 +00:00
|
|
|
let doc: TantivyDocument =
|
|
|
|
self.inner.doc(doc_address.into()).map_err(to_pyerr)?;
|
|
|
|
let named_doc = doc.to_named_doc(self.inner.schema());
|
|
|
|
Ok(crate::document::Document {
|
2019-08-02 11:23:10 +00:00
|
|
|
field_values: named_doc.0,
|
|
|
|
})
|
2019-06-04 09:09:58 +00:00
|
|
|
}
|
2022-04-15 03:50:37 +00:00
|
|
|
|
|
|
|
fn __repr__(&self) -> PyResult<String> {
|
|
|
|
Ok(format!(
|
|
|
|
"Searcher(num_docs={}, num_segments={})",
|
|
|
|
self.inner.num_docs(),
|
|
|
|
self.inner.segment_readers().len()
|
|
|
|
))
|
|
|
|
}
|
2019-06-04 09:09:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// DocAddress contains all the necessary information to identify a document
|
|
|
|
/// given a Searcher object.
|
|
|
|
///
|
|
|
|
/// It consists in an id identifying its segment, and its segment-local DocId.
|
|
|
|
/// The id used for the segment is actually an ordinal in the list of segment
|
|
|
|
/// hold by a Searcher.
|
2024-01-21 20:16:34 +00:00
|
|
|
#[pyclass(frozen, module = "tantivy.tantivy")]
|
2023-08-26 12:13:29 +00:00
|
|
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
2019-06-04 09:09:58 +00:00
|
|
|
pub(crate) struct DocAddress {
|
2022-01-03 13:51:13 +00:00
|
|
|
pub(crate) segment_ord: tv::SegmentOrdinal,
|
2019-06-04 09:09:58 +00:00
|
|
|
pub(crate) doc: tv::DocId,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pymethods]
|
|
|
|
impl DocAddress {
|
2023-08-26 12:13:29 +00:00
|
|
|
#[new]
|
|
|
|
fn new(segment_ord: tv::SegmentOrdinal, doc: tv::DocId) -> Self {
|
|
|
|
DocAddress { segment_ord, doc }
|
|
|
|
}
|
|
|
|
|
2019-06-04 09:09:58 +00:00
|
|
|
/// The segment ordinal is an id identifying the segment hosting the
|
|
|
|
/// document. It is only meaningful, in the context of a searcher.
|
|
|
|
#[getter]
|
|
|
|
fn segment_ord(&self) -> u32 {
|
|
|
|
self.segment_ord
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The segment local DocId
|
|
|
|
#[getter]
|
|
|
|
fn doc(&self) -> u32 {
|
|
|
|
self.doc
|
|
|
|
}
|
2023-08-04 07:23:31 +00:00
|
|
|
|
|
|
|
fn __richcmp__(
|
|
|
|
&self,
|
|
|
|
other: &Self,
|
|
|
|
op: CompareOp,
|
|
|
|
py: Python<'_>,
|
|
|
|
) -> PyObject {
|
|
|
|
match op {
|
|
|
|
CompareOp::Eq => (self == other).into_py(py),
|
|
|
|
CompareOp::Ne => (self != other).into_py(py),
|
|
|
|
_ => py.NotImplemented(),
|
|
|
|
}
|
|
|
|
}
|
2023-08-26 12:13:29 +00:00
|
|
|
|
|
|
|
fn __getnewargs__(&self) -> PyResult<(tv::SegmentOrdinal, tv::DocId)> {
|
|
|
|
Ok((self.segment_ord, self.doc))
|
|
|
|
}
|
2019-06-04 09:09:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl From<&tv::DocAddress> for DocAddress {
|
|
|
|
fn from(doc_address: &tv::DocAddress) -> Self {
|
|
|
|
DocAddress {
|
2022-01-03 13:51:13 +00:00
|
|
|
segment_ord: doc_address.segment_ord,
|
|
|
|
doc: doc_address.doc_id,
|
2019-06-04 09:09:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-14 13:20:59 +00:00
|
|
|
impl From<&DocAddress> for tv::DocAddress {
|
|
|
|
fn from(val: &DocAddress) -> Self {
|
2022-01-03 13:51:13 +00:00
|
|
|
tv::DocAddress {
|
2023-02-14 13:20:59 +00:00
|
|
|
segment_ord: val.segment_ord(),
|
|
|
|
doc_id: val.doc(),
|
2022-01-03 13:51:13 +00:00
|
|
|
}
|
2019-06-04 09:09:58 +00:00
|
|
|
}
|
|
|
|
}
|