ElasticSearch (2.2) Java filter between startDate and endDate if exists

半腔热情 提交于 2019-12-19 11:36:01

问题


I want to have following filter with elasticsearch (java client):

If startDate exists and lower then now

If endDate exists and greater then now

I already have following but it doesn't show the once which have no startDate or endDate:

       //Start date end date

        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        queryBuilder.filter(QueryBuilders.rangeQuery("startDate").lte("now"));
        queryBuilder.should(QueryBuilders.existsQuery("startDate"));
        queryBuilder.filter(QueryBuilders.rangeQuery("endDate").gte("now"));
        queryBuilder.should(QueryBuilders.existsQuery("endDate"));

        boolQueryBuilder.filter(queryBuilder);

The query in mysql looked like this:

SELECT * FROM customer_job WHERE (start_date <= CURDATE() OR start_date IS NULL) AND (end_date>=CURDATE() OR end_date IS NULL);

So how to do that?


I tried following from the answers but it still does not show the ones who have no startDate or endDate:

BoolQueryBuilder startDateQuery = new BoolQueryBuilder()
                .should(QueryBuilders.existsQuery("startDate"))
                .should(QueryBuilders.rangeQuery("startDate").lte("now"))
                .minimumNumberShouldMatch(1);
        BoolQueryBuilder endDateQuery = new BoolQueryBuilder()
                .should(QueryBuilders.existsQuery("endDate"))
                .should(QueryBuilders.rangeQuery("endDate").gte("now"))
                .minimumNumberShouldMatch(1);

        boolQueryBuilder.filter(startDateQuery).filter(endDateQuery);

回答1:


You need a query like this:

BoolQueryBuilder startDateQuery = new BoolQueryBuilder()
   .should(QueryBuilders.missingQuery("startDate"))
   .should(QueryBuilders.rangeQuery("startDate").lte("now"))
   .minimumShouldMatch(1);
BoolQueryBuilder endDateQuery = new BoolQueryBuilder()
   .should(QueryBuilders.missingQuery("endDate"))
   .should(QueryBuilders.rangeQuery("endDate").gte("now"))
   .minimumShouldMatch(1);
BoolQueryBuilder queryBuilder = new BoolQueryBuilder()
   .filter(startDateQuery)
   .filter(endDateQuery);


来源:https://stackoverflow.com/questions/41899072/elasticsearch-2-2-java-filter-between-startdate-and-enddate-if-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!