这是我的旧代码,工作正常
qb = QueryBuilders.queryString(query.replaceAll(" ", " OR ").replaceAll(",", " AND ").replaceAll("!", " NOT "));
FilterBuilder fb = FilterBuilders.andFilter(FilterBuilders.rangeFilter("Experiance").from(smonth).to(emonth));
FilteredQueryBuilder fqBuilder = QueryBuilders.filteredQuery(qb, fb);
org.elasticsearch.action.search.SearchResponse searchHits = node.client()
.prepareSearch(name)
.setQuery(fqBuilder)
在这段代码中,我正在搜索那些在smonth和emonth之间经历的数据。
现在我需要在搜索中添加更多过滤器,所以我转移到了NativeSearchQueryBuilder'。修改后,我写了这段代码: -
qb = QueryBuilders.queryString(query.replaceAll(" ", " OR ").replaceAll(",", " AND ").replaceAll("!", " NOT "));
FilterBuilder fb = FilterBuilders.andFilter(FilterBuilders.rangeFilter("Experiance").from(smonth).to(emonth));
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
builder.withQuery(qb);
AndFilterBuilder filters = null;
filters = new AndFilterBuilder(fb);
filters.add(FilterBuilders.andFilter(FilterBuilders.boolFilter().must(FilterBuilders.termFilter("providedZipcode", zipcode)))); //third filter
builder.withFilter(filters);
org.elasticsearch.action.search.SearchResponse searchHits = node.client()
.prepareSearch(name)
.setQuery(builder.build().getQuery());
但是当我搜索时,过滤器无效。我没有根据经验和邮政编码获取数据。
答案 0 :(得分:0)
知道了。
我们可以使用setPostFilter
https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/search.html
org.elasticsearch.action.search.SearchResponse searchHits = node.client()
.prepareSearch(name)
// .setIndices(name)
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(fqBuilder)
.setPostFilter(FilterBuilders.andFilter(FilterBuilders.boolFilter().must(FilterBuilders.termFilter("providedZipcode", zipcode)))); // Filter
但我有另一个问题。如果我没有通过邮政编码,那么它就不会显示数据。如果我没有传递任何邮政编码,我想获取所有数据。
答案 1 :(得分:0)
你看起来实际上从使用bool过滤器中获得更多好处,除了查询字符串之外还有两个condiditons。我们将搜索所有希望与providedZipcode
匹配的文档,但肯定会有smonth
到emonth
的经验。在我的回答中,我使用bool
过滤器来实现此逻辑。
上述答案中的帖子过滤器并不是您正在寻找的功能。它使用原始查询执行您的请求,然后通过第二个过滤器过滤原始查询的结果。
这是我写下你的请求的方式:
QueryStringQueryBuilder qb = QueryBuilders.queryString(query
.replaceAll(" ", " OR ")
.replaceAll(",", " AND ")
.replaceAll("!", " NOT "));
FilterBuilder fb = FilterBuilders.boolFilter()
.should(FilterBuilders.termFilter("providedZipcode", zipcode))
.must(FilterBuilders.rangeFilter("Experiance").from(smonth).to(emonth));
FilteredQueryBuilder fqb = new FilteredQueryBuilder(qb, fb);