Skip to content

fix(metadata): Elasticsearch date filtering — exact-match returns 0 and ASCII operators dropped - #16833

Closed
Xavierando wants to merge 1133 commits into
infiniflow:mainfrom
Xavierando:fix/es-date-metadata-filter
Closed

Xavierando wants to merge 1133 commits into
infiniflow:mainfrom
Xavierando:fix/es-date-metadata-filter

Conversation

@Xavierando

@Xavierando Xavierando commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes three bugs that break document-metadata date filtering on Elasticsearch (issue #16832). They surface as "date filter returns nothing / returns everything" in chat auto/semi_auto filtering and in /api/v1/retrieval.

1. Exact-match = on a date-typed field returned 0.
ES dynamic date detection types a YYYY-MM-DD meta field as date, which has no .keyword sub-field; _term_or_match built a .keyword-only term for string values, so = on a date field silently matched nothing. ISO-date values now match both the parent field and .keyword via a should; non-date strings are unchanged (multi-word phrase equality preserved).

2. ASCII comparison operators were silently dropped.
gen_meta_filter and user conditions may emit >=/<=/!=/==, but the push-down (SUPPORTED_OPERATORS) and the in-memory path only accept the Unicode set (≥/≤/≠/=); an un-normalised operator dropped the whole filter. Added normalize_condition_operators() (mirroring convert_conditions) and applied it at the top of _run_metadata_filter, so every backend benefits.

3. A filter that matches nothing fell back to unrestricted retrieval (latent; exposed by 1 and 2).
apply_meta_data_filter returned None from the auto/semi_auto branches when the generated conditions matched zero documents. None means "no metadata filter", so retrieval ran unrestricted and returned arbitrary documents instead of "no results". The manual branch already returns the ["-999"] no-results sentinel here; auto/semi_auto now do the same, while still returning None when no conditions were generated (genuinely no filter). This bug is pre-existing, but only once =/range filtering works (fixes 1 and 2) can a date query legitimately match zero documents and reach this fallback — e.g. "what happened yesterday" on a date with no documents previously surfaced unrelated docs with a hallucinated date.

All three fixes have unit tests (test/unit_test/common/test_metadata_filter.py, test/unit_test/common/test_metadata_filter_operators.py, test/unit_test/common/test_apply_semi_auto_meta_data_filter.py) and fixes 1–2 were verified against a live Elasticsearch index (bug 1: 0 → 12 docs; bug 2: dropped → 18 docs).

Closes #16832

dcc123456 and others added 30 commits July 7, 2026 14:50
### Summary

Go development guide

---------

Signed-off-by: Jin Hai <[email protected]>
As title

---------

Signed-off-by: Jin Hai <[email protected]>
### Summary

--migrate will trigger database migration
```
./ragflow_main --api --migrate
```

Signed-off-by: Jin Hai <[email protected]>
### Summary

Remove ragflow-cli building dependency

Signed-off-by: Jin Hai <[email protected]>
Lynn-Inf and others added 17 commits July 17, 2026 15:53
…17010)

## Summary

- Preserve request-scoped system variables such as files and user IDs
during Canvas execution.
- Persist conversation history, turn counts, and tool memory in the
session DSL across turns.
- Parse agent uploads into `sys.files` and align system variable
rendering with Python.

## Testing

- `bash build.sh --test ./internal/agent/...`
- `bash build.sh --test ./internal/service/...`

<img width="1896" height="1232" alt="image"
src="https://github.com/user-attachments/assets/b420cd97-53c3-470f-a3e1-d39cea26a213"
/>
…#17034)

## Summary

- Filter the `[DONE]` transport sentinel from Eino model streams
- Add regression coverage for stream messages and callbacks

## Testing

- `bash build.sh --test ./internal/entity/models`
- `bash build.sh --test ./internal/agent/component`
- `bash build.sh --test -run
'Test(AgentChatCompletions_Stream|RunAgent_Stream)' ./internal/handler`
### Summary

As title

<img width="3718" height="2029" alt="image"
src="https://github.com/user-attachments/assets/227bcd8b-e5b8-465e-983c-c0c0650a4ea5"
/>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
### Summary

CI: modify longtime testcase to p3
### Summary

