使用Java Api的条件语句构建ElasticSearch BoolQuery

时间:2015-10-27 12:18:25

标签: java elasticsearch

我对我的代码有一些非常类似的问题。我想通过使用条件语句来缩短和清理构建通用boolQuery的代码。这些是我的方法:

private SearchRequestBuilder createSearchRequestInRangeForGroupId( String groupId,Date rangeStart,Date rangeEnd) {
          ...
          .setQuery(filteredQuery(
                    boolQuery()
                          .must(matchQuery(FIELD_GROUP_NAME, groupId)),
                          rangeFilter(FIELD_TIMESTAMP).gte(rangeStart.getTime()).lte(rangeEnd.getTime())))
          ...         
    }

private SearchRequestBuilder createSearchRequestInRangeForGender( String gender,Date rangeStart,Date rangeEnd) {
          ...
          .setQuery(filteredQuery(
                    boolQuery()
                          .must(matchQuery(FIELD_GENDER, gender)),
                          rangeFilter(FIELD_TIMESTAMP).gte(rangeStart.getTime()).lte(rangeEnd.getTime())))
          ...
    }

private SearchRequestBuilder createSearchRequestInRangeForGroupIdAndGender( String groupId,String gender,Date rangeStart,Date rangeEnd) {
          ...
          .setQuery(filteredQuery(
                    boolQuery()
                          .must(matchQuery(FIELD_GROUP_NAME, groupId))
                          .must(matchQuery(FIELD_GENDER, gender)),
                          rangeFilter(FIELD_TIMESTAMP).gte(rangeStart.getTime()).lte(rangeEnd.getTime())))
          ....

        return searchRequestBuilder;
    }

我想像这样建立一个boolQuery构建器:

private SearchRequestBuilder createSearchRequestInRange( String groupId,String gender,Date rangeStart,Date rangeEnd) {
        ...
        .setQuery(filteredQuery(
                  buildBoolQuery(groupId,gender),
                  rangeFilter(FIELD_TIMESTAMP).gte(rangeStart.getTime()).lte(rangeEnd.getTime())))
        ...
    }



private QueryBuilder buildBoolQuery(String groupId, String gender){
        QueryBuilder boolQuery = boolQuery();

       if(groupId!=null && !groupId.isEmpty())
            boolQuery = boolQuery.must(matchQuery(FIELD_GROUP_NAME, groupId))
       }
       if(gender!=null && !gender.isEmpty())
            boolQuery = boolQuery.must(matchQuery(FIELD_GENDER, gender))
       }
       return boolQuery;
}

我已经尝试过这样做,但这是不可能的。有没有办法做到这一点? 谢谢。

1 个答案:

答案 0 :(得分:1)

这可能是因为你的boolQuery是QueryBuilder类型。您可能需要在BoolQueryBuilder query = QueryBuilders.boolQuery();

中使用BoolQueryBuilder