Skip to content

Perf: push metadata filters down to Elasticsearch - #14576

Merged
yingfeng merged 5 commits into
infiniflow:mainfrom
sxxtony:fix/14412-meta-filter-es-pushdown
May 7, 2026
Merged

yingfeng merged 5 commits into
infiniflow:mainfrom
sxxtony:fix/14412-meta-filter-es-pushdown

Conversation

@sxxtony

@sxxtony sxxtony commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #14412.

common.metadata_utils.meta_filter evaluates user-defined metadata conditions in Python after DocMetadataService.get_flatted_meta_by_kbs loads the entire meta_fields table into memory. Past a few thousand documents per knowledge base this becomes a memory bottleneck and a wasted ES round-trip — every filter request currently fetches up to 10000 metadata rows even when the resulting doc_ids list is tiny.

This PR adds an ES push-down path that translates the same filter language into a bool query and returns just the matching document IDs.

Changes

  • common/metadata_es_filter.py (new): pure-Python translator from the RAGflow filter list to ES DSL. Covers every operator the in-memory path supports (=, ≠, >, <, ≥, ≤, in, not in, contains, not contains, start with, end with, empty, not empty) with case_insensitive: true on prefix and wildcard for parity with the existing lower-cased Python comparisons. User wildcard metacharacters are escaped before being injected into wildcard patterns. Negative operators (≠, not in, not contains, ranges) are wrapped with an exists guard so they do not accidentally match documents missing the key, matching the legacy if k not in metas behaviour.
  • api/db/services/doc_metadata_service.py: new DocMetadataService.filter_doc_ids_by_meta_pushdown(kb_ids, filters, logic) that returns the doc IDs ES matched, or None to signal the caller should fall back to the in-memory path. Returns None when the active doc store is Infinity (meta_fields is a JSON column, not a dotted-object mapping), when any filter cannot be expressed in DSL (UnsupportedMetaFilter), or when the ES request or metadata index lookup errors.
  • common/metadata_utils.py: apply_meta_data_filter accepts an optional kb_ids argument. When supplied, conditions go through push-down first via a new _try_meta_pushdown helper; on None the function falls back to the original meta_filter call. Default behaviour is unchanged for callers that don't pass kb_ids.
  • Updated all four callers (agent/tools/retrieval.py, api/db/services/dialog_service.py ×2, api/apps/services/dataset_api_service.py, api/apps/sdk/session.py) to forward kb_ids so the push-down path is exercised in production.
  • test/unit_test/common/test_metadata_es_filter.py (new): 35 unit tests covering every operator's DSL shape, value coercion (ast.literal_eval, lowercasing, ISO-date pass-through), wildcard escaping, OR-logic wrapping that protects negative clauses, and the doc-ID extractor.

Behaviour preserved

  • The in-memory meta_filter is untouched and still services every fallback case (Infinity backend, unknown operators, ES outages).
  • The eligibility / credibility / issue-multiplier semantics described in the LLM-driven auto and semi_auto modes still hand the LLM the full in-memory metas dict to choose conditions from. Only the evaluation of those generated conditions is pushed down.
  • Existing tests in test/unit_test/common/test_metadata_filter_operators.py continue to pass (14/14).

Test plan

  • pytest test/unit_test/common/test_metadata_es_filter.py — 35 passed.
  • pytest test/unit_test/common/test_metadata_filter_operators.py — 14 passed.
  • ruff check clean on every modified file.
  • Reviewer please validate the ES query shapes against a live cluster — particularly case_insensitive on wildcard and prefix (requires ES 7.10+) and the exists + must_not pairing for ≠.

Notes

  • The first cut caps each push-down request at 10000 results, matching the existing get_flatted_meta_by_kbs limit, and logs a warning when the cap is hit. A search_after follow-up would let us drop the cap entirely once the push-down path is validated.
  • Operator parity with the in-memory path is exact for the canonical unicode operators (≥, ≤, ≠) used internally; the ASCII aliases (>=, <=, !=) are normalised by convert_conditions before they reach the translator.

Type of change

  • Performance Improvement

