<commit_before>/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.elasticsearch.search.aggregations.bucket;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.range.date.DateRange;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.hamcrest.Matchers;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.*;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;

/**
 *
 */
public class DateRangeTests extends ElasticsearchIntegrationTest {

    @Override
    public Settings indexSettings() {
        return ImmutableSettings.builder()
                .put("index.number_of_shards", between(1, 5))
                .put("index.number_of_replicas", between(0, 1))
                .build();
    }

    private static DateTime date(int month, int day) {
        return new DateTime(2012, month, day, 0, 0, DateTimeZone.UTC);
    }

    private static IndexRequestBuilder indexDoc(int month, int day, int value) throws Exception {
        return client().prepareIndex("idx", "type").setSource(jsonBuilder()
                .startObject()
                .field("value", value)
                .field("date", date(month, day))
                .startArray("dates").value(date(month, day)).value(date(month + 1, day + 1)).endArray()
                .endObject());
    }

    int numDocs;

    @Before
    public void init() throws Exception {
        createIndex("idx");
        createIndex("idx_unmapped");

        numDocs = randomIntBetween(7, 20);

        List<IndexRequestBuilder> docs = new ArrayList<IndexRequestBuilder>();
        docs.addAll(Arrays.asList(
                indexDoc(1, 2, 1),  // Jan 2
                indexDoc(2, 2, 2),  // Feb 2
                indexDoc(2, 15, 3), // Feb 15
                indexDoc(3, 2, 4),  // Mar 2
                indexDoc(3, 15, 5), // Mar 15
                indexDoc(3, 23, 6))); // Mar 23

        // dummy docs
        for (int i = docs.size(); i < numDocs; ++i) {
            docs.add(indexDoc(randomIntBetween(6, 10), randomIntBetween(1, 20), randomInt(100)));
        }

        indexRandom(true, docs);
        ensureSearchable();
    }

    @Test
    public void singleValueField() throws Exception {
        SearchResponse response = client().prepareSearch("idx")
                .addAggregation(dateRange("range")
                        .field("date")
                        .addUnboundedTo(date(2, 15))
                        .addRange(date(2, 15), date(3, 15))
                        .addUnboundedFrom(date(3, 15)))
                .execute().actionGet();<commit_msg>Add a basic test for date math in date ranges.<commit_after>/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.elasticsearch.search.aggregations.bucket;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.range.date.DateRange;
import org.elasticsearch.search.aggregations.bucket.range.date.DateRangeBuilder;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.hamcrest.Matchers;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.*;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;

/**
 *
 */
public class DateRangeTests extends ElasticsearchIntegrationTest {

    @Override
    public Settings indexSettings() {
        return ImmutableSettings.builder()
                .put("index.number_of_shards", between(1, 5))
                .put("index.number_of_replicas", between(0, 1))
                .build();
    }

    private static DateTime date(int month, int day) {
        return new DateTime(2012, month, day, 0, 0, DateTimeZone.UTC);
    }

    private static IndexRequestBuilder indexDoc(int month, int day, int value) throws Exception {
        return client().prepareIndex("idx", "type").setSource(jsonBuilder()
                .startObject()
                .field("value", value)
                .field("date", date(month, day))
                .startArray("dates").value(date(month, day)).value(date(month + 1, day + 1)).endArray()
                .endObject());
    }

    int numDocs;

    @Before
    public void init() throws Exception {
        createIndex("idx");
        createIndex("idx_unmapped");

        numDocs = randomIntBetween(7, 20);

        List<IndexRequestBuilder> docs = new ArrayList<IndexRequestBuilder>();
        docs.addAll(Arrays.asList(
                indexDoc(1, 2, 1),  // Jan 2
                indexDoc(2, 2, 2),  // Feb 2
                indexDoc(2, 15, 3), // Feb 15
                indexDoc(3, 2, 4),  // Mar 2
                indexDoc(3, 15, 5), // Mar 15
                indexDoc(3, 23, 6))); // Mar 23

        // dummy docs
        for (int i = docs.size(); i < numDocs; ++i) {
            docs.add(indexDoc(randomIntBetween(6, 10), randomIntBetween(1, 20), randomInt(100)));
        }

        indexRandom(true, docs);
        ensureSearchable();
    }

    @Test
    public void dateMath() throws Exception {
        DateRangeBuilder rangeBuilder = dateRange("range");
        if (randomBoolean()) {
            rangeBuilder.field("date");
        } else {
            rangeBuilder.script("doc['date'].value");
        }
        SearchResponse response = client().prepareSearch("idx")
                .addAggregation(rangeBuilder
                        .addUnboundedTo("a long time ago", "now-50y")
                        .addRange("recently", "now-50y", "now-1y")
                        .addUnboundedFrom("last year", "now-1y"))
                .execute().actionGet();

        assertSearchResponse(response);

        DateRange range = response.getAggregations().get("range");
        assertThat(range, notNullValue());
        assertThat(range.getName(), equalTo("range"));
        assertThat(range.buckets().size(), equalTo(3));

        DateRange.Bucket bucket = range.buckets().get(0);
        assertThat(bucket.getKey(), equalTo("a long time ago"));
        assertThat(bucket.getDocCount(), equalTo(0L));

        bucket = range.buckets().get(1);
        assertThat(bucket.getKey(), equalTo("recently"));
        assertThat(bucket.getDocCount(), equalTo((long) numDocs));

        bucket = range.buckets().get(2);
        assertThat(bucket.getKey(), equalTo("last year"));
        assertThat(bucket.getDocCount(), equalTo(0L));
    }

    @Test
    public void singleValueField() throws Exception {
        SearchResponse response = client().prepareSearch("idx")
                .addAggregation(dateRange("range")
                        .field("date")
                        .addUnboundedTo(date(2, 15))
                        .addRange(date(2, 15), date(3, 15))
                        .addUnboundedFrom(date(3, 15)))
                .execute().actionGet();
{'fraction_non_alphanumeric': 0.11333463490823897, 'fraction_numerical': 0.01483795392424834, 'mean_word_length': 2.9192807957153786, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7663243', 'n_tokens_mistral': 2911, 'n_tokens_neox': 2754, 'n_words': 702}