Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data elastic search - Query - Full text search

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

like image 742
user1578872 Avatar asked Apr 05 '15 19:04

user1578872


2 Answers

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;

like image 80
Roberto Avatar answered Sep 30 '22 16:09

Roberto


I found the way to achieve this and posting here. Hope, this would help.

QueryBuilder queryBuilder = boolQuery().should(
                    queryString("Mike Mat").analyzeWildcard(true)
                            .field("firstName", 2.0f).field("lastName").field("title")
                            .field("location").field("industry").field("email"));

Thanks

like image 28
user1578872 Avatar answered Sep 30 '22 18:09

user1578872