Search code examples
javaspring-dataspring-data-elasticsearch

How to write a Query annotation with collection parameter in Spring Data Elasticsearch repository


In a ProductRepository extends ElasticsearchRepository<Product, String> I have a working query like:

@Query("{\"bool\": {"
        + "    \"filter\": ["
        + "        {\"term\": {\"CategoryID.keyword\": {\"value\": \"?0\"}}},"
        + "        {\"terms\": {\"Name.keyword\": [\"Name_A\",\"Name_B\",\"Name_C\"]}}"
        + "     ]"
        + "   }"
        + "}")
Stream<Product> findByCategoryIDAndNames(String categoryId, PageRequest pageRequest);

I need to have the terms values not hardcoded in the annotation but as List<String> argument to the method. I cannot find the correct way to write the Query annotation to query for a collection of names like:

@Query("{\"bool\": {"
        + "    \"filter\": ["
        + "        {\"term\": {\"CategoryID.keyword\": {\"value\": \"?0\"}}},"
        + "        {\"terms\": {\"Name.keyword\": [\"?1\"]}}"
        + "     ]"
        + "   }"
        + "}")
Stream<Product> findByCategoryIDAndNames(String categoryId, List<String> names, PageRequest pageRequest);

This compiles and runs without errors but doesn't work.
Looking in the Spring Data Elasticsearch documentation I cannot find an example how to do this.

Spring Data Elasticsearch version: 4.0.4


Solution

  • Support for collection parameters was added with PR #1856 on July 3rd 2021 for the branches 4.3 to 4.1. The 4.0 branch has OSS support until May 2021, so it is not updated anymore.