Skip to content

Escape dates in Elasticsearch filter queries - #7146

Open
dusen0528 wants to merge 3 commits into
spring-projects:mainfrom
dusen0528:fix-es-date-filter-escaping
Open

dusen0528 wants to merge 3 commits into
spring-projects:mainfrom
dusen0528:fix-es-date-filter-escaping

Conversation

@dusen0528

Copy link
Copy Markdown

Escape dates in Elasticsearch filter queries

ISO date filters fail because ElasticsearchAiSearchFilterExpressionConverter writes formatted dates into query_string queries without escaping Lucene reserved characters.
For example, activationDate == '2024-01-07T14:29:12Z' produces:

metadata.activationDate:2024-01-07T14:29:12Z

Elasticsearch rejects this query with a query_shard_exception caused by a Lucene parse_exception at the colon in the time component.
ISO date strings take the same path as Date values because AbstractFilterExpressionConverter normalizes them before conversion.

This change passes the formatted date through the existing emitLuceneString helper:

metadata.activationDate:2024\-01\-07T14\:29\:12Z

The date stays unquoted, preserving the syntax used for range bounds.
The production change is limited to the Elasticsearch converter's date branch.

Regression coverage

  • Updated the existing date and concurrent date tests to expect escaped output.
  • Added date range and IN unit tests, covering ISO strings and Date values.
  • Added ElasticsearchVectorStoreDateFilterIT for ==, >, >=, <, <=, IN, and delete-by-filter against Elasticsearch 9.2.0.

The integration test uses the existing FixedDimensionEmbeddingModel and needs no hosted model API key.
It checks the returned document IDs, including exclusion of documents that do not match the filter.

Before the fix

With the converter restored to upstream main (5631edc7281c) and the regression tests retained, all seven integration tests errored:

Test Result
equalsWithIsoDateString Failed to parse query
greaterThanOrEqualWithIsoDateString Failed to parse query
greaterThanWithIsoDateString Failed to parse query
lessThanWithIsoDateString Failed to parse query
lessThanOrEqualWithIsoDateString Failed to parse query
inWithIsoDateStrings Failed to parse query
deleteWithIsoDateFilter Delete failed; caused by a query parsing error
Tests run: 7, Failures: 0, Errors: 7, Skipped: 0
BUILD FAILURE

A direct request with the same unescaped equality query against Elasticsearch 9.2.0 returned HTTP 400.
The raw response included:

query_shard_exception: Failed to parse query [metadata.activationDate:2024-01-07T14:29:12Z]
parse_exception: Encountered " ":" ": "" at line 1, column 37.

The additional range tests failed with query_shard_exception: Failed to parse query for these unescaped queries:

metadata.activationDate:>2024-01-08T00:00:00Z
metadata.activationDate:<2024-01-08T00:00:00Z
metadata.activationDate:<=2024-01-08T00:00:00Z

Before fix: captured Maven log excerpts for GT, LT, and LTE

After the fix

The same seven integration tests pass after applying the converter change, with their assertions unchanged.
The complete module unit test suite also passes.

The range tests use 2024-01-08T00:00:00Z as the boundary and check the exact returned document IDs:

Operator Returned documents
> jan9
>= jan8, jan9
< jan7
<= jan7, jan8

This verifies both the query syntax and whether the document at the boundary is included or excluded.

JDK Unit tests Elasticsearch integration tests Failures / errors / skipped
Liberica 17.0.19 16 passed 7 passed 0 / 0 / 0
OpenJDK 21.0.12.1 16 passed 7 passed 0 / 0 / 0

After fix: captured Maven log excerpts for JDK 17 and 21

Reproduction commands

Install the module and its reactor dependencies before running the integration test:

./mvnw -pl vector-stores/spring-ai-elasticsearch-store -am -DskipTests install

Before the fix, exclude the updated unit tests so their output assertions do not prevent the integration test from reaching Elasticsearch:

./mvnw -pl vector-stores/spring-ai-elasticsearch-store verify \
  -Pintegration-tests '-Dtest=!*' \
  -Dsurefire.failIfNoSpecifiedTests=false \
  -Dit.test=ElasticsearchVectorStoreDateFilterIT

After the fix, run the unit and integration tests together:

./mvnw -pl vector-stores/spring-ai-elasticsearch-store verify \
  -Pintegration-tests \
  -Dit.test=ElasticsearchVectorStoreDateFilterIT

