hellzone
hellzone

Reputation: 5246

How to search for list of keyword with Spring Data Elasticsearch?

I am using ElasticsearchRepository and I want to search some keywords. What I want to query is like;

//Get all results which contains at least one of these keywords
public List<Student> searchInBody(List<String> keywords);

I have already created a query for single keyword and It works but I don't know how to create a query for multiple keywords. Is there any way to do this?

@Repository
public interface StudentRepository extends 
ElasticsearchRepository<Student, String> {

    public List<Student> findByNameOrderByCreateDate(String name);

    @Query("{\"query\" : {\"match\" : {\"_all\" : \"?0\"}}}")
    List<ParsedContent> searchInBody(String keyword);

}

Upvotes: 2

Views: 3894

Answers (1)

100rabh
100rabh

Reputation: 138

Yes, You can pass an array of String objects in ElasticsearchRepository. Elasticsearch provides terms query for that.

Also You have to use JSONArray instead of List<String> i.e. you have to convert your List<String> to JsonArray. (Reason: check syntax of elastic query provided below)

Here is how you can use it in your code:

@Query("{\"bool\": {\"must\": {\"terms\": {\"your_field_name\":?0}}}}")
List<ParsedContent> searchInBody(JSONArray keyword);

Result will contain objects with atleast one keyword provided in your keyword array.

Following is rest request representation of above java code that you can use in your kibana console or in terminal:

GET your_index_name/_search
{
 "query" : {
            "bool": {
                     "must": {
                              "terms": {
                                       "your_field_name":["keyword_1", "keyword_2"]
                                       }
                             }
                    }
           }
}

Note: For more options, You can check terms-set-query

Upvotes: 4

Related Questions