Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
c47f98c
feat add tools for relations using ID
tourtourigny Jun 4, 2025
61c9d9e
Merge branch 'main' into feat/mcp/new-tools
tourtourigny Jun 4, 2025
8474154
fix can subquery multiple attributes
tourtourigny Jun 4, 2025
476a177
feat setup embeddings on seed data
tourtourigny Jun 4, 2025
0031b29
feat attributes and relation on get and name lookup
tourtourigny Jun 5, 2025
1689abb
feat add distant relations and fix search relationType
tourtourigny Jun 6, 2025
30edac2
feat relationships can now be indirect
tourtourigny Jun 6, 2025
580cfe9
feat restrict to paths with no primitives
tourtourigny Jun 9, 2025
aaf9fe2
fix remove phantom data
tourtourigny Jun 10, 2025
e161048
fix format
tourtourigny Jun 10, 2025
4262216
fix update descriptions for mcp tools
tourtourigny Jun 10, 2025
574fbfd
feat provide better instructions
tourtourigny Jun 11, 2025
e97868b
fix search relation type and cleanup get entity info output
tourtourigny Jun 11, 2025
a6174ab
feat get from relation basics
tourtourigny Jun 11, 2025
d0e884c
feat search from restrictions of relations that can be chained
tourtourigny Jun 13, 2025
6db4af8
feat traverse nodes in both directions
tourtourigny Jun 16, 2025
795c091
feat traversal added to search entity
tourtourigny Jun 17, 2025
7759a29
fix fmt
tourtourigny Jun 17, 2025
74e88c8
feat search by query with relation names and search space
tourtourigny Jun 25, 2025
919d3b4
feat new data for pluralism tests using spaces
tourtourigny Jun 25, 2025
d9d92a3
fix formatting and imports
tourtourigny Jun 25, 2025
7d72340
feat triples are use for searches
tourtourigny Jul 2, 2025
a5f4ffd
fix adapt descriptions
tourtourigny Jul 2, 2025
2bbe268
Merge branch 'main' into feat/mcp/new-tools
tourtourigny Jul 2, 2025
a2a6add
fix update format for clippy update
tourtourigny Jul 2, 2025
54db2b5
fix code review comments
tourtourigny Jul 2, 2025
c2c2e85
fix typos
tourtourigny Jul 3, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions api/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ fn main() {
.map(|desc| desc.trim().to_string())
.unwrap_or_else(|| "unknown".to_string());

println!("cargo::rustc-env=GIT_COMMIT={}", git_hash);
println!("cargo::rustc-env=GIT_TAG={}", git_tag);
println!("cargo::rustc-env=GIT_COMMIT={git_hash}");
println!("cargo::rustc-env=GIT_TAG={git_tag}");

// Always rerun if any git changes occur
println!("cargo::rerun-if-changed=.git/HEAD");
Expand Down
8 changes: 3 additions & 5 deletions api/src/query_mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl QueryMapper {
self.node_counter += 1;

self.match_statements
.push(format!("MATCH ({} {{id: \"{id}\"}})", node_var));
.push(format!("MATCH ({node_var} {{id: \"{id}\"}})"));
self.return_statement_vars.insert(node_var.clone());

selection
Expand All @@ -50,10 +50,8 @@ impl QueryMapper {
self.relation_counter += 1;
self.node_counter += 1;

self.match_statements.push(format!(
"MATCH ({}) -[{}]-> ({})",
node_var, relation_var, to_var
));
self.match_statements
.push(format!("MATCH ({node_var}) -[{relation_var}]-> ({to_var})"));
self.return_statement_vars.insert(self.relation_var());

selection
Expand Down
2 changes: 1 addition & 1 deletion grc20-core/src/ids/base58.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub fn decode_base58_to_uuid(encoded: &str) -> Result<String, &'static str> {
}
}

let hex_str = format!("{:032x}", decoded);
let hex_str = format!("{decoded:032x}");
Ok(format!(
"{}-{}-{}-{}-{}",
&hex_str[0..8],
Expand Down
6 changes: 3 additions & 3 deletions grc20-core/src/ids/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ pub fn create_merged_version_id(merged_version_ids: Vec<&str>) -> String {
}

pub fn create_version_id(space_id: &str, proposal_id: &str) -> String {
create_id_from_unique_string(format!("{}:{}", space_id, proposal_id))
create_id_from_unique_string(format!("{space_id}:{proposal_id}"))
}

pub fn create_version_id_from_block(space_id: &str, block: u64) -> String {
create_id_from_unique_string(format!("{}:{}", space_id, block))
create_id_from_unique_string(format!("{space_id}:{block}"))
}

/**
Expand All @@ -56,7 +56,7 @@ pub fn create_version_id_from_block(space_id: &str, block: u64) -> String {
* the new one that they're creating.
*/
pub fn create_space_id(network: &str, address: &str) -> String {
create_id_from_unique_string(format!("{}:{}", network, address))
create_id_from_unique_string(format!("{network}:{address}"))
}

pub fn create_id_from_unique_string(text: impl Into<String>) -> String {
Expand Down
9 changes: 9 additions & 0 deletions grc20-core/src/mapping/entity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub mod find_path;
pub mod insert_many;
pub mod insert_one;
pub mod models;
pub mod search_with_traversals;
pub mod semantic_search;
pub mod utils;

Expand All @@ -15,6 +16,7 @@ pub use find_one::FindOneQuery;
pub use find_path::FindPathQuery;
pub use insert_one::InsertOneQuery;
pub use models::{Entity, EntityNode, EntityNodeRef, SystemProperties};
pub use search_with_traversals::SearchWithTraversals;
pub use semantic_search::SemanticSearchQuery;
pub use utils::{EntityFilter, EntityRelationFilter, TypesFilter};

Expand Down Expand Up @@ -130,6 +132,13 @@ pub fn search<T>(neo4j: &neo4rs::Graph, vector: Vec<f64>) -> SemanticSearchQuery
SemanticSearchQuery::new(neo4j, vector)
}

pub fn search_from_restictions<T>(
neo4j: &neo4rs::Graph,
vector: Vec<f64>,
) -> SearchWithTraversals<T> {
SearchWithTraversals::new(neo4j, vector)
}

// TODO: add docs for use via GraphQL
pub fn find_path(neo4j: &neo4rs::Graph, id1: String, id2: String) -> FindPathQuery {
FindPathQuery::new(neo4j, id1, id2)
Expand Down
206 changes: 206 additions & 0 deletions grc20-core/src/mapping/entity/search_with_traversals.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
use futures::{Stream, StreamExt, TryStreamExt};

use crate::{
entity::utils::MatchEntity,
error::DatabaseError,
mapping::{
query_utils::VersionFilter, AttributeNode, FromAttributes, PropFilter, QueryBuilder,
QueryStream, Subquery, EFFECTIVE_SEARCH_RATIO,
},
};

use super::{Entity, EntityFilter, EntityNode};

pub struct SearchWithTraversals<T> {
neo4j: neo4rs::Graph,
vector: Vec<f64>,
filters: Vec<EntityFilter>,
space_id: Option<PropFilter<String>>,
version: VersionFilter,
limit: usize,
skip: Option<usize>,
threshold: f64,

_marker: std::marker::PhantomData<T>,
}

impl<T> SearchWithTraversals<T> {
pub fn new(neo4j: &neo4rs::Graph, vector: Vec<f64>) -> Self {
Self {
neo4j: neo4j.clone(),
vector,
filters: Vec::new(),
space_id: None,
version: VersionFilter::default(),
limit: 100,
skip: None,
threshold: 0.75,

_marker: std::marker::PhantomData,
}
}

pub fn filter(mut self, filter: EntityFilter) -> Self {
self.filters.push(filter);
self
}

pub fn space_id(mut self, filter: PropFilter<String>) -> Self {
self.space_id = Some(filter);
self
}

pub fn version(mut self, version: impl Into<String>) -> Self {
self.version.version_mut(version.into());
self
}

pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}

pub fn limit_opt(mut self, limit: Option<usize>) -> Self {
if let Some(limit) = limit {
self.limit = limit;
}
self
}

pub fn skip(mut self, skip: usize) -> Self {
self.skip = Some(skip);
self
}

pub fn skip_opt(mut self, skip: Option<usize>) -> Self {
self.skip = skip;
self
}

pub fn threshold(mut self, threshold: f64) -> Self {
if (0.0..=1.0).contains(&threshold) {
self.threshold = threshold
}
self
}

fn subquery(&self) -> QueryBuilder {
const QUERY: &str = r#"
CALL db.index.vector.queryNodes('vector_index', $limit * $effective_search_ratio, $vector)
YIELD node AS n, score AS score
WHERE score > $threshold
MATCH (e:Entity) -[r:ATTRIBUTE]-> (n)
"#;

self.filters
.iter()
.fold(QueryBuilder::default().subquery(QUERY), |query, filter| {
query.subquery(filter.subquery("e"))
})
.limit(self.limit)
.skip_opt(self.skip)
.params("vector", self.vector.clone())
.params("effective_search_ratio", EFFECTIVE_SEARCH_RATIO)
.params("limit", self.limit as i64)
.params("threshold", self.threshold)
}
}

#[derive(Clone, Debug, PartialEq)]
pub struct SearchWithTraversalsResult<T> {
pub entity: T,
}

impl QueryStream<SearchWithTraversalsResult<EntityNode>> for SearchWithTraversals<EntityNode> {
async fn send(
self,
) -> Result<
impl Stream<Item = Result<SearchWithTraversalsResult<EntityNode>, DatabaseError>>,
DatabaseError,
> {
let query = self.subquery().r#return("DISTINCT e");

if cfg!(debug_assertions) || cfg!(test) {
tracing::info!(
"entity_node::SearchWithTraversals::<EntityNode>:\n{}\nparams:{:?}",
query.compile(),
query.params()
);
};

#[derive(Debug, serde::Deserialize)]
struct RowResult {
e: EntityNode,
}

Ok(self
.neo4j
.execute(query.build())
.await?
.into_stream_as::<RowResult>()
.map_err(DatabaseError::from)
.and_then(|row| async move { Ok(SearchWithTraversalsResult { entity: row.e }) }))
}
}

impl<T: FromAttributes> QueryStream<SearchWithTraversalsResult<Entity<T>>>
for SearchWithTraversals<Entity<T>>
{
async fn send(
self,
) -> Result<
impl Stream<Item = Result<SearchWithTraversalsResult<Entity<T>>, DatabaseError>>,
DatabaseError,
> {
let match_entity = MatchEntity::new(&self.space_id, &self.version);

let query = self.subquery().with(
vec!["e".to_string()],
match_entity.chain(
"e",
"attrs",
"types",
Some(vec![]),
"RETURN e{.*, attrs: attrs, types: types}",
),
);

if cfg!(debug_assertions) || cfg!(test) {
tracing::info!(
"entity_node::SearchWithTraversals::<Entity<T>>:\n{}\nparams:{:?}",
query.compile(),
query.params
);
};

#[derive(Debug, serde::Deserialize)]
struct RowResult {
#[serde(flatten)]
node: EntityNode,
attrs: Vec<AttributeNode>,
types: Vec<EntityNode>,
}

let stream = self
.neo4j
.execute(query.build())
.await?
.into_stream_as::<RowResult>()
.map_err(DatabaseError::from)
.map(|row_result| {
row_result.and_then(|row| {
T::from_attributes(row.attrs.into())
.map(|data| SearchWithTraversalsResult {
entity: Entity {
node: row.node,
attributes: data,
types: row.types.into_iter().map(|t| t.id).collect(),
},
})
.map_err(DatabaseError::from)
})
});

Ok(stream)
}
}
5 changes: 1 addition & 4 deletions grc20-core/src/mapping/entity/semantic_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
error::DatabaseError,
mapping::{
query_utils::VersionFilter, AttributeNode, FromAttributes, PropFilter, QueryBuilder,
QueryStream, Subquery,
QueryStream, Subquery, EFFECTIVE_SEARCH_RATIO,
},
};

Expand Down Expand Up @@ -112,9 +112,6 @@ pub struct SemanticSearchResult<T> {
pub entity: T,
pub score: f64,
}

const EFFECTIVE_SEARCH_RATIO: f64 = 10000.0; // Adjust this ratio based on your needs

impl QueryStream<SemanticSearchResult<EntityNode>> for SemanticSearchQuery<EntityNode> {
async fn send(
self,
Expand Down
Loading