web search done right
re-use u64 column fields in webgraph queries as a significant fraction of the time was spend opening the columns
Mikkel Denkerc9a1d6f1a46d
diff --git a/crates/core/examples/search_preindexed.rs b/crates/core/examples/search_preindexed.rsindex be538ed1..4d80fd4c 100644--- a/crates/core/examples/search_preindexed.rs+++ b/crates/core/examples/search_preindexed.rs@@ -69,14 +69,12 @@ pub async fn main() {let searcher = stract::searcher::LocalSearchClient::from(searcher);+ let webgraph = Webgraph::open("data/webgraph", 0u64.into()).unwrap();+let searcher: ApiSearcher<LocalSearchClient, LiveSearcher, Webgraph> =- ApiSearcher::new(searcher, bangs, config);+ ApiSearcher::new(searcher, bangs, config).with_webgraph(webgraph);for query in queries {- let mut query = query;- query.push(' ');- let query = query.repeat(32);-let mut desc = "search '".to_string();desc.push_str(&query);desc.push('\'');@@ -87,7 +85,7 @@ pub async fn main() {.search(&SearchQuery {query: query.to_string(),host_rankings: Some(HostRankings {- liked: vec![],+ liked: vec!["en.wikipedia.org".to_string()],disliked: vec![],blocked: vec![],}),diff --git a/crates/core/src/webgraph/mod.rs b/crates/core/src/webgraph/mod.rsindex 38963c93..56ac5b1b 100644--- a/crates/core/src/webgraph/mod.rs+++ b/crates/core/src/webgraph/mod.rs@@ -44,6 +44,7 @@ mod schema;mod searcher;mod shortest_path;mod store;+mod warmed_column_fields;#[cfg(test)]pub mod tests;diff --git a/crates/core/src/webgraph/query/backlink.rs b/crates/core/src/webgraph/query/backlink.rsindex f7007cf6..2ed132bc 100644--- a/crates/core/src/webgraph/query/backlink.rs+++ b/crates/core/src/webgraph/query/backlink.rs@@ -49,14 +49,14 @@ pub fn fetch_small_edges<F: Field>(for doc in doc_ids {if Some(doc.segment_ord) != prev_segment_id {prev_segment_id = Some(doc.segment_ord);- let segment_reader = searcher.tantivy_searcher().segment_reader(doc.segment_ord);- field_column = Some(- segment_reader- .column_fields()- .u64(node_id_field.name())- .unwrap(),+ let segment_column_fields = searcher.warmed_column_fields().segment(+ &searcher+ .tantivy_searcher()+ .segment_reader(doc.segment_ord)+ .segment_id(),);- rel_flags_column = Some(segment_reader.column_fields().u64(RelFlags.name()).unwrap());+ field_column = Some(segment_column_fields.u64(node_id_field).unwrap());+ rel_flags_column = Some(segment_column_fields.u64(RelFlags).unwrap());}let Some(id) = field_column.as_ref().unwrap().first(doc.doc_id) else {@@ -112,7 +112,7 @@ impl Query for BacklinksQuery {type IntermediateOutput = Vec<(f32, SmallEdge)>;type Output = Vec<SmallEdge>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, _: &Searcher) -> Self::TantivyQuery {match self.limit {EdgeLimit::Unlimited => Box::new(LinksQuery::new(self.node, ToId)),EdgeLimit::Limit(limit) | EdgeLimit::LimitAndOffset { limit, .. } => Box::new(@@ -192,12 +192,22 @@ impl Query for HostBacklinksQuery {type IntermediateOutput = Vec<(f32, SmallEdge)>;type Output = Vec<SmallEdge>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, searcher: &Searcher) -> Self::TantivyQuery {match self.limit {- EdgeLimit::Unlimited => Box::new(HostLinksQuery::new(self.node, ToHostId, FromHostId)),+ EdgeLimit::Unlimited => Box::new(HostLinksQuery::new(+ self.node,+ ToHostId,+ FromHostId,+ searcher.warmed_column_fields().clone(),+ )),EdgeLimit::Limit(limit) | EdgeLimit::LimitAndOffset { limit, .. } => {Box::new(ShortCircuitQuery::new(- Box::new(HostLinksQuery::new(self.node, ToHostId, FromHostId)),+ Box::new(HostLinksQuery::new(+ self.node,+ ToHostId,+ FromHostId,+ searcher.warmed_column_fields().clone(),+ )),limit as u64,))}@@ -277,7 +287,7 @@ impl Query for FullBacklinksQuery {type IntermediateOutput = Vec<(f32, Edge)>;type Output = Vec<Edge>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, _: &Searcher) -> Self::TantivyQuery {match self.limit {EdgeLimit::Unlimited => Box::new(LinksQuery::new(self.node.id(), ToId)),EdgeLimit::Limit(limit) | EdgeLimit::LimitAndOffset { limit, .. } => {@@ -355,12 +365,13 @@ impl Query for FullHostBacklinksQuery {type IntermediateOutput = Vec<(f32, Edge)>;type Output = Vec<Edge>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, searcher: &Searcher) -> Self::TantivyQuery {match self.limit {EdgeLimit::Unlimited => Box::new(HostLinksQuery::new(self.node.clone().into_host().id(),ToHostId,FromHostId,+ searcher.warmed_column_fields().clone(),)),EdgeLimit::Limit(limit) | EdgeLimit::LimitAndOffset { limit, .. } => {Box::new(ShortCircuitQuery::new(@@ -368,6 +379,7 @@ impl Query for FullHostBacklinksQuery {self.node.clone().into_host().id(),ToHostId,FromHostId,+ searcher.warmed_column_fields().clone(),)),limit as u64,))@@ -449,7 +461,7 @@ impl Query for BacklinksWithLabelsQuery {type IntermediateOutput = Vec<(f32, SmallEdgeWithLabel)>;type Output = Vec<SmallEdgeWithLabel>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, _: &Searcher) -> Self::TantivyQuery {Box::new(LinksQuery::new(self.node, ToId))}diff --git a/crates/core/src/webgraph/query/degree.rs b/crates/core/src/webgraph/query/degree.rsindex 7950bdda..7f3d1f7a 100644--- a/crates/core/src/webgraph/query/degree.rs+++ b/crates/core/src/webgraph/query/degree.rs@@ -41,7 +41,7 @@ impl Query for InDegreeQuery {type IntermediateOutput = FxHashMap<ShardId, u64>;type Output = u64;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, _: &Searcher) -> Self::TantivyQuery {raw::DummyQuery}diff --git a/crates/core/src/webgraph/query/forwardlink.rs b/crates/core/src/webgraph/query/forwardlink.rsindex accf96f2..689805c9 100644--- a/crates/core/src/webgraph/query/forwardlink.rs+++ b/crates/core/src/webgraph/query/forwardlink.rs@@ -61,7 +61,7 @@ impl Query for ForwardlinksQuery {type IntermediateOutput = Vec<(f32, SmallEdge)>;type Output = Vec<SmallEdge>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, _: &Searcher) -> Self::TantivyQuery {match self.limit {EdgeLimit::Unlimited => Box::new(LinksQuery::new(self.node, FromId)),EdgeLimit::Limit(limit) | EdgeLimit::LimitAndOffset { limit, .. } => Box::new(@@ -143,12 +143,22 @@ impl Query for HostForwardlinksQuery {type IntermediateOutput = Vec<(f32, SmallEdge)>;type Output = Vec<SmallEdge>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, searcher: &Searcher) -> Self::TantivyQuery {match self.limit {- EdgeLimit::Unlimited => Box::new(HostLinksQuery::new(self.node, FromHostId, ToHostId)),+ EdgeLimit::Unlimited => Box::new(HostLinksQuery::new(+ self.node,+ FromHostId,+ ToHostId,+ searcher.warmed_column_fields().clone(),+ )),EdgeLimit::Limit(limit) | EdgeLimit::LimitAndOffset { limit, .. } => {Box::new(ShortCircuitQuery::new(- Box::new(HostLinksQuery::new(self.node, FromHostId, ToHostId)),+ Box::new(HostLinksQuery::new(+ self.node,+ FromHostId,+ ToHostId,+ searcher.warmed_column_fields().clone(),+ )),limit as u64,))}@@ -228,7 +238,7 @@ impl Query for FullForwardlinksQuery {type IntermediateOutput = Vec<(f32, Edge)>;type Output = Vec<Edge>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, _: &Searcher) -> Self::TantivyQuery {match self.limit {EdgeLimit::Unlimited => Box::new(LinksQuery::new(self.node.id(), FromId)),EdgeLimit::Limit(limit) | EdgeLimit::LimitAndOffset { limit, .. } => {@@ -306,12 +316,13 @@ impl Query for FullHostForwardlinksQuery {type IntermediateOutput = Vec<(f32, Edge)>;type Output = Vec<Edge>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, searcher: &Searcher) -> Self::TantivyQuery {match self.limit {EdgeLimit::Unlimited => Box::new(HostLinksQuery::new(self.node.clone().into_host().id(),FromHostId,ToHostId,+ searcher.warmed_column_fields().clone(),)),EdgeLimit::Limit(limit) | EdgeLimit::LimitAndOffset { limit, .. } => {Box::new(ShortCircuitQuery::new(@@ -319,6 +330,7 @@ impl Query for FullHostForwardlinksQuery {self.node.clone().into_host().id(),FromHostId,ToHostId,+ searcher.warmed_column_fields().clone(),)),limit as u64,))diff --git a/crates/core/src/webgraph/query/id2node.rs b/crates/core/src/webgraph/query/id2node.rsindex ffac2876..58d95910 100644--- a/crates/core/src/webgraph/query/id2node.rs+++ b/crates/core/src/webgraph/query/id2node.rs@@ -34,7 +34,7 @@ impl Query for Id2NodeQuery {type IntermediateOutput = Option<Node>;type Output = Option<Node>;- fn tantivy_query(&self) -> Self::TantivyQuery {+ fn tantivy_query(&self, _: &Searcher) -> Self::TantivyQuery {match self {Self::Page(node) => raw::Id2NodeQuery::new(*node, vec![ToId.into(), FromId.into()]),Self::Host(node) => {diff --git a/crates/core/src/webgraph/query/mod.rs b/crates/core/src/webgraph/query/mod.rsindex 6b70cc47..a826dd7b 100644--- a/crates/core/src/webgraph/query/mod.rs+++ b/crates/core/src/webgraph/query/mod.rs@@ -38,7 +38,7 @@ pub trait Query: Send + Sync + bincode::Encode + bincode::Decode + Clone {type IntermediateOutput;type Output;- fn tantivy_query(&self) -> Self::TantivyQuery;+ fn tantivy_query(&self, searcher: &Searcher) -> Self::TantivyQuery;fn collector(&self, shard_id: ShardId) -> Self::Collector;fn remote_collector(&self) -> Self::Collector;diff --git a/crates/core/src/webgraph/query/raw/host_links.rs b/crates/core/src/webgraph/query/raw/host_links.rsindex c50af494..6e3f1cb3 100644--- a/crates/core/src/webgraph/query/raw/host_links.rs+++ b/crates/core/src/webgraph/query/raw/host_links.rs@@ -18,14 +18,16 @@ use tantivy::{columnar::Column, postings::SegmentPostings, DocSet};use crate::webgraph::{schema::{Field, FieldEnum},+ warmed_column_fields::WarmedColumnFields,NodeID,};-#[derive(Debug, Clone, bincode::Encode, bincode::Decode)]+#[derive(Debug, Clone)]pub struct HostLinksQuery {node: NodeID,field: FieldEnum,deduplication_field: FieldEnum,+ warmed_column_fields: WarmedColumnFields,}impl HostLinksQuery {@@ -33,11 +35,13 @@ impl HostLinksQuery {node: NodeID,lookup_field: F,deduplication_field: FDedup,+ warmed_column_fields: WarmedColumnFields,) -> Self {Self {node,field: lookup_field.into(),deduplication_field: deduplication_field.into(),+ warmed_column_fields,}}}@@ -51,6 +55,7 @@ impl tantivy::query::Query for HostLinksQuery {node: self.node,field: self.field,deduplication_field: self.deduplication_field,+ warmed_column_fields: self.warmed_column_fields.clone(),}))}}@@ -59,6 +64,7 @@ struct HostLinksWeight {node: NodeID,field: FieldEnum,deduplication_field: FieldEnum,+ warmed_column_fields: WarmedColumnFields,}impl tantivy::query::Weight for HostLinksWeight {@@ -71,7 +77,12 @@ impl tantivy::query::Weight for HostLinksWeight {let field = schema.get_field(self.field.name())?;let term = tantivy::Term::from_field_u64(field, self.node.as_u64());- match HostLinksScorer::new(reader, term, self.deduplication_field) {+ match HostLinksScorer::new(+ reader,+ term,+ self.deduplication_field,+ &self.warmed_column_fields,+ ) {Ok(Some(scorer)) => Ok(Box::new(scorer)),_ => Ok(Box::new(tantivy::query::EmptyScorer)),}@@ -97,8 +108,12 @@ impl HostLinksScorer {reader: &tantivy::SegmentReader,term: tantivy::Term,deduplication_field: FieldEnum,+ warmed_column_fields: &WarmedColumnFields,) -> tantivy::Result<Option<Self>> {- let host_id_column = reader.column_fields().u64(deduplication_field.name())?;+ let host_id_column = warmed_column_fields+ .segment(&reader.segment_id())+ .u64(deduplication_field)+ .unwrap();Ok(reader.inverted_index(term.field())?diff --git a/crates/core/src/webgraph/schema.rs b/crates/core/src/webgraph/schema.rsindex 8ba42592..babaa232 100644--- a/crates/core/src/webgraph/schema.rs+++ b/crates/core/src/webgraph/schema.rs@@ -318,3 +318,9 @@ enum_dispatch_from_discriminant!(FieldEnumDiscriminants => FieldEnum,Label,SortScore,]);++impl crate::enum_map::InsertEnumMapKey for FieldEnumDiscriminants {+ fn into_usize(self) -> usize {+ self as usize+ }+}diff --git a/crates/core/src/webgraph/searcher.rs b/crates/core/src/webgraph/searcher.rsindex eaf1ba98..986cd45a 100644--- a/crates/core/src/webgraph/searcher.rs+++ b/crates/core/src/webgraph/searcher.rs@@ -16,15 +16,23 @@use crate::ampc::dht::ShardId;+use super::warmed_column_fields::WarmedColumnFields;+pub struct Searcher {tantivy_searcher: tantivy::Searcher,shard: ShardId,+ warmed_column_fields: WarmedColumnFields,}impl Searcher {- pub fn new(tantivy_searcher: tantivy::Searcher, shard: ShardId) -> Self {+ pub fn new(+ tantivy_searcher: tantivy::Searcher,+ warmed_column_fields: WarmedColumnFields,+ shard: ShardId,+ ) -> Self {Self {tantivy_searcher,+ warmed_column_fields,shard,}}@@ -36,4 +44,8 @@ impl Searcher {pub fn tantivy_searcher(&self) -> &tantivy::Searcher {&self.tantivy_searcher}++ pub fn warmed_column_fields(&self) -> &WarmedColumnFields {+ &self.warmed_column_fields+ }}diff --git a/crates/core/src/webgraph/store.rs b/crates/core/src/webgraph/store.rsindex 90773fe6..d850d973 100644--- a/crates/core/src/webgraph/store.rs+++ b/crates/core/src/webgraph/store.rs@@ -26,6 +26,7 @@ use super::{query::collector::{Collector, TantivyCollector},schema::{self, create_schema, Field, FromHostId, FromId, ToHostId, ToId},searcher::Searcher,+ warmed_column_fields::WarmedColumnFields,Edge,};use crate::{ampc::dht::ShardId, webpage::html::links::RelFlags, Result};@@ -44,6 +45,7 @@ pub struct EdgeStore {reader: tantivy::IndexReader,shard_id: ShardId,path: PathBuf,+ warmed_column_fields: WarmedColumnFields,}impl EdgeStore {@@ -63,12 +65,15 @@ impl EdgeStore {}).open_or_create(MmapDirectory::open(&path)?)?;+ let warmed_column_fields = WarmedColumnFields::new(&index.reader()?.searcher())?;+Ok(Self {path: path.as_ref().to_path_buf(),writer: None,reader: index.reader()?,index,shard_id,+ warmed_column_fields,writer_dedup: FxHashSet::default(),})}@@ -129,6 +134,8 @@ impl EdgeStore {)?;}+ self.commit()?;+Ok(())}@@ -154,6 +161,7 @@ impl EdgeStore {.commit()?;self.writer_dedup.clear();self.reader.reload()?;+ self.warmed_column_fields = WarmedColumnFields::new(&self.reader.searcher())?;Ok(())}@@ -217,15 +225,21 @@ impl EdgeStore {}fn searcher(&self) -> Searcher {- Searcher::new(self.reader.searcher(), self.shard_id)+ Searcher::new(+ self.reader.searcher(),+ self.warmed_column_fields.clone(),+ self.shard_id,+ )}pub fn search_initial<Q: Query>(&self,query: &Q,) -> Result<<Q::Collector as Collector>::Fruit> {- let res = self.searcher().tantivy_searcher().search(- &query.tantivy_query(),+ let searcher = self.searcher();++ let res = searcher.tantivy_searcher().search(+ &query.tantivy_query(&searcher),&TantivyCollector::from(&query.collector(self.shard_id)),)?;diff --git a/crates/core/src/webgraph/warmed_column_fields.rs b/crates/core/src/webgraph/warmed_column_fields.rsnew file mode 100644index 00000000..a2afc9fe--- /dev/null+++ b/crates/core/src/webgraph/warmed_column_fields.rs@@ -0,0 +1,68 @@+// Stract is an open source web search engine.+// Copyright (C) 2024 Stract ApS+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++use std::collections::HashMap;++use tantivy::{columnar::Column, index::SegmentId};++use super::schema::{Field, FieldEnum, FieldEnumDiscriminants};+use crate::{enum_map::EnumMap, Result};++#[derive(Debug, Clone)]+pub struct SegmentColumnFields {+ u64_fields: EnumMap<FieldEnumDiscriminants, Column<u64>>,+}++impl SegmentColumnFields {+ pub fn u64<F: Field>(&self, field: F) -> Option<Column<u64>> {+ let field_enum: FieldEnum = field.into();+ self.u64_fields+ .get(FieldEnumDiscriminants::from(field_enum))+ .cloned()+ }+}++#[derive(Debug, Clone)]+pub struct WarmedColumnFields {+ segments: HashMap<SegmentId, SegmentColumnFields>,+}++impl WarmedColumnFields {+ pub fn new(tantivy_searcher: &tantivy::Searcher) -> Result<Self> {+ let mut segments = HashMap::new();+ for segment in tantivy_searcher.segment_readers() {+ let mut u64_fields = EnumMap::new();+ for field in FieldEnum::iter() {+ match field.field_type() {+ tantivy::schema::FieldType::U64(numeric_options)+ if numeric_options.is_columnar() =>+ {+ let column = segment.column_fields().u64(field.name())?;+ u64_fields.insert(field.into(), column);+ }+ _ => {}+ }+ }+ segments.insert(segment.segment_id(), SegmentColumnFields { u64_fields });+ }++ Ok(Self { segments })+ }++ pub fn segment(&self, segment_id: &SegmentId) -> &SegmentColumnFields {+ self.segments.get(segment_id).as_ref().unwrap()+ }+}