```
RAGFlow(api/default)> CHAT WITH 'glm-4-flash@new_test@zhipu-ai' MESSAGE '30 words describes LLM';
Answer: Hello! I'm ChatGLM, an AI assistant. Feel free to ask me any questions or request help with any tasks.
Input tokens: 5
Output tokens: 28
Time: 12.748241
```

Signed-off-by: Jin Hai <[email protected]>
# Conflicts:
#	test/unit_test/common/test_metadata_filter_operators.py
@Xavierando

Copy link
Copy Markdown
Contributor Author

Rebased on latest main — the branch is now conflict-free and MERGEABLE/CLEAN again (head 04aa570).

The only conflict was a tail-append collision in test/unit_test/common/test_metadata_filter_operators.py with @chuenchen309's #16956 (merged July 16), which added case-insensitivity + per-entry state-reset fixes to filter_out. Both test sets are kept; the two changes are orthogonal in common/metadata_utils.py (his: filter_out operand coercion; this PR: convert_conditions/operator aliases + the apply_meta_data_filter no-results sentinel). Full metadata suite green locally — 102 passed, including test_normalised_ge_filters_dates_in_memory, which exercises the exact filter_out path #16956 rewrote, so the merge is behavior-verified, not just textually clean. ruff check clean, ruff format applied.

