Skip to content

web search done right

harmonic centrality nearest neighbor calculation that uses the harmonic centrality of the highest neighbors node as a seed node proxy for the centrality of that node (with a discount factor)

Mikkel Denker4915160449e3
diff --git a/crates/core/src/config/mod.rs b/crates/core/src/config/mod.rs
index 914e086a..6fc69b0c 100644
--- a/crates/core/src/config/mod.rs
+++ b/crates/core/src/config/mod.rs
@@ -696,8 +696,8 @@ pub struct CanonicalIndexConfig {
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct HarmonicNearestSeedConfig {
pub gossip: GossipConfig,
- pub original_centrality_path: String,
- pub output_path: String,
+ pub original_centrality_path: PathBuf,
+ pub output_path: PathBuf,
#[serde(default = "defaults::HarmonicNearestSeed::discount_factor")]
pub discount_factor: f64,
}
diff --git a/crates/core/src/entrypoint/centrality.rs b/crates/core/src/entrypoint/centrality.rs
index 25c8875a..a43ec60f 100644
--- a/crates/core/src/entrypoint/centrality.rs
+++ b/crates/core/src/entrypoint/centrality.rs
@@ -15,16 +15,21 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use anyhow::Result;
-use std::{cmp::Reverse, path::Path};
+use futures::StreamExt;
+use itertools::Itertools;
+use std::{cmp::Reverse, path::Path, sync::Arc};
use crate::{
+ config,
+ distributed::cluster::Cluster,
external_sort::ExternalSorter,
webgraph::{
centrality::{
approx_harmonic::ApproxHarmonic, harmonic::HarmonicCentrality, store_csv,
store_harmonic, TopNodes,
},
- WebgraphBuilder,
+ remote::{Page, RemoteWebgraph},
+ EdgeLimit, NodeID, WebgraphBuilder,
},
SortableFloat,
};
@@ -51,6 +56,7 @@ impl Centrality {
.collect();
store_csv(top_harmonics, base_output.as_ref().join("harmonic.csv"));
+ tracing::info!("done");
}
pub fn build_approx_harmonic<P: AsRef<Path>>(webgraph_path: P, base_output: P) -> Result<()> {
@@ -95,6 +101,82 @@ impl Centrality {
store_csv(top_nodes, base_output.as_ref().join("harmonic.csv"));
+ tracing::info!("done");
+
+ Ok(())
+ }
+
+ pub async fn harmonic_nearest_seed(config: config::HarmonicNearestSeedConfig) -> Result<()> {
+ let cluster = Arc::new(
+ Cluster::join_as_spectator(
+ config.gossip.addr,
+ config.gossip.seed_nodes.unwrap_or_default(),
+ )
+ .await?,
+ );
+ let graph: RemoteWebgraph<Page> = RemoteWebgraph::new(cluster).await;
+
+ let mut harmonic: speedy_kv::Db<NodeID, f64> =
+ speedy_kv::Db::open_or_create(config.output_path.join("harmonic"))?;
+ let original_centrality: speedy_kv::Db<NodeID, f64> =
+ speedy_kv::Db::open_or_create(&config.original_centrality_path)?;
+
+ let mut node_ids = graph.stream_node_ids().await;
+
+ while let Some(node_id) = node_ids.next().await {
+ match original_centrality.get(&node_id)? {
+ Some(original_centrality) => {
+ harmonic.insert(node_id, original_centrality)?;
+ }
+ None => {
+ if let Some(seed) = graph
+ .raw_ingoing_edges(node_id, EdgeLimit::Limit(1))
+ .await?
+ .pop()
+ .map(|edge| edge.from.node())
+ {
+ if let Some(seed_centrality) = original_centrality.get(&seed)? {
+ harmonic.insert(node_id, seed_centrality * config.discount_factor)?;
+ }
+ }
+ }
+ }
+
+ if harmonic.uncommitted_inserts() > 100_000_000 {
+ harmonic.commit()?;
+ }
+ }
+
+ harmonic.commit()?;
+ harmonic.merge_all_segments()?;
+
+ let mut top_nodes = Vec::with_capacity(1_000_000);
+
+ for chunk in ExternalSorter::new()
+ .with_chunk_size(100_000_000)
+ .sort(
+ harmonic
+ .iter()
+ .map(|(node_id, centrality)| (Reverse(SortableFloat(centrality)), node_id)),
+ )?
+ .take(1_000_000)
+ .map(|(Reverse(SortableFloat(centrality)), node_id)| (node_id, centrality))
+ .chunks(10_000)
+ .into_iter()
+ {
+ let (ids, centrality): (Vec<_>, Vec<_>) = chunk.into_iter().unzip();
+
+ let nodes = graph.batch_get_node(&ids).await?;
+
+ for (node, centrality) in nodes.into_iter().zip(centrality) {
+ if let Some(node) = node {
+ top_nodes.push((node, centrality));
+ }
+ }
+ }
+
+ store_csv(top_nodes, config.output_path.join("harmonic.csv"));
+
Ok(())
}
}
diff --git a/crates/core/src/entrypoint/webgraph_server.rs b/crates/core/src/entrypoint/webgraph_server.rs
index ae21fb04..96cb3bab 100644
--- a/crates/core/src/entrypoint/webgraph_server.rs
+++ b/crates/core/src/entrypoint/webgraph_server.rs
@@ -58,7 +58,8 @@ sonic_service!(
RawOutgoingEdges,
RawIngoingEdgesWithLabels,
RawOutgoingEdgesWithLabels,
- PagesByHosts
+ PagesByHosts,
+ GetNodeIDs
]
);
@@ -206,6 +207,25 @@ impl Message<WebGraphService> for OutDegreeUpperBound {
}
}
+#[derive(Debug, Clone, bincode::Encode, bincode::Decode)]
+pub struct GetNodeIDs {
+ pub offset: u64,
+ pub limit: u64,
+}
+
+impl Message<WebGraphService> for GetNodeIDs {
+ type Response = Vec<NodeID>;
+
+ async fn handle(self, server: &WebGraphService) -> Self::Response {
+ server
+ .graph
+ .iter_nodes_with_offset(self.offset)
+ .take(self.limit as usize)
+ .map(|(id, _)| id)
+ .collect()
+ }
+}
+
pub async fn run(config: config::WebgraphServerConfig) -> Result<()> {
let addr: SocketAddr = config.host;
diff --git a/crates/core/src/live_index/crawler/budgets.rs b/crates/core/src/live_index/crawler/budgets.rs
index 99914032..a5ac5d54 100644
--- a/crates/core/src/live_index/crawler/budgets.rs
+++ b/crates/core/src/live_index/crawler/budgets.rs
@@ -143,7 +143,7 @@ impl SiteBudgets {
if budget == 0 {
Some(Duration::from_millis(MILLIS_PER_DAY)) // once per day
} else {
- Some(Duration::from_millis(MILLIS_PER_DAY / budget as u64))
+ Some(Duration::from_millis(MILLIS_PER_DAY / budget))
}
}
}
diff --git a/crates/core/src/main.rs b/crates/core/src/main.rs
index 480753d8..8bc2edb3 100644
--- a/crates/core/src/main.rs
+++ b/crates/core/src/main.rs
@@ -220,11 +220,16 @@ enum CentralityMode {
webgraph_path: String,
output_path: String,
},
- /// Calculate approximate harmonic centrality for the page webgraph.
+ /// Calculate approximate harmonic centrality.
ApproxHarmonic {
webgraph_path: String,
output_path: String,
},
+
+ /// Calculate harmonic centrality nearest neighbor that uses
+ /// the harmonic centrality of the highest neighbors node
+ /// as a seed node proxy for the centrality of that node (with a discount factor).
+ HarmonicNearestSeed { config_path: String },
}
#[derive(Subcommand)]
@@ -318,21 +323,26 @@ fn main() -> Result<()> {
entrypoint::canonical::create(config)?;
}
},
- Commands::Centrality { mode } => {
- match mode {
- CentralityMode::Harmonic {
- webgraph_path,
- output_path,
- } => {
- entrypoint::Centrality::build_harmonic(&webgraph_path, &output_path);
- }
- CentralityMode::ApproxHarmonic {
- webgraph_path,
- output_path,
- } => entrypoint::Centrality::build_approx_harmonic(webgraph_path, output_path)?,
+ Commands::Centrality { mode } => match mode {
+ CentralityMode::Harmonic {
+ webgraph_path,
+ output_path,
+ } => {
+ entrypoint::Centrality::build_harmonic(&webgraph_path, &output_path);
}
- tracing::info!("Done");
- }
+ CentralityMode::ApproxHarmonic {
+ webgraph_path,
+ output_path,
+ } => entrypoint::Centrality::build_approx_harmonic(webgraph_path, output_path)?,
+ CentralityMode::HarmonicNearestSeed { config_path } => {
+ let config: config::HarmonicNearestSeedConfig = load_toml_config(config_path);
+
+ tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()?
+ .block_on(entrypoint::Centrality::harmonic_nearest_seed(config))?;
+ }
+ },
Commands::Webgraph { options } => match options {
WebgraphOptions::Create { config_path } => {
let config = load_toml_config(config_path);
diff --git a/crates/core/src/webgraph/id_node_db.rs b/crates/core/src/webgraph/id_node_db.rs
index 54964aaa..555ae6bb 100644
--- a/crates/core/src/webgraph/id_node_db.rs
+++ b/crates/core/src/webgraph/id_node_db.rs
@@ -41,6 +41,10 @@ impl Id2NodeDb {
self.db.iter().map(|(id, _)| id)
}
+ pub fn iter_with_offset(&self, offset: u64) -> impl Iterator<Item = (NodeID, Node)> + '_ {
+ self.db.iter_with_offset(offset)
+ }
+
pub fn estimate_num_keys(&self) -> usize {
self.db.len()
}
diff --git a/crates/core/src/webgraph/mod.rs b/crates/core/src/webgraph/mod.rs
index 0ff59837..4b3f7e7e 100644
--- a/crates/core/src/webgraph/mod.rs
+++ b/crates/core/src/webgraph/mod.rs
@@ -400,6 +400,10 @@ impl Webgraph {
self.id2node.estimate_num_keys()
}
+ pub fn iter_nodes_with_offset(&self, offset: u64) -> impl Iterator<Item = (NodeID, Node)> + '_ {
+ self.id2node.iter_with_offset(offset)
+ }
+
/// Iterate all edges in the graph at least once.
/// Some edges may be returned multiple times.
/// This happens if they are present in more than one segment.
diff --git a/crates/core/src/webgraph/remote.rs b/crates/core/src/webgraph/remote.rs
index a4f566fe..ab34501a 100644
--- a/crates/core/src/webgraph/remote.rs
+++ b/crates/core/src/webgraph/remote.rs
@@ -31,9 +31,10 @@ use crate::{
AllShardsSelector, RandomReplicaSelector, RemoteClient, ReplicatedClient,
},
},
+ streaming_response::StreamingResponse,
},
entrypoint::webgraph_server::{
- GetNode, IngoingEdges, OutgoingEdges, PagesByHosts, RawIngoingEdges,
+ GetNode, GetNodeIDs, IngoingEdges, OutgoingEdges, PagesByHosts, RawIngoingEdges,
RawIngoingEdgesWithLabels, RawOutgoingEdges, RawOutgoingEdgesWithLabels, WebGraphService,
},
Result,
@@ -458,4 +459,46 @@ impl<G: WebgraphGranularity> RemoteWebgraph<G> {
.unique()
.collect())
}
+
+ pub async fn stream_node_ids(&self) -> impl futures::Stream<Item = NodeID> {
+ StreamNodeIDs::new(self.conn().await).stream()
+ }
+}
+
+pub struct StreamNodeIDs {
+ offset: u64,
+ limit: u64,
+ conn: Arc<sonic::replication::ShardedClient<WebGraphService, ShardId>>,
+}
+
+impl StreamNodeIDs {
+ pub fn new(conn: Arc<sonic::replication::ShardedClient<WebGraphService, ShardId>>) -> Self {
+ Self {
+ offset: 0,
+ limit: 2048,
+ conn,
+ }
+ }
+}
+
+impl StreamingResponse for StreamNodeIDs {
+ type Item = NodeID;
+
+ async fn next_batch(&mut self) -> Result<Vec<Self::Item>> {
+ let req = GetNodeIDs {
+ offset: self.offset,
+ limit: self.limit,
+ };
+
+ let res = self
+ .conn
+ .send(req, &AllShardsSelector, &RandomReplicaSelector)
+ .await?;
+ self.offset += self.limit;
+
+ Ok(res
+ .into_iter()
+ .flat_map(|(_, v)| v.into_iter().flat_map(|(_, v)| v))
+ .collect())
+ }
}
diff --git a/crates/file-store/src/random_lookup.rs b/crates/file-store/src/random_lookup.rs
index f12cde1f..b3011f6a 100644
--- a/crates/file-store/src/random_lookup.rs
+++ b/crates/file-store/src/random_lookup.rs
@@ -109,9 +109,13 @@ where
}
pub fn iter(&self) -> impl Iterator<Item = (ItemId, V)> + '_ {
+ self.iter_with_offset(0)
+ }
+
+ pub fn iter_with_offset(&self, offset: u64) -> impl Iterator<Item = (ItemId, V)> + '_ {
RandomLookupIter {
data: &self.data,
- next_id: 0,
+ next_id: offset,
_phantom: std::marker::PhantomData,
}
}
@@ -194,4 +198,33 @@ mod tests {
assert_eq!(items, res);
}
+
+ #[test]
+ fn test_iter_with_offset() {
+ let mut writer = RandomLookupWriter::new(Vec::new());
+
+ let items = vec![1u64, 2, 3, 4, 5];
+
+ for item in &items {
+ writer.write(item).unwrap();
+ }
+
+ let bytes = writer.finish().unwrap();
+
+ let store = RandomLookup::<u64>::from(OwnedBytes::new(bytes));
+
+ let res = store
+ .iter_with_offset(2)
+ .map(|(_, val)| val)
+ .collect::<Vec<_>>();
+
+ assert_eq!(items[2..], res);
+
+ let res = store
+ .iter_with_offset(3)
+ .map(|(_, val)| val)
+ .collect::<Vec<_>>();
+
+ assert_eq!(items[3..], res);
+ }
}
diff --git a/crates/speedy-kv/src/blob_index.rs b/crates/speedy-kv/src/blob_index.rs
index 10056b11..490a4862 100644
--- a/crates/speedy-kv/src/blob_index.rs
+++ b/crates/speedy-kv/src/blob_index.rs
@@ -52,6 +52,10 @@ impl BlobIndex {
self.data.iter().map(|(_, v)| v)
}
+ pub fn iter_with_offset(&self, offset: u64) -> impl Iterator<Item = BlobPointer> + '_ {
+ self.data.iter_with_offset(offset).map(|(_, v)| v)
+ }
+
pub fn path(&self) -> &Path {
&self.path
}
diff --git a/crates/speedy-kv/src/lib.rs b/crates/speedy-kv/src/lib.rs
index 3266bd69..739c8858 100644
--- a/crates/speedy-kv/src/lib.rs
+++ b/crates/speedy-kv/src/lib.rs
@@ -417,6 +417,39 @@ where
self.segments.iter().flat_map(|segment| segment.iter_raw())
}
+ pub fn iter_raw_with_offset(
+ &self,
+ offset: u64,
+ ) -> impl Iterator<Item = (SerializedRef<'_, K>, SerializedRef<'_, V>)> + '_ {
+ let mut remaining_offset = offset;
+ let mut segment_idx = 0;
+ let mut found_segment = false;
+
+ for (idx, segment) in self.segments.iter().enumerate() {
+ let segment_len = segment.len() as u64;
+ segment_idx = idx;
+ if remaining_offset < segment_len {
+ found_segment = true;
+ break;
+ }
+
+ remaining_offset -= segment_len;
+ }
+
+ if !found_segment {
+ segment_idx = self.segments.len();
+ }
+
+ self.segments
+ .iter()
+ .skip(segment_idx)
+ .flat_map(move |segment| {
+ let iter = segment.iter_raw_with_offset(remaining_offset);
+ remaining_offset = 0; // only offset into first segment
+ iter
+ })
+ }
+
pub fn sorted_iter_raw(
&self,
) -> impl Iterator<Item = (SerializedRef<'_, K>, SerializedRef<'_, V>)> + '_ {
@@ -497,6 +530,15 @@ where
})
}
+ pub fn iter_with_offset(&self, offset: u64) -> impl Iterator<Item = (K, V)> + '_ {
+ self.iter_raw_with_offset(offset).filter_map(|(k, v)| {
+ let (k, _) = bincode::decode_from_slice(k.as_bytes(), common::bincode_config()).ok()?;
+ let (v, _) = bincode::decode_from_slice(v.as_bytes(), common::bincode_config()).ok()?;
+
+ Some((k, v))
+ })
+ }
+
pub fn sorted_iter(&self) -> impl Iterator<Item = (K, V)> + '_ {
self.sorted_iter_raw().filter_map(|(k, v)| {
let (k, _) = bincode::decode_from_slice(k.as_bytes(), common::bincode_config()).ok()?;
@@ -648,4 +690,39 @@ mod tests {
assert_eq!(db.get(&3).unwrap(), Some(4));
assert_eq!(db.get(&4).unwrap(), Some(5));
}
+
+ #[test]
+ fn test_iter_with_offset() {
+ let temp_dir = gen_temp_dir().unwrap();
+ let mut db = Db::open_or_create(&temp_dir).unwrap();
+
+ db.insert(1, 2).unwrap();
+ db.insert(2, 3).unwrap();
+ db.commit().unwrap();
+ db.insert(3, 4).unwrap();
+ db.insert(4, 5).unwrap();
+ db.insert(5, 6).unwrap();
+ db.commit().unwrap();
+
+ let res: Vec<_> = db.iter_with_offset(0).take(2).collect();
+ assert_eq!(res, vec![(1, 2), (2, 3)]);
+
+ let res: Vec<_> = db.iter_with_offset(1).take(2).collect();
+ assert_eq!(res, vec![(2, 3), (3, 4)]);
+
+ let res: Vec<_> = db.iter_with_offset(2).take(2).collect();
+ assert_eq!(res, vec![(3, 4), (4, 5)]);
+
+ let res: Vec<_> = db.iter_with_offset(3).take(2).collect();
+ assert_eq!(res, vec![(4, 5), (5, 6)]);
+
+ let res: Vec<_> = db.iter_with_offset(4).take(2).collect();
+ assert_eq!(res, vec![(5, 6)]);
+
+ let res: Vec<_> = db.iter_with_offset(5).take(2).collect();
+ assert_eq!(res, vec![]);
+
+ let res: Vec<_> = db.iter_with_offset(6).take(2).collect();
+ assert_eq!(res, vec![]);
+ }
}
diff --git a/crates/speedy-kv/src/segment.rs b/crates/speedy-kv/src/segment.rs
index 196aacf3..1e39e792 100644
--- a/crates/speedy-kv/src/segment.rs
+++ b/crates/speedy-kv/src/segment.rs
@@ -209,6 +209,16 @@ impl<K, V> Segment<K, V> {
})
}
+ pub fn iter_raw_with_offset(
+ &self,
+ offset: u64,
+ ) -> impl Iterator<Item = (SerializedRef<'_, K>, SerializedRef<'_, V>)> + '_ {
+ self.blob_index.iter_with_offset(offset).map(|ptr| {
+ let blob = self.store.get_raw(&ptr).unwrap();
+ (blob.key, blob.value)
+ })
+ }
+
pub fn get_raw(&self, key: &[u8]) -> Result<Option<SerializedRef<'_, V>>> {
if !self.bloom.contains_raw(key) {
return Ok(None);