Spring data elastic search - Query - Full text search

user1578872 picture user1578872 · Apr 5, 2015 · Viewed 15.8k times · Source

I am trying to use elastic search for full text search and Spring data for integrating elastic search with my application.

For example,

There are 6 fields to be indexed.

1)firstName 2)lastName 3)title 4)location 5)industry 6)email

http://localhost:9200/test/_mapping/

I can see these fields in the mapping.

Now, I would like to make a search against these fields with a search input.

For example, When I search "mike 123", it has to search against all these 6 fields.

In Spring data repository,

The below method works to search only in firstName.

Collection<Object> findByFirstNameLike(String searchInput)

But, I would like to search against all the fields.

I tried,

Collection<Object> findByFirstNameLikeOrLastNameLikeOrTitleLikeOrLocationLikeOrIndustryLikeOrEmailLike(String searchInput,String searchInput1,String searchInput2,String searchInput3,)

Here, even the input string is same, i need to pass the same input as 6 params. Also the method name looks bigger with multiple fields.

Is there anyway to make it simple with @Query or ....

Like,

Collection<Object> findByInput(String inputString)

Also, boosting should be given for one of the field.

For example,

When i search for "mike mat", if there is any match in the firstName, that should be the first one in the result even there are exact match in the other fields.

Thanks

Answer

Roberto picture Roberto · Oct 8, 2016

Lets suppose your search term is in the variable query, you can use the method search in ElasticsearchRepository.

repo.search(queryStringQuery(query))

to use queryStringQuery use the following import

import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;