Recap for reviewers — this fixes three bugs in ES metadata date filtering (#16832):

  • A — = on a date-typed field returns 0: _term_or_match builds term on <field>.keyword, but ES types YYYY-MM-DD as date, which has no .keyword sub-field. Fix: emit a should over both the parent field and .keyword.
  • B — ASCII operators silently dropped: gen_meta_filter/user input can emit >=,<=,!=,==, but SUPPORTED_OPERATORS only accepts the Unicode set, so the whole filter is discarded and retrieval runs unrestricted. Fix: normalize_condition_operators() applied in _run_metadata_filter.
  • C (latent, exposed once A+B are fixed) — apply_meta_data_filter's auto/semi_auto branches returned None (= "no filter") when a generated filter matched nothing, falling back to unrestricted retrieval. Fix: return the ["-999"] no-results sentinel, matching the existing manual branch.

Cross-PR note for @chuenchen309 / maintainers — there's a load-bearing ordering dependency with the open #16943 (Infinity push-down rejecting multi-valued-unsafe negative ops). That guard keys on the Unicode ≠/not in; an ASCII != reaching is_pushdown_supported before normalization would slip past it. Bug B's normalize_condition_operators is the precondition that makes the Unicode-only guard sound on the LLM/auto path. The two PRs are complementary and, ideally, land together.

Beyond these three point-fixes, @zeweihan's framing on #16832 and #16967 (backend-specific schema/semantics drift — "same query, different backend, materially different answer, zero error signal") points at a durable follow-up: a backend-parity test asserting ES/Infinity/in-memory return identical filter sets, plus a metadata_filter_coverage signal exposing dropped/no-matched operators at query time.

One note for maintainers: the ragflow_tests_elasticsearch/_infinity jobs came back SKIPPED (fork PR awaiting CI approval), so the ES path this fixes hasn't actually run in CI yet — a workflow-run approval would let it verify end-to-end.

yuzhichang pushed a commit that referenced this pull request Jul 18, 2026
…ative ops (≠, not in) (#16943)

### What problem does this PR solve?

The Elasticsearch and Infinity metadata push-down translators are meant
to be
interchangeable pre-filters that both mirror the in-memory `meta_filter`
fallback — the shared test section is even titled
*"is_pushdown_supported
pre-check (same logic for both backends)"*. But the two
`is_pushdown_supported`
implementations diverge:

- `common/metadata_es_filter.py` defines
`MULTIVALUE_UNSAFE_NEGATIVE_OPS = frozenset({"≠", "not in"})` and
refuses
  push-down for those operators.
- `common/metadata_infinity_filter.py` has **no such guard** and pushes
them
  down.

**Why the guard exists:** `meta_fields.<key>` can hold a JSON array, and
the
in-memory `meta_filter` matches a document when **any** of its values
satisfies
the predicate (per-value-bucket semantics). A document whose `tag` is
`[a, b]`
therefore still matches `tag ≠ a` — bucket `b` satisfies it. The
Infinity
push-down emits `NOT JSON_CONTAINS(meta_fields, '$.tag', '"a"')`, which
means
*"the array contains no `a` at all"*, so it **silently drops** that
document.
Same divergence for `not in`. The result: `tag ≠ a` / `tag not in (...)`
under-counts results for any document that has the excluded value
alongside
others, but only on the Infinity backend.

This is on a live production path:
`DocMetadataService._filter_doc_ids_by_metadata_infinity`
(`api/db/services/doc_metadata_service.py:948`) calls this exact
`is_pushdown_supported` as the sole gate before building the Infinity
SQL,
mirroring the ES branch at line 880 which uses the guarded ES version.

Reproduction (both real modules, no services needed):

```python
>>> from common import metadata_es_filter as es, metadata_infinity_filter as inf
>>> f = [{"op": "≠", "key": "tag", "value": "a"}]
>>> es.is_pushdown_supported(f), inf.is_pushdown_supported(f)
(False, True)   # ES falls back to in-memory (correct); Infinity pushes down (wrong)
```

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

### Fix

Add the same `MULTIVALUE_UNSAFE_NEGATIVE_OPS` set to
`metadata_infinity_filter` and reject those operators in
`is_pushdown_supported`, so a single such filter forces the whole
request to
the in-memory path — the only place the per-bucket semantics are
reproduced.
`not contains` is intentionally still allowed, matching the ES backend
(`all(not contains)` == `not any(contains)`, which the push-down
expresses
correctly on multi-valued fields). The `≠` / `not in` translators
themselves
are unchanged — they remain correct for the in-memory-fallback path;
only the
push-down eligibility gate is fixed.

### Testing

- Confirmed `is_pushdown_supported([{op}])` now returns `False` for `≠`
and
  `not in` on **both** backends (previously ES=False, Infinity=True).
- Added `test_pushdown_check_rejects_multivalue_unsafe_negative_ops`,
which
asserts both backends reject these ops. Confirmed red→green: it fails
against
  the pre-fix Infinity module, passes after.
- `ruff check` / `ruff format --check` clean.

### Note on overlap

Open PR #16833 also edits
`test/unit_test/common/test_metadata_filter.py`, but
only **appends** at the end of the file (line 640+) and changes
`metadata_es_filter.py` / `metadata_utils.py`, not the Infinity module —
no
overlap with this change.

### Disclosure

AI-assisted (Claude Code): the divergence was surfaced by an AI-assisted
review
pass, but I independently reproduced it against the real modules,
confirmed the
production call path, and verified the fix and test before submitting.

Signed-off-by: Andrew Chen <[email protected]>
Signed-off-by: chuenchen309 <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
@JinHai-CN

Copy link
Copy Markdown
Member

@sxxtony Would you please help review this PR?

@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.

@Xavierando Please rebase your code change to latest code.

And make sure you have verified your code change.

@qinling0210

Copy link
Copy Markdown
Contributor

@Xavierando

We have released RAGFlow v1.0.0-rc1 today, and we only have go code on main branch. Python code is only on 0.27.x branch.

Could you please apply your code change to the 2 branches separately? We are mainly developing in Go, so please make modifications in Go first.

Thanks.

@Xavierando

Copy link
Copy Markdown
Contributor Author

Hi, thanks for the info. I belive i will update my project to the go codebase and adapt my fix. It will probably take a couple of days

@Xavierando

Copy link
Copy Markdown
Contributor Author

Thanks @qinling0210. The Go fix is in #20532. On main only the exact-match part reproduces: =/in on a metadata field that Elasticsearch mapped as date returns nothing, because the clause targets <field>.keyword. ASCII operators are already applied in Go: the push-down declines them and the in-memory filter normalises them. The "no match → unrestricted retrieval" point is a behaviour question, so I'll open it as a separate issue.

Since main is Go-only and this PR targets it, I'm closing it in favour of #20532. If you still want the Python fix on 0.27.x, let me know and I'll open a separate PR against that branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Elasticsearch metadata date filtering — exact-match "=" returns 0 and LLM range operators are silently dropped