Skip to main content

iqdb_types/
hit.rs

1//! A single search result.
2
3use crate::id::VectorId;
4use crate::metadata::Metadata;
5
6/// One result of a similarity search: a matched record and its distance.
7///
8/// `id` identifies the matched vector, `distance` is its distance from the
9/// query under the search's metric (smaller is nearer), and `metadata` is the
10/// record's metadata when the engine was asked to return it. Build a bare hit
11/// with [`Hit::new`] and attach metadata by setting the field.
12///
13/// # Examples
14///
15/// ```
16/// use iqdb_types::{Hit, VectorId};
17///
18/// let hit = Hit::new(VectorId::from(42u64), 0.125);
19/// assert_eq!(hit.id, VectorId::U64(42));
20/// assert_eq!(hit.distance, 0.125);
21/// assert!(hit.metadata.is_none());
22/// ```
23#[derive(Debug, Clone, PartialEq)]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25pub struct Hit {
26    /// The identifier of the matched vector.
27    pub id: VectorId,
28    /// The distance from the query under the search's metric (smaller is
29    /// nearer).
30    pub distance: f32,
31    /// The record's metadata, when the search was asked to return it.
32    pub metadata: Option<Metadata>,
33}
34
35impl Hit {
36    /// Creates a hit for `id` at `distance`, with no metadata attached.
37    ///
38    /// # Examples
39    ///
40    /// ```
41    /// use iqdb_types::{Hit, VectorId};
42    ///
43    /// let hit = Hit::new(VectorId::from(1u64), 2.5);
44    /// assert_eq!(hit.distance, 2.5);
45    /// assert!(hit.metadata.is_none());
46    /// ```
47    #[inline]
48    #[must_use]
49    pub fn new(id: VectorId, distance: f32) -> Self {
50        Self {
51            id,
52            distance,
53            metadata: None,
54        }
55    }
56}