The meta_filter helper has been loading every document's metadata into
memory and applying user conditions in Python, which doesn't scale once
a knowledge base grows past a few thousand documents (issue infiniflow#14412).

Add common/metadata_es_filter.py — a translator from RAGflow's filter
list into Elasticsearch bool DSL — and a new
DocMetadataService.filter_doc_ids_by_meta_pushdown method that runs the
translated query against ES and returns just the matching doc IDs.
apply_meta_data_filter now tries the push-down first when callers pass
kb_ids, falling back to the existing in-memory meta_filter whenever the
backend isn't ES, the operator can't be expressed, or the request fails.

Fixes infiniflow#14412
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 5, 2026
@coderabbitai

coderabbitai Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5b9d48b3-7520-4d31-ac4b-4a4c9b8883af

📥 Commits

Reviewing files that changed from the base of the PR and between 2c1ab82 and 7a053e8.

📒 Files selected for processing (1)
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
✅ Files skipped from review due to trivial changes (1)
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py

📝 Walkthrough

Walkthrough

Metadata-filter evaluation now attempts Elasticsearch push-down: new translator and pushdown planner translate filters to ES DSL; DocMetadataService can run pushdown queries; apply_meta_data_filter accepts kb_ids and a lazy metas_loader, trying ES pushdown and falling back to in-memory filtering. Call sites updated to pass kb_ids and metas_loader.

Changes

Elasticsearch Push-Down Metadata Filtering

Layer / File(s) Summary
Filter translation primitives
common/metadata_es_filter.py
New module translating RAGflow metadata filter dicts into Elasticsearch bool-query DSL; defines supported operators, coercion helpers, UnsupportedMetaFilter, TranslatedFilter, MetaFilterPushdownPlan, MetaFilterTranslator, plan_pushdown, build_meta_filter_query, is_pushdown_supported, and extract_doc_ids.
ES pushdown execution
api/db/services/doc_metadata_service.py
Added filter_doc_ids_by_meta_pushdown(kb_ids, filters, logic, limit) which builds/runs ES queries using the translator, extracts/de-duplicates doc IDs, returns None to signal fallback or [] for missing index.
Filtering runtime & lazy metas
common/metadata_utils.py
apply_meta_data_filter signature extended with kb_ids and metas_loader; adds memoized _get_metas(), _evaluate() (attempts _try_meta_pushdown then falls back to in-memory meta_filter), and _try_meta_pushdown() that lazy-imports DocMetadataService. Modes (auto, semi_auto, manual) now route through _evaluate().
Call-site integration (lazy metadata)
agent/tools/retrieval.py, api/apps/sdk/session.py, api/apps/services/dataset_api_service.py, api/db/services/dialog_service.py
Call sites changed to stop eager metadata loading and instead pass kb_ids and a metas_loader lambda into apply_meta_data_filter.
Unit tests for translation & extractors
test/unit_test/common/test_metadata_es_filter.py
Extensive tests added validating per-operator translation, coercion, negation semantics, AND/OR plan composition, pushdown pre-checks, and extract_doc_ids behavior.
Test helper adaptation
test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
Test helper _apply_filter updated to accept kwargs and assert kb_ids propagation to mocked apply_meta_data_filter.
sequenceDiagram
    participant Client
    participant MetadataUtils as apply_meta_data_filter
    participant Pushdown as _try_meta_pushdown
    participant Service as DocMetadataService
    participant ES as Elasticsearch

    Client->>MetadataUtils: apply_meta_data_filter(conditions, kb_ids, metas_loader, ...)
    MetadataUtils->>Pushdown: _evaluate(conditions, logic, kb_ids)
    alt kb_ids present AND plan pushdownable
        Pushdown->>Service: filter_doc_ids_by_meta_pushdown(kb_ids, conditions)
        alt pushdown supported
            Service->>ES: search(translated ES DSL)
            ES-->>Service: hits (doc ids)
            Service-->>Pushdown: List[str] doc IDs
            Pushdown-->>MetadataUtils: doc IDs
        else pushdown unsupported or failed
            Service-->>Pushdown: None
            Pushdown->>MetadataUtils: fallback -> meta_filter(metas_loader())
        end
    else fallback
        Pushdown->>MetadataUtils: meta_filter(metas_loader())
    end
    MetadataUtils-->>Client: filtered doc IDs or sentinel
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

size:L, 🧪 test, 🐖api

Poem

🐇
I hop through code with nimble cheer,
I push filters down so searches steer.
Lazy loaders wake when asked,
ES finds IDs — no longer tasked.
A rabbit grin — results appear!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.20% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Perf: push metadata filters down to Elasticsearch' accurately and specifically summarizes the main change: implementing ES push-down for metadata filtering to improve performance.
Description check ✅ Passed The description is well-structured and covers all required template sections: it explains the problem solved, provides detailed implementation changes, preserves existing behavior, includes test coverage, and specifies the type of change (Performance Improvement).
Linked Issues check ✅ Passed The PR fully addresses issue #14412's requirements: translates filter conditions to ES DSL, returns matched doc IDs, preserves in-memory fallback for unsupported cases, maintains filter semantics, and ensures auto/semi_auto modes receive full metas for condition generation.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the ES push-down metadata filtering feature. No unrelated refactoring, dependency updates, or out-of-scope modifications are present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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 and usage tips.

@dosubot dosubot Bot added the python Pull requests that update python code label May 5, 2026
@sxxtony sxxtony changed the title Push metadata filters down to Elasticsearch instead of filtering in memory Perf: push metadata filters down to Elasticsearch May 5, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
common/metadata_utils.py (1)

166-209: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Make metas lazy or optional here.

This function now advertises ES pushdown, but its contract still forces every caller to build metas first. In the updated flows, manual filters still do get_flatted_meta_by_kbs(...) before _try_meta_pushdown() runs, so the full metadata table is still loaded and flattened even when pushdown succeeds. That keeps the original memory/latency bottleneck on the hot path this PR is trying to remove.

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@common/metadata_es_filter.py`:
- Around line 105-112: to_clauses() currently returns multiple top-level clauses
for a single positive filter which lets parts of that filter be OR'ed
independently; change it so a filter always yields a single atomic clause when
it will be OR'd by the parent. Specifically, update to_clauses() (and the
analogous code at the 136–147 block) so that when self.must is non-empty and the
parent logic is OR (i.e. when the caller will put these into a parent "should"),
you wrap the must list into a single {"bool": {"must": [...]} } entry instead of
returning list(self.must); also ensure the negative-case wrap remains as
{"bool": {"must": list(self.must), "must_not": list(self.must_not)}}. This keeps
each translated filter atomic when to_query() flattens into parent should.

In `@common/metadata_utils.py`:
- Around line 203-209: The ES push-down in _evaluate incorrectly sends negative
operators (≠, not in, not contains) to _try_meta_pushdown when the metadata key
may be multi-valued, producing different results than meta_filter; change
_evaluate to detect any negative operators in the incoming conditions and only
call _try_meta_pushdown for those conditions when you can prove the target key
is single-valued (use the available metas/kb metadata or the same single-valued
check used by get_flatted_meta_by_kbs); otherwise fall back to meta_filter for
those conditions. Apply the same guard to the other affected block (around the
247-267 logic) so negative filters are never pushed into must_not unless the
field is known single-valued.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bf2dfa1d-9c7b-447d-b437-ddf3a379eda8

📥 Commits

Reviewing files that changed from the base of the PR and between 3a51c27 and b308702.

📒 Files selected for processing (8)
  • agent/tools/retrieval.py
  • api/apps/sdk/session.py
  • api/apps/services/dataset_api_service.py
  • api/db/services/dialog_service.py
  • api/db/services/doc_metadata_service.py
  • common/metadata_es_filter.py
  • common/metadata_utils.py
  • test/unit_test/common/test_metadata_es_filter.py

Comment thread common/metadata_es_filter.py Resolved
Comment thread common/metadata_utils.py Resolved
Three correctness/perf fixes from infiniflow#14576 review:

1. Lazy-load `metas` via a new optional `metas_loader` callable so
   manual filters served by ES push-down skip the full
   `get_flatted_meta_by_kbs` round-trip — the original bottleneck. Auto
   and semi_auto modes still materialise `metas` because the LLM needs
   it; the in-memory fallback also still materialises on demand.
2. `TranslatedFilter.to_clauses()` now wraps multi-clause positive
   filters in a single `bool: must` so an OR-logic parent `should`
   cannot match on just one half (e.g. range = `exists` + `range`
   previously could have leaked the `exists` branch).
3. Reject `≠` and `not in` from push-down (`is_pushdown_supported`).
   These diverge from `meta_filter` on multi-valued metadata fields:
   in-memory checks per value bucket, while `must_not term` excludes
   any doc with the term at all. Without a cheap field-cardinality
   probe at query time, the only correct answer is in-memory fallback.
   `not contains` is unaffected — `all(not contains)` ≡
   `not any(contains)` so its push-down stays correct.

Tests updated for the new range wrap shape; new tests added for
push-down rejection of multi-value-unsafe negatives and OR-atomicity.
54/54 unit tests pass.
@sxxtony

sxxtony commented May 5, 2026

Copy link
Copy Markdown
Contributor Author

@euvre Could you please review and add any feedbacks?

@yingfeng
yingfeng requested a review from qinling0210 May 6, 2026 02:06

@qinling0210 qinling0210 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please test to make sure your change works.

Based on my test, apply_meta_data_filter() does not return the doc ids containing the requested meta data when we use Elasticsearch

The dynamic mapping under meta_fields indexes string values as text with a
.keyword multi-field. term/terms/prefix/wildcard against the analyzed
parent broke for any multi-word value because the inverted index stores
per-token entries, not the original phrase. A filter for author="Alice
Wonderland" emitted term: meta_fields.author="alice wonderland" against
text tokens ["alice", "wonderland"] and matched nothing.

Routing string values through <field>.keyword with case_insensitive=true
keeps phrase matching aligned with the in-memory meta_filter (full-string
compare after lower-casing). Numeric/bool values keep the parent path
because dynamic mapping creates no .keyword sub-field for those.

Also wraps the empty/not-empty blank check on .keyword so the analyzer's
empty-token elision does not let blank-string docs leak through.

Verified end-to-end against ES 8.11 with the actual doc_meta_es_mapping:
all 9 parity cases now match the in-memory path (was 4 divergences).

Reported by qinling0210 in PR review.
@sxxtony

sxxtony commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

@qinling0210 thanks — reproduced your finding end-to-end, root-caused it, and pushed a fix in d0c40fdc3.

Root cause

conf/doc_meta_es_mapping.json maps meta_fields as {"type": "object", "dynamic": true}. With default dynamic mapping, string values land as text (analyzed) with a .keyword multi-field. The translator was emitting term/terms/prefix/wildcard against the analyzed parent path, so any multi-word value silently failed: a filter for author = "Alice Wonderland" became term: meta_fields.author = "alice wonderland", which searched the inverted index for that literal phrase token — but the index only held per-token entries ["alice", "wonderland"]. No match.

The fix routes string values through <field>.keyword with case_insensitive: true. Numeric/bool values keep the parent path (those types don't get a .keyword sub-field). The empty/not-empty blank-string check also moved to .keyword because the analyzer drops empty tokens at index time.

Before fix — repro

Real ES 8.11.3, real doc_meta_es_mapping.json, six representative docs (single-word, multi-word, list, numeric, missing-key, empty-string). Same filter run through both meta_filter() (in-memory) and build_meta_filter_query() (push-down):

[FAIL] eq single-word string
       in-memory: ['d_alice']
       ES query:  ['d_alice', 'd_alicew']      ← false positive
[FAIL] eq MULTI-WORD string (the failure mode you reported)
       in-memory: ['d_alicew']
       ES query:  []                            ← false negative, exact mode you saw
[FAIL] in list
       in-memory: ['d_alice', 'd_bob']
       ES query:  ['d_alice', 'd_alicew', 'd_bob']  ← FP + FN
[FAIL] not empty
       in-memory: ['d_alice', 'd_alicew', 'd_bob', 'd_carol']
       ES query:  ['d_alice', 'd_alicew', 'd_bob', 'd_carol', 'd_empty_author']

RESULT: 4/9 parity divergences

After fix

[PASS] eq single-word string                  → ['d_alice']
[PASS] eq MULTI-WORD string                   → ['d_alicew']
[PASS] eq numeric                             → ['d_alice', 'd_no_author']
[PASS] contains substring of multi-word       → ['d_alicew']
[PASS] start with prefix                      → ['d_carol']
[PASS] end with suffix                        → ['d_carol']
[PASS] in list                                → ['d_alice', 'd_bob']
[PASS] range >                                → ['d_alice', 'd_bob', 'd_no_author']
[PASS] not empty                              → ['d_alice', 'd_alicew', 'd_bob', 'd_carol']

RESULT: all 9 cases match between push-down and in-memory.

Unit tests

Updated the operator-shape assertions in test_metadata_es_filter.py to match .keyword-routed queries, and added a regression test (test_equal_multiword_uses_keyword_subfield) that locks in your reported failure mode. 42/42 pass.

$ pytest test/unit_test/common/test_metadata_es_filter.py -v
============================== 42 passed in 0.24s ==============================

The other metadata test files (test_metadata_filter_operators.py, test_apply_semi_auto_meta_data_filter.py) also still pass; the 2 failures you might see in test_apply_semi_auto are a pre-existing import issue in the test environment (verified identical on main), unrelated to this change.

PTAL when you have a moment.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
common/metadata_es_filter.py (2)

1-67: ⚡ Quick win

Add logging for the new pushdown translation flow.

Per coding guidelines, this new flow should emit logs. Useful breadcrumbs: when a filter is rejected as unsupported (operator/value reason), and ideally a debug-level dump of the rendered ES body so post-fix parity issues like the recent .keyword mismatch can be diagnosed without redeploys. Today the module has no logging at all, which leaves the routing layer to infer reasons from exception strings only.

♻️ Sketch
 import ast
 import re
+import logging
 from dataclasses import dataclass, field
 from typing import Any, Dict, Iterable, List, Optional, Sequence
+
+logger = logging.getLogger(__name__)

Then, e.g., in plan_pushdown / translate:

     for flt in filters:
-        plan.translated.append(t.translate(flt))
+        try:
+            plan.translated.append(t.translate(flt))
+        except UnsupportedMetaFilter as e:
+            logger.debug("meta pushdown unsupported: %s (filter=%s)", e.reason, flt)
+            raise
     return plan

As per coding guidelines: "Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@common/metadata_es_filter.py` around lines 1 - 67, Add logging to the
pushdown translation flow: import and create a module-level logger (use Python's
logging), then instrument functions plan_pushdown and translate to log (1) WARN
when a filter is rejected by raising UnsupportedMetaFilter including the
operator/value and a short reason (reference symbols: UnsupportedMetaFilter,
SUPPORTED_OPERATORS, META_FIELDS_PREFIX, _DATE_RE), and (2) DEBUG to emit the
final rendered Elasticsearch bool body before returning so callers can inspect
the exact ES DSL that was produced; ensure the debug dump happens after all
field/key normalization (e.g., where ".keyword" selection is applied) and
include context like the original filter input and the constructed ES dict.

86-86: ⚡ Quick win

Defensively reject multi-value-unsafe negatives in the translator too.

MULTIVALUE_UNSAFE_NEGATIVE_OPS (≠, not in) is only enforced inside is_pushdown_supported. build_meta_filter_query and plan_pushdown are public entry points that don't run that precheck — calling them directly with ≠/not in silently emits an ES body whose semantics diverge from the legacy in-memory path on multi-valued metadata, exactly the parity class the comment at lines 77‑86 warns against. Either gate inside translate (raising UnsupportedMetaFilter) or inside plan_pushdown, so the only way to bypass the guard is the explicit precheck.

♻️ Suggested gate
     def translate(self, flt: Dict[str, Any]) -> TranslatedFilter:
         ...
         if op not in SUPPORTED_OPERATORS:
             raise UnsupportedMetaFilter(f"unknown operator {op!r}", flt)
+        if op in MULTIVALUE_UNSAFE_NEGATIVE_OPS:
+            raise UnsupportedMetaFilter(
+                f"operator {op!r} cannot be safely pushed down on multi-valued fields",
+                flt,
+            )

Also applies to: 194-236

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@common/metadata_es_filter.py` at line 86, The translator currently only
enforces MULTIVALUE_UNSAFE_NEGATIVE_OPS inside is_pushdown_supported, but public
entry points build_meta_filter_query and plan_pushdown (and translate) can be
called directly and must defensively reject multi-value-unsafe negatives; update
translate (or plan_pushdown) to check for any operator in
MULTIVALUE_UNSAFE_NEGATIVE_OPS and raise UnsupportedMetaFilter when present, so
build_meta_filter_query/plan_pushdown cannot produce divergent ES bodies without
this explicit guard; reference MULTIVALUE_UNSAFE_NEGATIVE_OPS, translate,
plan_pushdown, build_meta_filter_query, is_pushdown_supported, and
UnsupportedMetaFilter when adding the check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@common/metadata_es_filter.py`:
- Around line 1-67: Add logging to the pushdown translation flow: import and
create a module-level logger (use Python's logging), then instrument functions
plan_pushdown and translate to log (1) WARN when a filter is rejected by raising
UnsupportedMetaFilter including the operator/value and a short reason (reference
symbols: UnsupportedMetaFilter, SUPPORTED_OPERATORS, META_FIELDS_PREFIX,
_DATE_RE), and (2) DEBUG to emit the final rendered Elasticsearch bool body
before returning so callers can inspect the exact ES DSL that was produced;
ensure the debug dump happens after all field/key normalization (e.g., where
".keyword" selection is applied) and include context like the original filter
input and the constructed ES dict.
- Line 86: The translator currently only enforces MULTIVALUE_UNSAFE_NEGATIVE_OPS
inside is_pushdown_supported, but public entry points build_meta_filter_query
and plan_pushdown (and translate) can be called directly and must defensively
reject multi-value-unsafe negatives; update translate (or plan_pushdown) to
check for any operator in MULTIVALUE_UNSAFE_NEGATIVE_OPS and raise
UnsupportedMetaFilter when present, so build_meta_filter_query/plan_pushdown
cannot produce divergent ES bodies without this explicit guard; reference
MULTIVALUE_UNSAFE_NEGATIVE_OPS, translate, plan_pushdown,
build_meta_filter_query, is_pushdown_supported, and UnsupportedMetaFilter when
adding the check.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8100ef25-f309-4a33-8474-653d60af8227

📥 Commits

Reviewing files that changed from the base of the PR and between fca311b and d0c40fd.

📒 Files selected for processing (2)
  • common/metadata_es_filter.py
  • test/unit_test/common/test_metadata_es_filter.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/unit_test/common/test_metadata_es_filter.py

@qinling0210 qinling0210 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@yingfeng yingfeng added the ci Continue Integration label May 7, 2026
@yingfeng
yingfeng marked this pull request as draft May 7, 2026 04:02
@yingfeng
yingfeng marked this pull request as ready for review May 7, 2026 04:02
@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (12f80f1) to head (7a053e8).
⚠️ Report is 12 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14576   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 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.

@qinling0210

Copy link
Copy Markdown
Contributor

@sxxtony , please analyze the CI failure, it failed on

test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py::test_searchbots_retrieval_test_embedded_matrix_unit

@yingfeng
yingfeng merged commit 59c3510 into infiniflow:main May 7, 2026
1 check passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
### What problem does this PR solve?

Fixes infiniflow#14412.

`common.metadata_utils.meta_filter` evaluates user-defined metadata
conditions in Python after `DocMetadataService.get_flatted_meta_by_kbs`
loads the entire `meta_fields` table into memory. Past a few thousand
documents per knowledge base this becomes a memory bottleneck and a
wasted ES round-trip — every filter request currently fetches up to
10000 metadata rows even when the resulting `doc_ids` list is tiny.

This PR adds an ES push-down path that translates the same filter
language into a `bool` query and returns just the matching document IDs.

**Changes**

- `common/metadata_es_filter.py` *(new)*: pure-Python translator from
the RAGflow filter list to ES DSL. Covers every operator the in-memory
path supports (`=`, `≠`, `>`, `<`, `≥`, `≤`, `in`, `not in`, `contains`,
`not contains`, `start with`, `end with`, `empty`, `not empty`) with
`case_insensitive: true` on `prefix` and `wildcard` for parity with the
existing lower-cased Python comparisons. User wildcard metacharacters
are escaped before being injected into `wildcard` patterns. Negative
operators (`≠`, `not in`, `not contains`, ranges) are wrapped with an
`exists` guard so they do not accidentally match documents missing the
key, matching the legacy `if k not in metas` behaviour.
- `api/db/services/doc_metadata_service.py`: new
`DocMetadataService.filter_doc_ids_by_meta_pushdown(kb_ids, filters,
logic)` that returns the doc IDs ES matched, or `None` to signal the
caller should fall back to the in-memory path. Returns `None` when the
active doc store is Infinity (`meta_fields` is a JSON column, not a
dotted-object mapping), when any filter cannot be expressed in DSL
(`UnsupportedMetaFilter`), or when the ES request or metadata index
lookup errors.
- `common/metadata_utils.py`: `apply_meta_data_filter` accepts an
optional `kb_ids` argument. When supplied, conditions go through
push-down first via a new `_try_meta_pushdown` helper; on `None` the
function falls back to the original `meta_filter` call. Default
behaviour is unchanged for callers that don't pass `kb_ids`.
- Updated all four callers (`agent/tools/retrieval.py`,
`api/db/services/dialog_service.py` ×2,
`api/apps/services/dataset_api_service.py`, `api/apps/sdk/session.py`)
to forward `kb_ids` so the push-down path is exercised in production.
- `test/unit_test/common/test_metadata_es_filter.py` *(new)*: 35 unit
tests covering every operator's DSL shape, value coercion
(`ast.literal_eval`, lowercasing, ISO-date pass-through), wildcard
escaping, OR-logic wrapping that protects negative clauses, and the
doc-ID extractor.

**Behaviour preserved**

- The in-memory `meta_filter` is untouched and still services every
fallback case (Infinity backend, unknown operators, ES outages).
- The eligibility / credibility / issue-multiplier semantics described
in the LLM-driven `auto` and `semi_auto` modes still hand the LLM the
full in-memory `metas` dict to choose conditions from. Only the
*evaluation* of those generated conditions is pushed down.
- Existing tests in
`test/unit_test/common/test_metadata_filter_operators.py` continue to
pass (14/14).

**Test plan**

- `pytest test/unit_test/common/test_metadata_es_filter.py` — 35 passed.
- `pytest test/unit_test/common/test_metadata_filter_operators.py` — 14
passed.
- `ruff check` clean on every modified file.
- Reviewer please validate the ES query shapes against a live cluster —
particularly `case_insensitive` on `wildcard` and `prefix` (requires ES
7.10+) and the `exists` + `must_not` pairing for `≠`.

**Notes**

- The first cut caps each push-down request at 10000 results, matching
the existing `get_flatted_meta_by_kbs` limit, and logs a warning when
the cap is hit. A `search_after` follow-up would let us drop the cap
entirely once the push-down path is validated.
- Operator parity with the in-memory path is exact for the canonical
unicode operators (`≥`, `≤`, `≠`) used internally; the ASCII aliases
(`>=`, `<=`, `!=`) are normalised by `convert_conditions` before they
reach the translator.

### Type of change

- [x] Performance Improvement

---------

Co-authored-by: sxxtony <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request May 18, 2026
1 task done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

Fixes infiniflow#14412.

`common.metadata_utils.meta_filter` evaluates user-defined metadata
conditions in Python after `DocMetadataService.get_flatted_meta_by_kbs`
loads the entire `meta_fields` table into memory. Past a few thousand
documents per knowledge base this becomes a memory bottleneck and a
wasted ES round-trip — every filter request currently fetches up to
10000 metadata rows even when the resulting `doc_ids` list is tiny.

This PR adds an ES push-down path that translates the same filter
language into a `bool` query and returns just the matching document IDs.

**Changes**

- `common/metadata_es_filter.py` *(new)*: pure-Python translator from
the RAGflow filter list to ES DSL. Covers every operator the in-memory
path supports (`=`, `≠`, `>`, `<`, `≥`, `≤`, `in`, `not in`, `contains`,
`not contains`, `start with`, `end with`, `empty`, `not empty`) with
`case_insensitive: true` on `prefix` and `wildcard` for parity with the
existing lower-cased Python comparisons. User wildcard metacharacters
are escaped before being injected into `wildcard` patterns. Negative
operators (`≠`, `not in`, `not contains`, ranges) are wrapped with an
`exists` guard so they do not accidentally match documents missing the
key, matching the legacy `if k not in metas` behaviour.
- `api/db/services/doc_metadata_service.py`: new
`DocMetadataService.filter_doc_ids_by_meta_pushdown(kb_ids, filters,
logic)` that returns the doc IDs ES matched, or `None` to signal the
caller should fall back to the in-memory path. Returns `None` when the
active doc store is Infinity (`meta_fields` is a JSON column, not a
dotted-object mapping), when any filter cannot be expressed in DSL
(`UnsupportedMetaFilter`), or when the ES request or metadata index
lookup errors.
- `common/metadata_utils.py`: `apply_meta_data_filter` accepts an
optional `kb_ids` argument. When supplied, conditions go through
push-down first via a new `_try_meta_pushdown` helper; on `None` the
function falls back to the original `meta_filter` call. Default
behaviour is unchanged for callers that don't pass `kb_ids`.
- Updated all four callers (`agent/tools/retrieval.py`,
`api/db/services/dialog_service.py` ×2,
`api/apps/services/dataset_api_service.py`, `api/apps/sdk/session.py`)
to forward `kb_ids` so the push-down path is exercised in production.
- `test/unit_test/common/test_metadata_es_filter.py` *(new)*: 35 unit
tests covering every operator's DSL shape, value coercion
(`ast.literal_eval`, lowercasing, ISO-date pass-through), wildcard
escaping, OR-logic wrapping that protects negative clauses, and the
doc-ID extractor.

**Behaviour preserved**

- The in-memory `meta_filter` is untouched and still services every
fallback case (Infinity backend, unknown operators, ES outages).
- The eligibility / credibility / issue-multiplier semantics described
in the LLM-driven `auto` and `semi_auto` modes still hand the LLM the
full in-memory `metas` dict to choose conditions from. Only the
*evaluation* of those generated conditions is pushed down.
- Existing tests in
`test/unit_test/common/test_metadata_filter_operators.py` continue to
pass (14/14).

**Test plan**

- `pytest test/unit_test/common/test_metadata_es_filter.py` — 35 passed.
- `pytest test/unit_test/common/test_metadata_filter_operators.py` — 14
passed.
- `ruff check` clean on every modified file.
- Reviewer please validate the ES query shapes against a live cluster —
particularly `case_insensitive` on `wildcard` and `prefix` (requires ES
7.10+) and the `exists` + `must_not` pairing for `≠`.

**Notes**

- The first cut caps each push-down request at 10000 results, matching
the existing `get_flatted_meta_by_kbs` limit, and logs a warning when
the cap is hit. A `search_after` follow-up would let us drop the cap
entirely once the push-down path is validated.
- Operator parity with the in-memory path is exact for the canonical
unicode operators (`≥`, `≤`, `≠`) used internally; the ASCII aliases
(`>=`, `<=`, `!=`) are normalised by `convert_conditions` before they
reach the translator.

### Type of change

- [x] Performance Improvement

---------

Co-authored-by: sxxtony <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration python Pull requests that update python code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Metadata Filtering is Performed In-Memory Instead of Leveraging Elasticsearch, Leading to Performance Bottlenecks

3 participants