Cleydyr Albuquerque
Cleydyr Albuquerque

Reputation: 1

How to conditionally add a term query to a Elasticsearch Data Elasticsearch repository using the @Query annotation and SpEl?

I'm trying to integrate an existing legacy application to Elasticsearch using Spring Data Elasticsearch (version 5.3.0). I wrote a repository like this:


public interface IndexableUserRepository extends ElasticsearchRepository<IndexableUser, Integer> {

  @Query(
    """
          {
            "bool": {
              "filter": [
                 #{#user.hasNeverPrintedUserCard ? '' :
                  '{
                    "term": {
                      "hasPrintedUserCard": false
                    }
                  },'
                }
                {
                  "term": {
                    "isInactive": #{#user.isInactive}
                  }
                }
              ]
            }
          }
  """)
  Page<IndexableUser> findByQueryWithName(
          IndexableUserQueryParameters user, PageRequest pageRequest);
}

(I'll omit the definition of IndexableUserQueryParameters and IndexableUser for the sake of brevity.)

I want to include a term query conditionally on the hasPrintedUserCard property of the record IndexableUserQueryParameters being false. In other words,

However, the double quotes around "term" and "hasPrintedUserCard" are being escaped, which causes a syntax error for Elasticsearch.

I decoded the wrapped query value and got this

{
  "bool": {
    "filter": [
       {
          \"term\": {
            \"hasPrintedUserCard\": false
          }
        },
      {
        "term": {
          "isInactive": false
        }
      }
    ]
  }
}

Is that the expected behavior for SpEl? Or is it an issue with how the @Query annotation works? Is there a way to implement that conditional inclusion of a term query using @Query + @SpEl?

I tried removing the single quotes from around the term query, but it then gave me an error detected by Spring itself about SpEl syntax.

Upvotes: 0

Views: 22

Answers (0)

Related Questions