@atscript/db-mongo 0.1.182 → 0.1.183

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1368,25 +1368,47 @@ function textRunOptions(plan, query) {
1368
1368
  defaultSort: RELEVANCE_SORT
1369
1369
  } : {};
1370
1370
  }
1371
+ /**
1372
+ * Field the `vectorSearchScore` rides in through the pipeline. Renamed to the
1373
+ * public `$score` after fetch — a field name cannot start with `$`.
1374
+ */
1375
+ const SCORE_FIELD = "__atscript_score";
1371
1376
  /** Vector search via $vectorSearch aggregation stage. */
1372
1377
  async function vectorSearchImpl(host, vector, query, indexName) {
1373
1378
  const controls = query.controls || {};
1374
1379
  const plan = buildVectorSearchPlan(host, vector, query, indexName);
1375
1380
  const threshold = resolveThreshold(host, controls, indexName);
1376
- return runSearchPipeline(host, plan.stage, query, "vectorSearch", {
1377
- threshold,
1381
+ return (await runSearchPipeline(host, plan.stage, query, "vectorSearch", {
1382
+ vector: { threshold },
1378
1383
  filterStages: plan.filterStages
1379
- });
1384
+ })).map((row) => renameComputed(row, SCORE_FIELD, "$score"));
1380
1385
  }
1381
1386
  /** Vector search with faceted count. */
1382
1387
  async function vectorSearchWithCountImpl(host, vector, query, indexName) {
1383
1388
  const controls = query.controls || {};
1384
1389
  const plan = buildVectorSearchPlan(host, vector, query, indexName);
1385
1390
  const threshold = resolveThreshold(host, controls, indexName);
1386
- return runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
1387
- threshold,
1391
+ const result = await runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
1392
+ vector: { threshold },
1388
1393
  filterStages: plan.filterStages
1389
1394
  });
1395
+ return {
1396
+ data: result.data.map((row) => renameComputed(row, SCORE_FIELD, "$score")),
1397
+ count: result.count
1398
+ };
1399
+ }
1400
+ /**
1401
+ * The stages right after `$vectorSearch`: its score into {@link SCORE_FIELD}
1402
+ * (the `$meta` is read here, ahead of any `$facet`) and, with a threshold,
1403
+ * into `_score` — kept for compatibility — with the `$match` on it.
1404
+ */
1405
+ function vectorScoreStages(threshold) {
1406
+ const score = { $meta: "vectorSearchScore" };
1407
+ if (threshold === void 0) return [{ $addFields: { [SCORE_FIELD]: score } }];
1408
+ return [{ $addFields: {
1409
+ _score: score,
1410
+ [SCORE_FIELD]: score
1411
+ } }, { $match: { _score: { $gte: threshold } } }];
1390
1412
  }
1391
1413
  /**
1392
1414
  * Field name `$geoNear` writes the computed distance into. Renamed to the
@@ -1400,9 +1422,9 @@ async function geoSearchImpl(host, point, query, indexName) {
1400
1422
  const pipeline = buildGeoNearStages(host, point, query, indexName);
1401
1423
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
1402
1424
  pipeline.push({ $limit: controls.$limit || 1e3 });
1403
- pushGeoProjection(pipeline, query.controls);
1425
+ pushProjection(pipeline, query.controls, DISTANCE_FIELD);
1404
1426
  host._log("aggregate (geoSearch)", pipeline);
1405
- return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameDistance(row));
1427
+ return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance"));
1406
1428
  }
1407
1429
  /** Geo search with faceted count (rows within the distance window). */