Both JDK runs used clean verify -Dmaven.build.cache.enabled=false to compile and execute the tests without restored build results.
spring-javaformat:apply completed successfully.

Escape formatted ISO date values with emitLuceneString so Elasticsearch
query_string filters parse correctly.

Add unit coverage for date ranges and IN filters, and integration tests
for date equality, ranges, IN, and deletion against Elasticsearch.

Signed-off-by: 최인호 <[email protected]>
Cover GT, LT, and LTE ISO date filters against Elasticsearch, checking
the exact document IDs and inclusive or exclusive range boundaries.

Signed-off-by: 최인호 <[email protected]>

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

Checked e7cda7bea against a real Elasticsearch 9.2.0 container, using the fixed-dimension embedding model. The seven original date integration cases pass, along with four local controls: Java Date equality, mixed Date/ISO-string IN, a closed range retaining its exact boundary, and NIN. Final selected integration run: 11 tests, zero failures/errors/skips. The module's 16 unit tests also pass separately.

Reverting only the date escaping line makes the Java Date equality control fail with Failed to parse query [metadata.activationDate:2024-01-08T00:00:00Z]. I restored production and reran the 11 cases successfully. That supports the escaping approach without quoting range operands.

Two extra NE controls exposed a separate, pre-existing converter issue: both plain strings and dates generate metadata.<field>: NOT <value>, which Elasticsearch rejects. The plain-string failure persists with the date change reverted. I filed #7153 separately; it shouldn't expand or block this focused date fix. The complete expanded 13-case run therefore is not green, and I'm not giving blanket approval or claiming a full-repository run.

The Java Date / mixed-list / closed-boundary cases would be useful additions to the permanent fixture. My local checks target the actual query parser and stored documents, rather than only asserting rendered query strings.

Add Java Date equality, mixed Date and ISO-string IN, closed-range
boundaries, and ISO-string NIN integration coverage.

Verify exact document IDs against Elasticsearch 9.2.0 with the existing
fixed-dimension embedding fixture.

See spring-projects#7146

Signed-off-by: 최인호 <[email protected]>
@dusen0528

Copy link
Copy Markdown
Author

Thanks @CryoThrust for independently checking this against Elasticsearch 9.2.0 and for isolating the pre-existing NE issue in #7153.

In commit 81ed907, I added the four controls to the permanent ElasticsearchVectorStoreDateFilterIT fixture:

  • equalsWithJavaDate: Java Date equality returns jan8.
  • inWithMixedJavaDateAndIsoDateString: mixed Java Date / ISO-string IN returns jan7 and jan9.
  • closedRangeKeepsInclusiveBoundaries: a >= / <= range retains both boundary documents (jan7, jan8) and excludes jan9.
  • notInWithIsoDateStrings: NIN excludes the listed dates and returns only jan8.

I ran clean verify on Liberica JDK 17.0.19 with the integration-tests profile and Maven build cache disabled, against a real Elasticsearch 9.2.0 Testcontainers instance. The module's 16 unit tests and all 11 date integration tests passed, with zero failures, errors, or skips.

As a regression check, reverting only the date-escaping line made all four new cases fail with Failed to parse query. I restored that line before the successful run. The production code is unchanged by this follow-up commit. This is focused module/date-filter validation, not a full-repository test run.

I agree that #7153 should remain a separate follow-up rather than expanding this date fix. If you do not plan to take it on, I can work on it in a separate PR.

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

I checked out this branch and ran ElasticsearchAiSearchFilterExpressionConverterTest locally (JDK 21): all 16 tests pass, including the new testDateRange and testDateIn. The change looks right to me: routing the formatted date through emitLuceneString escapes the - and : without quoting, so range operators keep working.

One suggestion: there's no test for a not-equal filter on a date. #7158 (fixing #7153) changes NE to emit NOT field:value, and with this PR the date value is also escaped, so the combined output should be NOT metadata.activationDate:2024\-01\-07T14\:29\:12Z. A unit test like this would pin how the two changes fit together, whichever lands first:

@Test
public void testNeWithDateValue() {
    String vectorExpr = this.converter.convertExpression(
            new Filter.Expression(NE, new Filter.Key("activationDate"), new Filter.Value(new Date(1704637752148L))));
    assertThat(vectorExpr).contains("2024\\-01\\-07T14\\:29\\:12Z");
}

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants