Skip to content

feat(#10685): db.index.vector.queryNodes takes an optional {where, filter} pre-filter (#10808) [skip ci] - #10808

Merged
robfrank merged 5 commits into
mainfrom
feat/10685-cypher-querynodes-filter-argument
Oct 28, 2026
Merged

robfrank merged 5 commits into
mainfrom
feat/10685-cypher-querynodes-filter-argument

Conversation

@robfrank

@robfrank robfrank commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #10685

db.index.vector.queryNodes(index, k, vector) (the Neo4j-compatible form) had no filter, so a tenant or property filter could only be applied after its top k: a query whose nearest neighbours belong to another tenant answered fewer rows than asked, or none. The procedure now takes an optional fourth argument, an options map carrying the same pre-filter vector.neighbors takes, tested by the index as it meets each candidate:

CALL db.index.vector.queryNodes('Fact[embedding]', 10, $q, {where: {tenant: $tenant}}) YIELD node, score
CALL db.index.vector.queryNodes('Fact[embedding]', 10, $q, {where: 'tenant = :tenant'}) YIELD node, score
CALL db.index.vector.queryNodes('Fact[embedding]', 10, $q, {filter: allowedNodesOrRids}) YIELD node, score

The option parsing is shared: SQLFunctionVectorAbstract.parsePreFilter(filter, where, ...) is now what both vector.neighbors and queryNodes call, so the two cannot drift.

Finding ledger

  1. Docs sentence pointing queryNodes users to the pre-filtered form - out of this repo (docs live in ArcadeData/arcadedb-docs); follow-up drafted but not filed (filing in the docs repo was not permitted in this run), see Known gaps
  2. Optional fourth argument mapping to the same pre-filter - fixed here

Completeness

Invariant: every Cypher k-NN entry point that answers k rows can restrict its candidates during the search, not only after it.

Entry point Status
CALL db.index.vector.queryNodes(idx, k, v, {where}) (map) fixed here, tested
CALL db.index.vector.queryNodes(idx, k, v, {where: 'cond :param'}) fixed here, tested
CALL db.index.vector.queryNodes(idx, k, v, {filter}) (collected nodes / RID strings) fixed here, tested
filter + where together fixed here, tested
CALL vector.neighbors(..., {where/filter}) already pre-filtered (#10169); now reads the options through the shared helper, existing tests green
Bolt goes through the same Cypher procedure, no separate path
db.index.vector.queryRelationships does not exist (only the full-text one does), nothing to cover

Test plan

  • Issue10685VectorQueryNodesPreFilterTest (12 tests): the issue's data (900 tenant-b vectors all nearer than 100 tenant-a ones, k = 10); the 3-arg post-filter still answers 0 rows; each pre-filter form answers 10 rows, all tenant a; combined filter+where; a parent-type spec with several sub-indexes (sub-type); a pre-filter matching fewer than k (k = 200 answers exactly the 100 of tenant a); an empty filter and a where matching nothing; {}/null; unknown option and non-map options rejected as CommandSQLParsingException
  • Proven able to fail: with allowedRIDs not passed to findNeighbors, 4 of the original 9 fail
  • Related suites green (187 tests): *VectorQueryNodes*, CypherCallVectorNeighborsTest, *VectorNeighbors*, Issue10169*, Issue9858*, Issue10514*, Issue9896*, Issue7862*, CypherProcedureRegistryTest, LSMVectorIndex* ordering/parent-type

Coverage

Entry points covered: see the Completeness table above.

Known gaps

  • Docs (ArcadeData/arcadedb-docs, reference/cypher/cypher-clauses.adoc / concepts/vector-search.adoc): say that the 3-argument queryNodes filters after the top-k and show the fourth argument and CALL vector.neighbors(..., {where}) as the pre-filtered forms, plus the multi-tenant vector.fuse example from the issue comment. Unfiled - the docs-repo issue could not be created from this run; needs a manual follow-up.

Adversarial pass

Not run: no subagent tool was available in this session to spawn the independent reviewer.

Review cycles

Cycle Head Changes claude review
1 1cedb4d initial LGTM with nits: tighter exception assertions, a where matching fewer than k, field alignment -> applied
2 3bbbe37 exception type/message asserted, fewer-than-k test, alignment no blocking: rename the private reader, a multi-index test -> applied
3 f58009a parsePreFilter (private) renamed parseOptions, sub-type/multi-index test LGTM: a where matching nothing -> applied
4 89f6573 where-matching-nothing test "looks good to merge once CI is green", nits only (below)

Deferred / skipped items

  • "The Javadoc has a stray </p> after the <pre> block" (cycles 1, 2, 4): skipped. The paragraph is opened with <p> and closed once after the <pre>, the same shape as the class Javadoc block right above it (the reviewer notes the original has it too); no doclint failure.
  • "allowedRIDs ... reused across stale top-up iterations ... confirm it carries no per-search state" (cycle 1): no change. RecordPredicateRidSet only memoizes each RID's verdict (decided), which is deterministic within the statement; vector.neighbors reuses the same set across its top-up passes the same way. Covered by preFilterMatchingFewerThanKAnswersEveryMatch.
  • "searchAndLoad now takes 8 parameters" (cycle 3): skipped, optional.
  • "parseOptions runs before the query vector is extracted" (cycle 4): skipped. The where side is lazy (tested per candidate); only a filter list is materialized, which is the caller's own list, and checking options before the vector matches vector.neighbors.
  • "Consider one test that goes through Bolt or a server" (cycle 4): skipped. Bolt dispatches to the same Cypher procedure with the same parameter map; no protocol-specific code changed.
  • Docs follow-up in ArcadeData/arcadedb-docs (every cycle): still unfiled, creating the issue in the docs repo was denied in this run. Needs a manual follow-up.

Final state

clean-approval (cycle 4 of 4: only non-blocking nits, none applied).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Vector node queries now accept an optional options map with where conditions, record filters, or both to limit results before nearest-neighbor selection.
    • When the options match no records, the query returns no results. Empty or omitted options leave the search unfiltered.
    • Vector neighbor searches also support applying where conditions and record filters together.

…lter} pre-filter

The Neo4j-compatible three-argument form can only be filtered after its top k,
so a tenant whose records are not the nearest got fewer rows than asked, or
none. An optional fourth options map now carries the same where/filter
pre-filter vector.neighbors takes, tested by the index during the search.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1e9b1b2d-0c3d-46d8-a02e-b5787230a9f7
Commits

Reviewing files that changed from the base of the PR and between f8ae3a8 and 89f6573.

Files selected for processing: 4
  • engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorAbstract.java
  • engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorNeighbors.java
  • engine/src/main/java/com/arcadedb/query/opencypher/procedures/db/DbIndexVectorQueryNodes.java
  • engine/src/test/java/com/arcadedb/query/opencypher/Issue10685VectorQueryNodesPreFilterTest.java

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

Walkthrough

The Cypher db.index.vector.queryNodes procedure now accepts an optional fourth options map with where and filter pre-filters. The SQL vector-neighbor function uses a shared helper to combine those options. Tests cover filtering results, empty options, and invalid options.

Changes: Vector query pre-filters

Layer / File(s) Summary
Shared pre-filter parsing
engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorAbstract.java, engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorNeighbors.java
A shared helper combines RID filters with a where predicate. SQL vector neighbors now use this helper.
Cypher query options and index search
engine/src/main/java/com/arcadedb/query/opencypher/procedures/db/DbIndexVectorQueryNodes.java, engine/src/test/java/com/arcadedb/query/opencypher/Issue10685VectorQueryNodesPreFilterTest.java
queryNodes accepts an optional fourth options map and passes allowed RIDs to vector-index searches. Tests cover pre-filter behavior, three-argument behavior, empty or missing options, and invalid options.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant CypherCaller
  participant DbIndexVectorQueryNodes
  participant SQLFunctionVectorAbstract
  participant VectorIndex
  CypherCaller->>DbIndexVectorQueryNodes: call queryNodes with options
  DbIndexVectorQueryNodes->>SQLFunctionVectorAbstract: parse where and filter options
  SQLFunctionVectorAbstract-->>DbIndexVectorQueryNodes: return allowed RIDs
  DbIndexVectorQueryNodes->>VectorIndex: search with allowed RIDs
  VectorIndex-->>DbIndexVectorQueryNodes: return matching neighbors
  DbIndexVectorQueryNodes-->>CypherCaller: return query rows
Loading

Possibly related issues

  • ArcadeData/arcadedb#10782 — This change adds pre-filtering to queryNodes, but does not change the SEARCH limit behavior described in the issue.

Suggested reviewers: lvca

Merge Risk: Minimal · up to 89f65

The new vector pre-filter options have no identified merge-blocking issue; the change is ready for normal merge checks.

Pre-merge checks: Passed 4
Check name Status Explanation
Description check Passed The description provides the change summary, motivation, related issue, implementation details, test coverage, limitations, and known gaps. It does not use all template headings and does not confirm t…
Linked Issues check Passed Issue #10685 asks for one of two changes: a Cypher docs note that points users to the pre-filtered form, or an optional fourth argument on db.index.vector.queryNodes that maps to the same pre-filter. …
Out of Scope Changes check Passed The diff from merge base 491dfa9 to head 89f6573 touches four production or test areas, all tied to #10685. (1) SQLFunctionVectorAbstract gains public static parsePreFilter(...). It is a thin wr…
Title check Passed The title clearly identifies the main change: adding an optional {where, filter} pre-filter to db.index.vector.queryNodes.
Full details: Description check

Explanation

The description provides the change summary, motivation, related issue, implementation details, test coverage, limitations, and known gaps. It does not use all template headings and does not confirm the mvn clean package checklist item, but it contains the required review information overall.

Full details: Linked Issues check

Explanation

Issue #10685 asks for one of two changes: a Cypher docs note that points users to the pre-filtered form, or an optional fourth argument on db.index.vector.queryNodes that maps to the same pre-filter. The issue states that either option would help. This PR implements the second option. At head 89f6573, DbIndexVectorQueryNodes.getMaxArgs() returns 4. The execute path parses args[3] through parseOptions(), which accepts only the keys where and filter (OPTIONS = {where, filter}). It rejects a non-map value with CommandSQLParsingException. It passes filter and where to SQLFunctionVectorAbstract.parsePreFilter(), which wraps RecordPredicateRidSet.of(...) and parseRidFilter(...). A null or empty result from the options returns Stream.empty() when the set is empty, and the set is passed as allowedRIDs to findNeighbors on each index search. The three-argument form still passes null, so its behavior is unchanged. The PR also adds Issue10685VectorQueryNodesPreFilterTest. I did not open the test file, so the test claims rest on the PR description and the summary. The docs follow-up is not filed. The issue does not require it once the code option is implemented.

Full details: Out of Scope Changes check

Explanation

The diff from merge base 491dfa9 to head 89f6573 touches four production or test areas, all tied to #10685. (1) SQLFunctionVectorAbstract gains public static parsePreFilter(...). It is a thin wrapper over the existing RecordPredicateRidSet.of and parseRidFilter, and it is the shared helper that the new queryNodes option needs. (2) SQLFunctionVectorNeighbors.execute now calls parsePreFilter instead of two separate calls. The diff is +1/-4 with the same behavior. The change keeps vector.neighbors and queryNodes on one code path, which the issue's pre-filter goal supports. (3) DbIndexVectorQueryNodes gains the fourth argument, its option parsing, and Javadoc. This is the requested change. (4) Issue10685VectorQueryNodesPreFilterTest adds coverage for the new behavior. No unrelated file or subsystem changes appear in the reviewed evidence.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@claude

claude Bot commented Oct 27, 2026

Copy link
Copy Markdown

Review of #10808

Summary: This is a clean, well-scoped change. The shared parsePreFilter helper stops vector.neighbors and queryNodes from drifting apart. The three-argument form is unchanged. I found no blocking issues, and nothing here looks like a security hazard.

Security

  • The where SQL condition goes through the same RecordPredicateRidSet path that vector.neighbors already uses. It adds no new injection surface, and parameters are bound by name.
  • Unknown option keys and non-map options are rejected by name, which is good strictness.

Correctness

Minor / style

  • The Javadoc has a stray </p> after the <pre> block, so the <p> is closed twice.
  • In the test, the field alignment on K, QUERY and PARAMS is uneven. This is cosmetic.
  • unknownOptionIsRejectedByName and optionsThatAreNotAMapAreRejected assert with hasStackTraceContaining. Asserting the exception type (CommandSQLParsingException or the wrapped cause) would be tighter.
  • Consider a test with a where that matches fewer than k rows, to cover the stale top-up and saturation interplay. A test with filter as Cypher nodes combined with a multi-index type would also help.

Performance: There is no overhead on the unfiltered path, because null is passed as before.

Docs: The follow-up in arcadedb-docs is still needed, as the PR notes. Please file it before merging.

Overall: LGTM, with the minor nits above.

@codacy-production

codacy-production Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 9 complexity

Metric Results
Complexity 9

View in Codacy

🟢 Coverage 87.50% diff coverage · -4.69% coverage variation

Metric Results
Coverage variation ✅ -4.69% coverage variation
Diff coverage ✅ 87.50% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (ff58245) 252708 220311 87.18%
Head commit (fe25a74) 285882 (+33174) 235824 (+15513) 82.49% (-4.69%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#10808) 24 21 87.50%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@mergify

mergify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

…lter matching fewer than k

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@claude

claude Bot commented Oct 27, 2026

Copy link
Copy Markdown

Review of #10808: no blocking issues found.

What looks good

  • The pre-filter parsing now lives in one place, SQLFunctionVectorAbstract.parsePreFilter. vector.neighbors and queryNodes both call it, so the two can't drift apart.
  • The three-argument form is unchanged. null and {} fall back to it.
  • Unknown keys and non-map options are rejected by name.
  • An empty filter returns an empty stream before the vector is extracted, which matches the vector.neighbors: a filter that matches no records is treated as no filter, so the search returns records outside it (a tenant subquery with no rows returns other tenants' records) #8959 contract.
  • allowedRIDs is applied inside findNeighbors, so the index tests candidates during the search rather than on the top k.
  • I found no security concerns. where goes through the existing RecordPredicateRidSet, with named parameters bound from the context.
  • The new test class covers the issue's scenario and each option form. It follows the project's AssertJ style and uses no fixed ports or wall-clock assertions.
  • I read the diff only. I didn't build the PR or run the tests, so the PR's own test results are unverified here.

Minor points (non-blocking)

  1. The new Javadoc block in DbIndexVectorQueryNodes ends with a stray </p> after the <pre>. The </p> that follows the earlier example already has the same shape, so this only matters if you run strict doclint.
  2. The two parsePreFilter overloads (the static helper in the abstract class and the private one in DbIndexVectorQueryNodes) share a name. Renaming the private one, for example to parseOptions, would make call sites easier to read.
  3. It would be worth a test where where is combined with filter over a multi-index spec, i.e. several indexes resolved by resolveVectorIndexes. The shared allowedRIDs set is passed to every index, which should be fine, but nothing covers it.
  4. The docs follow-up in arcadedb-docs is still unfiled, as the PR notes. Please file it before merge so it isn't lost.

Overall this is a clean, focused change.

…a parent spec with several sub-indexes

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@claude

claude Bot commented Oct 27, 2026

Copy link
Copy Markdown

Review

Overall this is a clean, well-scoped change. I found no blocking issues and no security hazards.

What looks good

  • Reusing one parsing path (SQLFunctionVectorAbstract.parsePreFilter) for vector.neighbors and queryNodes keeps the two from drifting.
  • FunctionOptions with an allow-list rejects unknown keys by name, and a non-map argument is rejected.
  • The empty-set contract from vector.neighbors: a filter that matches no records is treated as no filter, so the search returns records outside it (a tenant subquery with no rows returns other tenants' records) #8959 is honoured by returning Stream.empty(). The options are parsed after the index is resolved, so a bad index spec still fails loudly.
  • The three-argument form is unchanged, and null/{} map to it.
  • Security: where as a SQL condition goes through the same RecordPredicateRidSet path as vector.neighbors, and values come in as named parameters. This adds no new injection surface beyond what that function already has.
  • Performance: the filter is tested inside the index search, with no extra materialisation beyond what neighbors already does.

Minor suggestions (non-blocking)

  1. The PR description says 9 tests, but the test class has 12. Consider updating the description.
  2. searchAndLoad now takes 8 parameters. It's still readable, but a small holder for staleSkipped/saturated/guard could help if it grows further.
  3. The stale top-up loop re-runs the search with a larger fetchK using the same allowedRIDs. preFilterMatchingFewerThanKAnswersEveryMatch covers this, so I think it's fine.
  4. It might be worth a test where where matches nothing (not only filter: []). That would pin the empty-set contract for the predicate path too.
  5. The docs follow-up in arcadedb-docs still needs filing.

LGTM from my side. I didn't run the tests locally.

@claude

claude Bot commented Oct 27, 2026

Copy link
Copy Markdown

Review of #10808

The change is small and well scoped. It reuses the vector.neighbors pre-filter through the shared parsePreFilter helper, so the two entry points can't drift. The three-argument form is unchanged. Unknown keys and non-map options are rejected by name, and an empty filter answers no rows (#8959). I found no security concerns: where goes through the same RecordPredicateRidSet path that vector.neighbors already uses, so this adds no new injection surface.

I read the diff only and did not build or run the tests.

Minor points, none blocking:

  • The PR description says 9 tests, but the class has 12.
  • The Javadoc in DbIndexVectorQueryNodes has a stray </p> after the closing </pre> in the new paragraph. The original block has the same shape, but it is worth tidying.
  • parseOptions runs before the query vector is extracted. If the where / filter evaluation is costly for a large filter list, a bad vector fails only after that work. This is an edge case.
  • Consider one test that goes through Bolt or a server with a parameter map. Other modules don't need to change, since the procedure is shared.

Overall this looks good to merge once CI is green.

@codecov

codecov Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.33333% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.12%. Comparing base (ff58245) to head (fe25a74).
⚠️ Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
...ncypher/procedures/db/DbIndexVectorQueryNodes.java 81.81% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main   #10808      +/-   ##
============================================
+ Coverage     79.09%   79.12%   +0.03%     
+ Complexity     4827     4823       -4     
============================================
  Files          2305     2307       +2     
  Lines        252708   253055     +347     
  Branches      55209    55305      +96     
============================================
+ Hits         199869   200223     +354     
+ Misses        32437    32395      -42     
- Partials      20402    20437      +35     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Conflict in DbIndexVectorQueryNodes: main (#10776, #10782) moved the k-NN search
into the static search(indexSpec, k, vector, Predicate<Document> filter, context,
caller) shared with the Cypher 25 SEARCH clause, which turns the predicate into
the index allow-list through RecordPredicateRidSet.matching; this branch parsed
the optional {where, filter} options map inside execute() into the same kind of
allow-list (SQLFunctionVectorAbstract.parsePreFilter).

Resolution keeps one search path: the public search(...) signature used by
VectorSearchClauseProcedure is unchanged and delegates to a private overload that
also takes the options map. The options are still parsed after the index is
resolved (a bad index spec stays loud) and an empty filter still answers no rows
(#8959). Either pre-filter becomes the allow-list handed to findNeighbors; both
together intersect. extractLimit keeps main's caller-aware messages, the imports
keep both FunctionOptions and RecordPredicateRidSet, and the allow-list assertion
message no longer names only the SEARCH clause.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@claude

claude Bot commented Oct 28, 2026

Copy link
Copy Markdown

Review of #10808: no blocking issues found.

What looks good

Minor suggestions (non-blocking)

  1. When both the options and the SEARCH predicate are present, RecordPredicateRidSet.matching(record -> optionRIDs.contains(record.getIdentity()) && filter.test(record), ...) is used. If optionRIDs is itself a lazy predicate set (where), contains may load the record a second time per candidate. That's fine for correctness. If it shows up in profiles, consider composing the predicates once.
  2. There's no test for the combined case of the 4th argument plus the SEARCH clause predicate (openCypher SEARCH: an inner WHERE that rejects the 100k nearest candidates answers fewer than LIMIT rows #10782), which is the new branch in search. A small regression test would lock it in.
  3. The docs follow-up lives in arcadedb-docs. Please make sure an issue gets filed there.

No security hazards found.

@robfrank robfrank changed the title feat(#10685): db.index.vector.queryNodes takes an optional {where, filter} pre-filter feat(#10685): db.index.vector.queryNodes takes an optional {where, filter} pre-filter (#10808) [skip ci] Oct 28, 2026
@robfrank
robfrank merged commit 81c3012 into main Oct 28, 2026
31 of 32 checks passed
robfrank added a commit that referenced this pull request Nov 5, 2026
…lter} pre-filter (#10808) [skip ci]

(cherry picked from commit 81c3012)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cypher: db.index.vector.queryNodes filters only after the top-k; point users to vector.neighbors with where/filter (docs), or accept a filter argument

1 participant