Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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: 4 additions & 0 deletions crates/utopia-server/src/api/graph_routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ pub struct EntitySearchQuery {
/// 不给就是当下
#[serde(default)]
pub as_of: Option<String>,
/// 只要名字完全相同的(规范名或现行别名),不扫整个库;不给就是子串搜索
#[serde(default)]
pub exact: bool,
}

pub async fn search_entities(
Expand All @@ -158,6 +161,7 @@ pub async fn search_entities(
query.limit.unwrap_or(10).clamp(1, 100),
query.offset.unwrap_or(0).max(0),
as_of,
query.exact,
)
.await?;
Ok(Json(json!({ "entities": entities, "total": total })))
Expand Down
50 changes: 50 additions & 0 deletions crates/utopia-server/src/api/token_read_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,3 +402,53 @@ async fn an_external_id_prefix_docs_underscore_finds_docs_a_md_but_not_docsxa_md
);
Ok(())
}

#[tokio::test]
async fn an_exact_name_search_by_a_read_token_returns_only_that_entity() -> anyhow::Result<()> {
let Some(f) = Fixture::new().await? else {
return Ok(());
};
let result = async {
sqlx::query(
"INSERT INTO entities(id,kb_id,type_id,canonical_name)
VALUES ($1,$2,$3,'Zhang San Jr')",
)
.bind(Uuid::now_v7())
.bind(f.kb)
.bind(f.person)
.execute(&f.pool)
.await?;
let token = f.read_token(f.kb).await;
let mut answers = Vec::new();
for suffix in ["", "&exact=true"] {
let request = Request::get(format!(
"/api/v1/kbs/{}/entities?q=zhang%20san{suffix}",
f.kb
))
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())?;
let response = f.app.clone().oneshot(request).await?;
anyhow::ensure!(
response.status() == StatusCode::OK,
"{suffix}: {}",
response.status()
);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
answers.push(serde_json::from_slice::<serde_json::Value>(&bytes)?);
}
anyhow::ensure!(
answers[0]["total"] == 2,
"without exact both are found: {}",
answers[0]
);
anyhow::ensure!(
answers[1]["total"] == 1 && answers[1]["entities"][0]["id"] == json!(f.entity),
"with exact only Zhang San is found: {}",
answers[1]
);
Ok(())
}
.await;
f.cleanup().await?;
result
}
5 changes: 3 additions & 2 deletions crates/utopia-server/src/api/tools_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,8 @@ async fn lookup(
// 现在算——和现状一致,回放图上的搜索框另走 `/kbs/{id}/entities` 自己挂
// 时刻
let (hits, total) =
utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, raw, 8, 0, None).await?;
utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, raw, 8, 0, None, false)
.await?;
if !hits.is_empty() {
return Ok((hits, Some(total)));
}
Expand All @@ -482,7 +483,7 @@ async fn lookup(
let mut pool: Vec<GraphNode> = Vec::new();
for w in &words {
let (found, _) =
utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, w, 40, 0, None)
utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, w, 40, 0, None, false)
.await?;
for n in found {
if !pool.iter().any(|p| p.id == n.id) {
Expand Down
45 changes: 38 additions & 7 deletions crates/utopia-store/src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1645,42 +1645,73 @@ pub async fn search_entities(
// 记录轴(0019):给了就按**当时**回放——列出当时可见的实体(合并之前的被并者
// 还在,之后才建的不在),度数按当时谁持有事实来数,与回放中的画布一致
as_of: Option<chrono::DateTime<chrono::Utc>>,
// 只要名字完全相同的(规范名或现行别名),不做子串扫描
exact: bool,
) -> AppResult<(Vec<GraphNode>, i64)> {
let pattern = format!("%{}%", text.trim());
let named = crate::names::has_name_like("e", 2);
// 同名的键与召回同一种写法(`resolution` 里 `has_name_in` 的用法):规整之后小写
let exact = vec![crate::resolution::normalize_name(text).to_lowercase()];
let folded_name = vec![crate::resolution::normalize_name(text).to_lowercase()];
// 不回放时 SQL 里没有时刻参数,与从前逐字相同;回放时才多绑一个
let visible = |param: usize| crate::record_axis::entity_visible_at("e", as_of.map(|_| param));
let rewind = as_of.map(|_| 6);
let same_name = crate::names::has_name_in("e", 1, 5);
// 精确时把规范名与别名写成一个 id 集合,各走各的索引(`entities_kb_name_idx`、
// `facts_value_text_idx`)。写成 `OR` 的话一边是子查询,规划器只能把库里的实体扫一遍。
// 规范名那个索引只收没被合并的实体:不回放时这与 `visible` 是一回事,带上它;回放时
// 被并者当时还在,不能带,那一支退回按库扫。`$2` 绑着不用,参数位不挪
let exactly_named = |names: usize| {
format!(
"e.id IN (SELECT x.id FROM entities x
WHERE x.kb_id = $1 AND lower(x.canonical_name) = ANY(${names}){unmerged}
UNION ALL {aliases})",
unmerged = if as_of.is_none() {
" AND x.merged_into IS NULL"
} else {
""
},
aliases = crate::names::named_ids(1, names),
)
};
let matches = if exact {
exactly_named(5)
} else {
format!("(e.canonical_name ILIKE $2 OR {named})")
};
let sql = format!(
"{} WHERE e.kb_id = $1 AND {visible}
AND (e.canonical_name ILIKE $2 OR {named})
AND {matches}
ORDER BY (lower(e.canonical_name) = ANY($5) OR {same_name}) DESC,
degree DESC, e.canonical_name, e.id LIMIT $3 OFFSET $4",
node_sql(rewind, rewind),
visible = visible(6),
same_name = crate::names::has_name_in("e", 1, 5),
);
let mut nodes_query = sqlx::query_as::<_, GraphNode>(&sql)
.bind(kb_id)
.bind(&pattern)
.bind(limit)
.bind(offset)
.bind(&exact);
.bind(&folded_name);
if let Some(t) = as_of {
nodes_query = nodes_query.bind(t);
}
let nodes: Vec<GraphNode> = nodes_query.fetch_all(pool).await?;
// 数量那条的名字列表在 `$3`,时刻挪到 `$4`
let count_matches = if exact {
exactly_named(3)
} else {
format!("(e.canonical_name ILIKE $2 OR {named})")
};
let count_sql = format!(
"SELECT count(*) FROM entities e
WHERE e.kb_id = $1 AND {visible}
AND (e.canonical_name ILIKE $2 OR {named})",
visible = visible(3),
AND {count_matches}",
visible = visible(4),
);
let mut count_query = sqlx::query_as::<_, (i64,)>(&count_sql)
.bind(kb_id)
.bind(&pattern);
.bind(&pattern)
.bind(&folded_name);
if let Some(t) = as_of {
count_query = count_query.bind(t);
}
Expand Down
9 changes: 7 additions & 2 deletions crates/utopia-store/src/names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,17 @@ pub async fn record(
/// 相关子查询 `nf.subject_id = e.id` 不带库,规划器用不上这个索引,每次召回都要
/// 扫全表的 facts——所有库的
pub fn has_name_in(entity: &str, kb: usize, names: usize) -> String {
format!("{entity}.id IN ({})", named_ids(kb, names))
}

/// [`has_name_in`] 的子查询本身:有这些名字之一的实体的 id
pub fn named_ids(kb: usize, names: usize) -> String {
format!(
"{entity}.id IN (SELECT nf.subject_id FROM facts nf
"SELECT nf.subject_id FROM facts nf
JOIN relation_types nr ON nr.id = nf.predicate_id
WHERE nf.kb_id = ${kb} AND nr.kb_id = ${kb} AND nr.builtin AND nr.key = '{KNOWN_AS}'
AND nf.invalidated_at IS NULL AND nf.object_value IS NOT NULL
AND lower(nf.object_value->>'value') = ANY(${names}))"
AND lower(nf.object_value->>'value') = ANY(${names})"
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ async fn a_search_puts_the_exact_name_first() -> anyhow::Result<()> {
busy(&pool, kb, store, rel, city).await?;
}
let (rows, total) =
utopia_store::graph::search_entities(&pool, kb, "Apple", 8, 0, None).await?;
utopia_store::graph::search_entities(&pool, kb, "Apple", 8, 0, None, false).await?;
assert_eq!(total, 10);
assert_eq!(rows.len(), 8);
assert_eq!(rows[0].id, apple, "the entity named exactly Apple comes first");
Expand All @@ -118,6 +118,7 @@ async fn a_search_puts_the_exact_name_first() -> anyhow::Result<()> {
8,
0,
Some(chrono::Utc::now()),
false,
)
.await?;
assert_eq!(rows[0].id, apple, "the same holds when replaying a moment");
Expand All @@ -130,7 +131,7 @@ async fn a_search_puts_the_exact_name_first() -> anyhow::Result<()> {
busy(&pool, kb, lab, rel, city).await?;
}
let (rows, total) =
utopia_store::graph::search_entities(&pool, kb, "ibm", 8, 0, None).await?;
utopia_store::graph::search_entities(&pool, kb, "ibm", 8, 0, None, false).await?;
assert_eq!(total, 10);
assert_eq!(rows[0].id, ibm, "an entity whose name is exactly IBM comes first");
anyhow::Ok(())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
//! `exact = true`: the entity named exactly so, and nothing that merely contains the name.
//!
//! A caller that knows the name (a path, a symbol) wants one entity, not the substring scan of
//! the whole base. The default stays the substring search, exact name first.
//!
//! Skipped without `UTOPIA_DATABASE_URL`. Builds and removes its own rows.

use sqlx::PgPool;
use uuid::Uuid;

async fn entity(pool: &PgPool, kb: Uuid, ty: Uuid, name: &str) -> anyhow::Result<Uuid> {
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
)
.bind(id)
.bind(kb)
.bind(ty)
.bind(name)
.execute(pool)
.await?;
Ok(id)
}

#[tokio::test]
async fn an_exact_name_search_returns_only_that_entity() -> anyhow::Result<()> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(());
};
let pool = PgPool::connect(&url).await?;
let (org, ws, kb, ty) = (
Uuid::now_v7(),
Uuid::now_v7(),
Uuid::now_v7(),
Uuid::now_v7(),
);
sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'exact-only-search-test')")
.bind(org)
.execute(&pool)
.await?;
sqlx::query(
"INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'exact-only-search-test')",
)
.bind(ws)
.bind(org)
.execute(&pool)
.await?;
sqlx::query(
"INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'exact-only-search-test')",
)
.bind(kb)
.bind(ws)
.execute(&pool)
.await?;

let run = async {
sqlx::query(
"INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'file', 'File')",
)
.bind(ty)
.bind(kb)
.execute(&pool)
.await?;
let file = entity(&pool, kb, ty, "acme/repo:src/a.ts").await?;
let symbol = entity(&pool, kb, ty, "acme/repo:src/a.ts#parse").await?;

let (rows, total) = utopia_store::graph::search_entities(
&pool,
kb,
"acme/repo:src/a.ts",
10,
0,
None,
true,
)
.await?;
assert_eq!(
rows.iter().map(|r| r.id).collect::<Vec<_>>(),
vec![file],
"an exact search returns the entity named so and not the one that contains the name"
);
assert_eq!(total, 1, "the total counts only the exact match");

let (rows, total) = utopia_store::graph::search_entities(
&pool,
kb,
"acme/repo:src/a.ts",
10,
0,
None,
false,
)
.await?;
assert_eq!(
rows.iter().map(|r| r.id).collect::<Vec<_>>(),
vec![file, symbol],
"without exact both are found, the exact name first"
);
assert_eq!(total, 2);

let (rows, total) = utopia_store::graph::search_entities(
&pool,
kb,
"ACME/Repo:SRC/a.ts",
10,
0,
None,
true,
)
.await?;
assert_eq!(
rows.iter().map(|r| r.id).collect::<Vec<_>>(),
vec![file],
"the name is folded to lower case, so another case still finds it"
);
assert_eq!(total, 1);
anyhow::Ok(())
}
.await;
sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
.bind(kb)
.execute(&pool)
.await?;
sqlx::query("DELETE FROM organizations WHERE id = $1")
.bind(org)
.execute(&pool)
.await?;
run
}
1 change: 1 addition & 0 deletions crates/utopia-store/tests/store/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ mod an_earlier_mention_keeps_the_stated_end;
mod an_empty_ontology_does_not_cover_the_corpus;
mod an_end_date_closes_the_open_span;
mod an_event_holds_at_the_moment_it_names;
mod an_exact_name_search_returns_only_that_entity;
mod an_exploration_says_what_it_covered;
mod an_export_carries_the_whole_ledger;
mod an_identity_name_attaches_by_its_exact_name;
Expand Down
Loading
Loading