title: Search and filter with Spring Data Elasticsearch
body: <p>I have a JPA entity called <code>Invoice</code> 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.</p>
  
  <p>This one correctly searches for instances having "foobar" in some of the properties:</p>
  
  <pre><code>// 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&lt;T&gt; result = searchRepository.search(query);
  </code></pre>
  
  <p>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".</p>
  
  <p>Currently, last one I tried is this one (according to similar questions on SO): </p>
  
  <pre><code>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&lt;T&gt; result = searchRepository.search(query);
  </code></pre>
  
  <p>This one gives me an empty result, although there must be some results. </p>
  
  <p>I also tried to create somthing like this, but this is also not working:</p>
  
  <pre><code>String search = "foobar*";
  QueryBuilder queryStringQuery = QueryBuilders.queryStringQuery(search);
  searchFilters = QueryBuilders.termQuery("state", "New");
  
  BoolQueryBuilder searchQuery = QueryBuilders.boolQuery().should(queryStringQuery).must(searchFilters);
  Iterable&lt;T&gt; result = searchRepository.search(searchQuery);
  </code></pre>