Hi everybody!
In our elasticsearch (version 2.3.1) index we have a showDate
field for every document. This field contains a unix timestamp and I want to find out how many documents have a showDate
in the last 24 hours and how many documents have a showDate
in the last 7 days.
In my Java code this is how I tried to accomplish this:
public static final String TODAY = "today";
public static final String THIS_WEEK = "thisWeek";
protected static final int SECONDS_PER_DAY = (24 * 60 * 60);
//...
Date now = new Date();
double timestampNow = now.getTime() / 1000;
double timestampYesterday = timestampNow - SECONDS_PER_DAY;
double timestampThisWeek = timestampNow - (SECONDS_PER_DAY * 7);
AbstractAggregationBuilder aggregation = AggregationBuilders.range("time").field("showDate")
.addRange(TODAY, timestampYesterday, timestampNow)
.addRange(THIS_WEEK, timestampThisWeek, timestampNow);
searchRequestBuilder.addAggregation(aggregation);
When I execute this searchRequest and look at the produced query I get something like this
{
"from": 0,
"size": 15,
"query": {
...
}
"aggregations": {
"time": {
"range": {
"field": "showDate",
"ranges": [
{
"key": "today",
"from": 1.465369290E9,
"to": 1.465455690E9
},
{
"key": "thisWeek",
"from": 1.464850890E9,
"to": 1.465455690E9
}
]
}
}
}
}
When I execute the query in a plugin such as Kopf or Head I get the expected result. When I execute it in my java service the docCount is always 0.
The only difference I noticed is that the plugins convert the double value into a long value. So after I sent the query the 1.465455690E9
numbers are converted to 1465455690
. Does anyone know how I get the same result in my Java service as I get from the plugins?
Update 1
I've just updated my code and I use a dateRange now. This gives me the expected query, however the DocCount is still always 0.
// ...
Date now = new Date();
long timestampNow = now.getTime() / 1000;
long timestampYesterday = timestampNow - SECONDS_PER_DAY;
long timestampThisWeek = timestampNow - (SECONDS_PER_DAY * 7);
AbstractAggregationBuilder aggregation = AggregationBuilders.dateRange(KEY).field("showDate").format("epoch_second")
.addRange(TODAY, timestampYesterday, timestampNow)
.addRange(THIS_WEEK, timestampThisWeek, timestampNow);
// ...