Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(search): return size hits when a query sits beside a top-level knn (#2561)

Term567ea7b2bde250
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 76f57a407..aba2165c6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- A search with both `query` and a top-level `knn` returns `size` hits, not
+ `k` (#2561). The page was widened to `k`, so `size: 5, k: 20` returned
+ 20 hits. `k` still sets how many nearest neighbours join the candidate
+ set, and `from`/`size` page through the union, as in Elasticsearch.
- Index deletion no longer waits for unrelated index statistics while
resolving its selectors. Index listings and health checks also release
their index-map locks before awaiting statistics, so a stalled schema
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 86acb6958..8e3a16356 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -14177,9 +14177,19 @@ async fn search_impl(
} else {
knn_query_json
};
+ // A pure knn search is raised to `k` here and trimmed back by
+ // `knn_total_cap`. A hybrid search keeps the request's `size`
+ // (#2561): the engine pins the full top-k into the union itself
+ // (`pin_knn_clause`), so `k` widens the candidate set, and `size`
+ // is how many hits come back, as in ES.
+ let size = if body.query.is_some() {
+ body.size
+ } else {
+ body.size.max(k_total)
+ };
EsSearchBody {
query: Some(merged_query),
- size: body.size.max(k_total),
+ size,
knn: None,
..body.clone()
}
diff --git a/engine/crates/xerj-api/tests/knn_beside_query_with_aggs_stays_200.rs b/engine/crates/xerj-api/tests/knn_beside_query_with_aggs_stays_200.rs
index 66a360c94..fcdab9bd9 100644
--- a/engine/crates/xerj-api/tests/knn_beside_query_with_aggs_stays_200.rs
+++ b/engine/crates/xerj-api/tests/knn_beside_query_with_aggs_stays_200.rs
@@ -429,3 +429,83 @@ async fn knn_beside_bool_query_keeps_the_vector_contribution() {
"#825: the better vector match must lead the page: hits={hits:?} {body}"
);
}
+
+/// #2561: in the hybrid shape `size` is how many hits come back and `k` is
+/// how many nearest neighbours join the candidate set. The page used to be
+/// widened to `k`, so `size: 5, k: 20` returned 20 hits. The page must be
+/// the first `size` hits of the union (paged with `from`), and the vector
+/// side must still contribute: `vec` matches no term, and its vector is the
+/// query vector, so it leads the union.
+#[tokio::test]
+async fn knn_beside_query_returns_size_hits_not_k() {
+ let (app, _dir) = app().await;
+
+ let (st, b) = json_req(
+ &app,
+ "PUT",
+ "/sz",
+ json!({ "mappings": { "properties": {
+ "text": { "type": "text" },
+ "v": { "type": "dense_vector", "dims": 3, "similarity": "cosine" }
+ } } }),
+ )
+ .await;
+ assert!(st.is_success(), "create index: {st} {b}");
+ let mut docs: Vec<(String, Value)> = (1..=30)
+ .map(|i| {
+ (
+ i.to_string(),
+ json!({ "text": format!("apple doc {i}"), "v": [1.0, i as f32, 0.5] }),
+ )
+ })
+ .collect();
+ docs.push(("vec".into(), json!({ "text": "zzz", "v": [0.0, 0.0, 1.0] })));
+ for (id, doc) in docs {
+ let (st, b) = json_req(&app, "POST", &format!("/sz/_doc/{id}"), doc).await;
+ assert!(st.is_success(), "index {id}: {st} {b}");
+ }
+ let (_s, _b) = json_req(&app, "POST", "/sz/_refresh", json!({})).await;
+
+ let search = |from: usize, size: usize| {
+ let app = app.clone();
+ async move {
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ "/sz/_search",
+ json!({
+ "from": from,
+ "size": size,
+ "_source": false,
+ "query": { "match": { "text": "apple" } },
+ "knn": { "field": "v", "query_vector": [0.0, 0.0, 1.0], "k": 20, "num_candidates": 31 }
+ }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "_search status: {status} {body}");
+ body.pointer("/hits/hits")
+ .and_then(Value::as_array)
+ .map(|hits| {
+ hits.iter()
+ .filter_map(|h| h.get("_id").and_then(Value::as_str).map(String::from))
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default()
+ }
+ };
+
+ let all = search(0, 31).await;
+ let page = search(0, 5).await;
+ assert_eq!(
+ page.len(),
+ 5,
+ "#2561: size 5 beside knn k 20 must return 5 hits, not k: {page:?}"
+ );
+ assert_eq!(page, all[..5], "the page is the head of the union: {all:?}");
+ assert!(
+ page.iter().any(|id| id == "vec"),
+ "the vector-only document must still reach the page: {page:?}"
+ );
+ let next = search(5, 5).await;
+ assert_eq!(next, all[5..10], "from pages through the union: {all:?}");
+}