1408
1430
  async function geoSearchWithCountImpl(host, point, query, indexName) {
@@ -1410,7 +1432,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
1410
1432
  const dataStages = [];
1411
1433
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1412
1434
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1413
- pushGeoProjection(dataStages, query.controls);
1435
+ pushProjection(dataStages, query.controls, DISTANCE_FIELD);
1414
1436
  const pipeline = [...buildGeoNearStages(host, point, query, indexName), { $facet: {
1415
1437
  data: dataStages,
1416
1438
  meta: [{ $count: "count" }]
@@ -1418,7 +1440,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
1418
1440
  host._log("aggregate (geoSearchWithCount)", pipeline);
1419
1441
  const result = await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
1420
1442
  return {
1421
- data: (result[0]?.data || []).map((row) => renameDistance(row)),
1443
+ data: (result[0]?.data || []).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance")),
1422
1444
  count: result[0]?.meta?.[0]?.count || 0
1423
1445
  };
1424
1446
  }
@@ -1459,27 +1481,28 @@ function resolveGeoKeyPath(host, indexName) {
1459
1481
  return field;
1460
1482
  }
1461
1483
  /**
1462
- * Appends a `$project` stage, keeping the computed distance in inclusion mode.
1463
- * The distance key goes on a COPY: `asProjection` (and `dedupeProjection`)
1464
- * hand back the caller's own `$select` map when nothing needs rewriting — an
1465
- * object the caller may share across queries (moost-db memoizes, and in dev /
1466
- * test deep-freezes, the projection of a read without `$select`).
1484
+ * Appends the `$select` `$project` stage, keeping the computed field `keep`
1485
+ * (the geo distance, the vector score) in inclusion mode. That key goes on a
1486
+ * COPY: `asProjection` (and `dedupeProjection`) hand back the caller's own
1487
+ * `$select` map when nothing needs rewriting — an object the caller may share
1488
+ * across queries (moost-db memoizes, and in dev / test deep-freezes, the
1489
+ * projection of a read without `$select`).
1467
1490
  */
1468
- function pushGeoProjection(stages, controls) {
1491
+ function pushProjection(stages, controls, keep) {
1469
1492
  const projection = controls?.$select?.asProjection;
1470
1493
  if (!projection) return;
1471
1494
  const deduped = dedupeProjection(projection);
1472
- const isInclusion = Object.values(deduped).some((v) => v === 1);
1495
+ const isInclusion = keep !== void 0 && Object.values(deduped).some((v) => v === 1);
1473
1496
  stages.push({ $project: isInclusion ? {
1474
1497
  ...deduped,
1475
- [DISTANCE_FIELD]: 1
1498
+ [keep]: 1
1476
1499
  } : deduped });
1477
1500
  }
1478
- /** Renames the internal distance field to the public `$distance` pseudo-field. */
1479
- function renameDistance(row) {
1480
- if (DISTANCE_FIELD in row) {
1481
- row.$distance = row[DISTANCE_FIELD];
1482
- delete row[DISTANCE_FIELD];
1501
+ /** Renames an internal computed field to its public `$`-prefixed name (in place). */
1502
+ function renameComputed(row, field, name) {
1503
+ if (field in row) {
1504
+ row[name] = row[field];
1505
+ delete row[field];
1483
1506
  }
1484
1507
  return row;
1485
1508
  }
@@ -1775,13 +1798,11 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
1775
1798
  };
1776
1799
  }
1777
1800
  /** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
1778
- async function runSearchPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1801
+ async function runSearchPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1779
1802
  const controls = query.controls || {};
1780
1803
  const pipeline = [stage];
1781
- if (threshold !== void 0) {
1782
- pipeline.push({ $addFields: { _score: { $meta: "vectorSearchScore" } } });
1783
- pipeline.push({ $match: { _score: { $gte: threshold } } });
1784
- } else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1804
+ if (vector) pipeline.push(...vectorScoreStages(vector.threshold));
1805
+ else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1785
1806
  pipeline.push(...filterStages ?? require_mongo_accumulator.mongoFilterStages(query.filter, filterOptionsOf(host)));
1786
1807
  const { stages: sorted, cleanup } = require_mongo_accumulator.sortStages(controls);
1787
1808
  if (sorted.length > 0) pipeline.push(...sorted);
@@ -1790,10 +1811,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1790
1811
  if (controls.$limit) pipeline.push({ $limit: controls.$limit });
1791
1812
  else pipeline.push({ $limit: 1e3 });
1792
1813
  if (cleanup) pipeline.push(cleanup);
1793
- if (controls.$select) {
1794
- const projection = controls.$select.asProjection;
1795
- if (projection) pipeline.push({ $project: dedupeProjection(projection) });
1796
- }
1814
+ pushProjection(pipeline, controls, vector ? SCORE_FIELD : void 0);
1797
1815
  host._log(`aggregate (${label})`, pipeline);
1798
1816
  return wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
1799
1817
  }
@@ -1807,22 +1825,17 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1807
1825
  * `count: total` — the same counts `$$SEARCH_META` reports), concurrently
1808
1826
  * outside a transaction.
1809
1827
  */
1810
- async function runSearchWithCountPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1828
+ async function runSearchWithCountPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1811
1829
  const controls = query.controls || {};
1812
1830
  const preStages = [];
1813
- if (threshold !== void 0) {
1814
- preStages.push({ $addFields: { _score: { $meta: "vectorSearchScore" } } });
1815
- preStages.push({ $match: { _score: { $gte: threshold } } });
1816
- } else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1831
+ if (vector) preStages.push(...vectorScoreStages(vector.threshold));
1832
+ else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1817
1833
  const { stages: dataStages, cleanup } = require_mongo_accumulator.sortStages(controls);
1818
1834
  if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
1819
1835
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1820
1836
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1821
1837
  if (cleanup) dataStages.push(cleanup);
1822
- if (controls.$select) {
1823
- const projection = controls.$select.asProjection;
1824
- if (projection) dataStages.push({ $project: dedupeProjection(projection) });
1825
- }
1838
+ pushProjection(dataStages, controls, vector ? SCORE_FIELD : void 0);
1826
1839
  const stages = filterStages ?? require_mongo_accumulator.mongoFilterStages(query.filter, filterOptionsOf(host));
1827
1840
  if ("$search" in stage && preStages.length === 0 && stages.every(isNoopMatch)) return runSearchWithMeta(host, stage, dataStages, label);
1828
1841
  const pipeline = [
package/dist/index.mjs CHANGED
@@ -1367,25 +1367,47 @@ function textRunOptions(plan, query) {
1367
1367
  defaultSort: RELEVANCE_SORT
1368
1368
  } : {};
1369
1369
  }
1370
+ /**
1371
+ * Field the `vectorSearchScore` rides in through the pipeline. Renamed to the
1372
+ * public `$score` after fetch — a field name cannot start with `$`.
1373
+ */
1374
+ const SCORE_FIELD = "__atscript_score";
1370
1375
  /** Vector search via $vectorSearch aggregation stage. */
1371
1376
  async function vectorSearchImpl(host, vector, query, indexName) {
1372
1377
  const controls = query.controls || {};
1373
1378
  const plan = buildVectorSearchPlan(host, vector, query, indexName);
1374
1379
  const threshold = resolveThreshold(host, controls, indexName);
1375
- return runSearchPipeline(host, plan.stage, query, "vectorSearch", {
1376
- threshold,
1380
+ return (await runSearchPipeline(host, plan.stage, query, "vectorSearch", {
1381
+ vector: { threshold },
1377
1382
  filterStages: plan.filterStages
1378
- });
1383
+ })).map((row) => renameComputed(row, SCORE_FIELD, "$score"));
1379
1384
  }
1380
1385
  /** Vector search with faceted count. */
1381
1386
  async function vectorSearchWithCountImpl(host, vector, query, indexName) {
1382
1387
  const controls = query.controls || {};
1383
1388
  const plan = buildVectorSearchPlan(host, vector, query, indexName);
1384
1389
  const threshold = resolveThreshold(host, controls, indexName);
1385
- return runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
1386
- threshold,
1390
+ const result = await runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
1391
+ vector: { threshold },
1387
1392
  filterStages: plan.filterStages
1388
1393
  });
1394
+ return {
1395
+ data: result.data.map((row) => renameComputed(row, SCORE_FIELD, "$score")),
1396
+ count: result.count
1397
+ };
1398
+ }
1399
+ /**
1400
+ * The stages right after `$vectorSearch`: its score into {@link SCORE_FIELD}
1401
+ * (the `$meta` is read here, ahead of any `$facet`) and, with a threshold,
1402
+ * into `_score` — kept for compatibility — with the `$match` on it.
1403
+ */
1404
+ function vectorScoreStages(threshold) {
1405
+ const score = { $meta: "vectorSearchScore" };
1406
+ if (threshold === void 0) return [{ $addFields: { [SCORE_FIELD]: score } }];
1407
+ return [{ $addFields: {
1408
+ _score: score,
1409
+ [SCORE_FIELD]: score
1410
+ } }, { $match: { _score: { $gte: threshold } } }];
1389
1411
  }
1390
1412
  /**
1391
1413
  * Field name `$geoNear` writes the computed distance into. Renamed to the
@@ -1399,9 +1421,9 @@ async function geoSearchImpl(host, point, query, indexName) {
1399
1421
  const pipeline = buildGeoNearStages(host, point, query, indexName);
1400
1422
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
1401
1423
  pipeline.push({ $limit: controls.$limit || 1e3 });
1402
- pushGeoProjection(pipeline, query.controls);
1424
+ pushProjection(pipeline, query.controls, DISTANCE_FIELD);
1403
1425
  host._log("aggregate (geoSearch)", pipeline);
1404
- return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameDistance(row));
1426
+ return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance"));
1405
1427
  }
1406
1428
  /** Geo search with faceted count (rows within the distance window). */
1407
1429
  async function geoSearchWithCountImpl(host, point, query, indexName) {
@@ -1409,7 +1431,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
1409
1431
  const dataStages = [];
1410
1432
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1411
1433
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1412
- pushGeoProjection(dataStages, query.controls);
1434
+ pushProjection(dataStages, query.controls, DISTANCE_FIELD);
1413
1435
  const pipeline = [...buildGeoNearStages(host, point, query, indexName), { $facet: {
1414
1436
  data: dataStages,
1415
1437
  meta: [{ $count: "count" }]
@@ -1417,7 +1439,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
1417
1439
  host._log("aggregate (geoSearchWithCount)", pipeline);
1418
1440
  const result = await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
1419
1441
  return {
1420
- data: (result[0]?.data || []).map((row) => renameDistance(row)),
1442
+ data: (result[0]?.data || []).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance")),
1421
1443
  count: result[0]?.meta?.[0]?.count || 0
1422
1444
  };
1423
1445
  }
@@ -1458,27 +1480,28 @@ function resolveGeoKeyPath(host, indexName) {
1458
1480
  return field;
1459
1481
  }
1460
1482
  /**
1461
- * Appends a `$project` stage, keeping the computed distance in inclusion mode.
1462
- * The distance key goes on a COPY: `asProjection` (and `dedupeProjection`)
1463
- * hand back the caller's own `$select` map when nothing needs rewriting — an
1464
- * object the caller may share across queries (moost-db memoizes, and in dev /
1465
- * test deep-freezes, the projection of a read without `$select`).
1483
+ * Appends the `$select` `$project` stage, keeping the computed field `keep`
1484
+ * (the geo distance, the vector score) in inclusion mode. That key goes on a
1485
+ * COPY: `asProjection` (and `dedupeProjection`) hand back the caller's own
1486
+ * `$select` map when nothing needs rewriting — an object the caller may share
1487
+ * across queries (moost-db memoizes, and in dev / test deep-freezes, the
1488
+ * projection of a read without `$select`).
1466
1489
  */
1467
- function pushGeoProjection(stages, controls) {
1490
+ function pushProjection(stages, controls, keep) {
1468
1491
  const projection = controls?.$select?.asProjection;
1469
1492
  if (!projection) return;
1470
1493
  const deduped = dedupeProjection(projection);
1471
- const isInclusion = Object.values(deduped).some((v) => v === 1);
1494
+ const isInclusion = keep !== void 0 && Object.values(deduped).some((v) => v === 1);
1472
1495
  stages.push({ $project: isInclusion ? {
1473
1496
  ...deduped,
1474
- [DISTANCE_FIELD]: 1
1497
+ [keep]: 1
1475
1498
  } : deduped });
1476
1499
  }
1477
- /** Renames the internal distance field to the public `$distance` pseudo-field. */
1478
- function renameDistance(row) {
1479
- if (DISTANCE_FIELD in row) {
1480
- row.$distance = row[DISTANCE_FIELD];
1481
- delete row[DISTANCE_FIELD];
1500
+ /** Renames an internal computed field to its public `$`-prefixed name (in place). */
1501
+ function renameComputed(row, field, name) {
1502
+ if (field in row) {
1503
+ row[name] = row[field];
1504
+ delete row[field];
1482
1505
  }
1483
1506
  return row;
1484
1507
  }
@@ -1774,13 +1797,11 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
1774
1797
  };
1775
1798
  }
1776
1799
  /** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
1777
- async function runSearchPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1800
+ async function runSearchPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1778
1801
  const controls = query.controls || {};
1779
1802
  const pipeline = [stage];
1780
- if (threshold !== void 0) {
1781
- pipeline.push({ $addFields: { _score: { $meta: "vectorSearchScore" } } });
1782
- pipeline.push({ $match: { _score: { $gte: threshold } } });
1783
- } else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1803
+ if (vector) pipeline.push(...vectorScoreStages(vector.threshold));
1804
+ else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1784
1805
  pipeline.push(...filterStages ?? mongoFilterStages(query.filter, filterOptionsOf(host)));
1785
1806
  const { stages: sorted, cleanup } = sortStages(controls);
1786
1807
  if (sorted.length > 0) pipeline.push(...sorted);
@@ -1789,10 +1810,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1789
1810
  if (controls.$limit) pipeline.push({ $limit: controls.$limit });
1790
1811
  else pipeline.push({ $limit: 1e3 });
1791
1812
  if (cleanup) pipeline.push(cleanup);
1792
- if (controls.$select) {
1793
- const projection = controls.$select.asProjection;
1794
- if (projection) pipeline.push({ $project: dedupeProjection(projection) });
1795
- }
1813
+ pushProjection(pipeline, controls, vector ? SCORE_FIELD : void 0);
1796
1814
  host._log(`aggregate (${label})`, pipeline);
1797
1815
  return wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
1798
1816
  }
@@ -1806,22 +1824,17 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1806
1824
  * `count: total` — the same counts `$$SEARCH_META` reports), concurrently
1807
1825
  * outside a transaction.
1808
1826
  */
1809
- async function runSearchWithCountPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1827
+ async function runSearchWithCountPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1810
1828
  const controls = query.controls || {};
1811
1829
  const preStages = [];
1812
- if (threshold !== void 0) {
1813
- preStages.push({ $addFields: { _score: { $meta: "vectorSearchScore" } } });
1814
- preStages.push({ $match: { _score: { $gte: threshold } } });
1815
- } else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1830
+ if (vector) preStages.push(...vectorScoreStages(vector.threshold));
1831
+ else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1816
1832
  const { stages: dataStages, cleanup } = sortStages(controls);
1817
1833
  if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
1818
1834
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1819
1835
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1820
1836
  if (cleanup) dataStages.push(cleanup);
1821
- if (controls.$select) {
1822
- const projection = controls.$select.asProjection;
1823
- if (projection) dataStages.push({ $project: dedupeProjection(projection) });
1824
- }
1837
+ pushProjection(dataStages, controls, vector ? SCORE_FIELD : void 0);
1825
1838
  const stages = filterStages ?? mongoFilterStages(query.filter, filterOptionsOf(host));
1826
1839
  if ("$search" in stage && preStages.length === 0 && stages.every(isNoopMatch)) return runSearchWithMeta(host, stage, dataStages, label);
1827
1840
  const pipeline = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-mongo",
3
- "version": "0.1.182",
3
+ "version": "0.1.183",
4
4
  "description": "Mongodb plugin for atscript.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -58,7 +58,7 @@
58
58
  "@atscript/typescript": "^0.2.13",
59
59
  "@uniqu/core": "^0.2.2",
60
60
  "mongodb": "^6.17.0",
61
- "@atscript/db": "^0.1.182"
61
+ "@atscript/db": "^0.1.183"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "vp pack",