使用Spring Data Elasticsearch搜索和过滤

时间:2018-02-19 15:03:31

标签: java spring jpa elasticsearch spring-data-elasticsearch

我有一个名为Invoice的JPA实体,它有一些属性,想要搜索和过滤结果,但过滤器工作不正常。我尝试了各种组合,但没有人为我工作。

这个正确搜索有" foobar"在一些属性中:

// 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);

这是有效的,并且给了我所有的发票,但现在我只想要新的发票&#34;,这是由名为&#34; state&#34;的属性给出的,然后它具有价值&#34;新&#34;

目前,我尝试的最后一个是这个(根据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);

这个给了我一个空洞的结果,虽然必须有一些结果。

我也试图创建这样的东西,但这也不起作用:

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);

1 个答案:

答案 0 :(得分:0)

使用类似这样的东西

QueryBuilder qb;

QueryBuilder stateFilters = QueryBuilders.boolQuery();
((BoolQueryBuilder) filters).filter(QueryBuilders.matchQuery("state", "New"));
qb = QueryBuilders.boolQuery().should(QueryBuilders.queryStringQuery("foobar*")).filter(stateFilters );

此处的过滤器功能可以帮助我们

此处 qb 将具有正确的查询,现在可以使用elasticsearchRepository.search(qb)进行搜索;

以下是spring文档中的一些信息: https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.operations