Reputation: 1864
I have a JPA entity called Invoice
with some properties and want to search and filter the results, but the filter is not working properly. I tried various combinations but no one worked for me.
This one correctly searches for instances having "foobar" in some of the properties:
// this is the search string...
String search = "foobar*";
QueryBuilder queryStringQuery = QueryBuilders.queryStringQuery(search);
NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder();
searchQuery.withQuery(queryStringQuery);
// build and run against the ElasticsearchRepository
NativeSearchQuery query = searchQuery.build();
Page<T> result = searchRepository.search(query);
This is working and gives me all invoices, but now I only want to have "new invoices", which is given by a property called "state", which then has the value "New".
Currently, last one I tried is this one (according to similar questions on SO):
String search = "foobar*";
QueryBuilder queryStringQuery = QueryBuilders.queryStringQuery(search);
NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder();
searchQuery.withQuery(queryStringQuery);
// add filter
QueryBuilder filters = QueryBuilders.termQuery("state", "New");
searchQuery.withFilter(searchFilters);
// build and run against the ElasticsearchRepository
NativeSearchQuery query = searchQuery.build();
Page<T> result = searchRepository.search(query);
This one gives me an empty result, although there must be some results.
I also tried to create somthing like this, but this is also not working:
String search = "foobar*";
QueryBuilder queryStringQuery = QueryBuilders.queryStringQuery(search);
searchFilters = QueryBuilders.termQuery("state", "New");
BoolQueryBuilder searchQuery = QueryBuilders.boolQuery().should(queryStringQuery).must(searchFilters);
Iterable<T> result = searchRepository.search(searchQuery);
Upvotes: 3
Views: 6322
Reputation: 11
Use something like this
QueryBuilder qb;
QueryBuilder stateFilters = QueryBuilders.boolQuery();
((BoolQueryBuilder) filters).filter(QueryBuilders.matchQuery("state", "New"));
qb = QueryBuilders.boolQuery().should(QueryBuilders.queryStringQuery("foobar*")).filter(stateFilters );
the filter function here helps us with this
here qb will have the proper query which can now be used to search using the elasticsearchRepository.search(qb)
;
Here is some information from spring docs: https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.operations
Upvotes: 1