Search in sources :

Example 1 with Filter

use of org.opensearch.search.aggregations.bucket.filter.Filter in project OpenSearch by opensearch-project.

the class EquivalenceIT method testRandomRanges.

// Make sure that unordered, reversed, disjoint and/or overlapping ranges are supported
// Duel with filters
public void testRandomRanges() throws Exception {
    final int numDocs = scaledRandomIntBetween(500, 5000);
    final double[][] docs = new double[numDocs][];
    for (int i = 0; i < numDocs; ++i) {
        final int numValues = randomInt(5);
        docs[i] = new double[numValues];
        for (int j = 0; j < numValues; ++j) {
            docs[i][j] = randomDouble() * 100;
        }
    }
    prepareCreate("idx").addMapping("type", jsonBuilder().startObject().startObject("type").startObject("properties").startObject("values").field("type", "double").endObject().endObject().endObject().endObject()).get();
    for (int i = 0; i < docs.length; ++i) {
        XContentBuilder source = jsonBuilder().startObject().startArray("values");
        for (int j = 0; j < docs[i].length; ++j) {
            source = source.value(docs[i][j]);
        }
        source = source.endArray().endObject();
        client().prepareIndex("idx").setSource(source).get();
    }
    assertNoFailures(client().admin().indices().prepareRefresh("idx").setIndicesOptions(IndicesOptions.lenientExpandOpen()).get());
    final int numRanges = randomIntBetween(1, 20);
    final double[][] ranges = new double[numRanges][];
    for (int i = 0; i < ranges.length; ++i) {
        switch(randomInt(2)) {
            case 0:
                ranges[i] = new double[] { Double.NEGATIVE_INFINITY, randomInt(100) };
                break;
            case 1:
                ranges[i] = new double[] { randomInt(100), Double.POSITIVE_INFINITY };
                break;
            case 2:
                ranges[i] = new double[] { randomInt(100), randomInt(100) };
                break;
            default:
                throw new AssertionError();
        }
    }
    RangeAggregationBuilder query = range("range").field("values");
    for (int i = 0; i < ranges.length; ++i) {
        String key = Integer.toString(i);
        if (ranges[i][0] == Double.NEGATIVE_INFINITY) {
            query.addUnboundedTo(key, ranges[i][1]);
        } else if (ranges[i][1] == Double.POSITIVE_INFINITY) {
            query.addUnboundedFrom(key, ranges[i][0]);
        } else {
            query.addRange(key, ranges[i][0], ranges[i][1]);
        }
    }
    SearchRequestBuilder reqBuilder = client().prepareSearch("idx").addAggregation(query);
    for (int i = 0; i < ranges.length; ++i) {
        RangeQueryBuilder filter = QueryBuilders.rangeQuery("values");
        if (ranges[i][0] != Double.NEGATIVE_INFINITY) {
            filter = filter.from(ranges[i][0]);
        }
        if (ranges[i][1] != Double.POSITIVE_INFINITY) {
            filter = filter.to(ranges[i][1]);
        }
        reqBuilder = reqBuilder.addAggregation(filter("filter" + i, filter));
    }
    SearchResponse resp = reqBuilder.get();
    Range range = resp.getAggregations().get("range");
    List<? extends Bucket> buckets = range.getBuckets();
    HashMap<String, Bucket> bucketMap = new HashMap<>(buckets.size());
    for (Bucket bucket : buckets) {
        bucketMap.put(bucket.getKeyAsString(), bucket);
    }
    for (int i = 0; i < ranges.length; ++i) {
        long count = 0;
        for (double[] values : docs) {
            for (double value : values) {
                if (value >= ranges[i][0] && value < ranges[i][1]) {
                    ++count;
                    break;
                }
            }
        }
        final Range.Bucket bucket = bucketMap.get(Integer.toString(i));
        assertEquals(bucket.getKeyAsString(), Integer.toString(i), bucket.getKeyAsString());
        assertEquals(bucket.getKeyAsString(), count, bucket.getDocCount());
        final Filter filter = resp.getAggregations().get("filter" + i);
        assertThat(filter.getDocCount(), equalTo(count));
    }
}
Also used : Bucket(org.opensearch.search.aggregations.bucket.range.Range.Bucket) SearchRequestBuilder(org.opensearch.action.search.SearchRequestBuilder) HashMap(java.util.HashMap) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) Range(org.opensearch.search.aggregations.bucket.range.Range) RangeAggregationBuilder(org.opensearch.search.aggregations.bucket.range.RangeAggregationBuilder) OpenSearchAssertions.assertSearchResponse(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse) Bucket(org.opensearch.search.aggregations.bucket.range.Range.Bucket) Filter(org.opensearch.search.aggregations.bucket.filter.Filter) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder)

Example 2 with Filter

use of org.opensearch.search.aggregations.bucket.filter.Filter in project OpenSearch by opensearch-project.

the class EquivalenceIT method testReduce.

// https://github.com/elastic/elasticsearch/issues/6435
public void testReduce() throws Exception {
    createIndex("idx");
    final int value = randomIntBetween(0, 10);
    indexRandom(true, client().prepareIndex("idx").setSource("f", value));
    SearchResponse response = client().prepareSearch("idx").addAggregation(filter("filter", QueryBuilders.matchAllQuery()).subAggregation(range("range").field("f").addUnboundedTo(6).addUnboundedFrom(6).subAggregation(sum("sum").field("f")))).get();
    assertSearchResponse(response);
    Filter filter = response.getAggregations().get("filter");
    assertNotNull(filter);
    assertEquals(1, filter.getDocCount());
    Range range = filter.getAggregations().get("range");
    assertThat(range, notNullValue());
    assertThat(range.getName(), equalTo("range"));
    List<? extends Bucket> buckets = range.getBuckets();
    assertThat(buckets.size(), equalTo(2));
    Range.Bucket bucket = buckets.get(0);
    assertThat(bucket, notNullValue());
    assertThat((String) bucket.getKey(), equalTo("*-6.0"));
    assertThat(((Number) bucket.getFrom()).doubleValue(), equalTo(Double.NEGATIVE_INFINITY));
    assertThat(((Number) bucket.getTo()).doubleValue(), equalTo(6.0));
    assertThat(bucket.getDocCount(), equalTo(value < 6 ? 1L : 0L));
    Sum sum = bucket.getAggregations().get("sum");
    assertEquals(value < 6 ? value : 0, sum.getValue(), 0d);
    bucket = buckets.get(1);
    assertThat(bucket, notNullValue());
    assertThat((String) bucket.getKey(), equalTo("6.0-*"));
    assertThat(((Number) bucket.getFrom()).doubleValue(), equalTo(6.0));
    assertThat(((Number) bucket.getTo()).doubleValue(), equalTo(Double.POSITIVE_INFINITY));
    assertThat(bucket.getDocCount(), equalTo(value >= 6 ? 1L : 0L));
    sum = bucket.getAggregations().get("sum");
    assertEquals(value >= 6 ? value : 0, sum.getValue(), 0d);
}
Also used : Bucket(org.opensearch.search.aggregations.bucket.range.Range.Bucket) Filter(org.opensearch.search.aggregations.bucket.filter.Filter) Sum(org.opensearch.search.aggregations.metrics.Sum) Range(org.opensearch.search.aggregations.bucket.range.Range) OpenSearchAssertions.assertSearchResponse(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse)

Example 3 with Filter

use of org.opensearch.search.aggregations.bucket.filter.Filter in project OpenSearch by opensearch-project.

the class FilterIT method testAsSubAggregation.

public void testAsSubAggregation() {
    SearchResponse response = client().prepareSearch("idx").addAggregation(histogram("histo").field("value").interval(2L).subAggregation(filter("filter", matchAllQuery()))).get();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getBuckets().size(), greaterThanOrEqualTo(1));
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        Filter filter = bucket.getAggregations().get("filter");
        assertThat(filter, notNullValue());
        assertEquals(bucket.getDocCount(), filter.getDocCount());
    }
}
Also used : Histogram(org.opensearch.search.aggregations.bucket.histogram.Histogram) Filter(org.opensearch.search.aggregations.bucket.filter.Filter) OpenSearchAssertions.assertSearchResponse(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse)

Example 4 with Filter

use of org.opensearch.search.aggregations.bucket.filter.Filter in project OpenSearch by opensearch-project.

the class FilterIT method testEmptyFilterDeclarations.

// See NullPointer issue when filters are empty:
// https://github.com/elastic/elasticsearch/issues/8438
public void testEmptyFilterDeclarations() throws Exception {
    QueryBuilder emptyFilter = new BoolQueryBuilder();
    SearchResponse response = client().prepareSearch("idx").addAggregation(filter("tag1", emptyFilter)).get();
    assertSearchResponse(response);
    Filter filter = response.getAggregations().get("tag1");
    assertThat(filter, notNullValue());
    assertThat(filter.getDocCount(), equalTo((long) numDocs));
}
Also used : BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) Filter(org.opensearch.search.aggregations.bucket.filter.Filter) QueryBuilder(org.opensearch.index.query.QueryBuilder) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) OpenSearchAssertions.assertSearchResponse(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse)

Example 5 with Filter

use of org.opensearch.search.aggregations.bucket.filter.Filter in project OpenSearch by opensearch-project.

the class FilterIT method testWithSubAggregation.

public void testWithSubAggregation() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(filter("tag1", termQuery("tag", "tag1")).subAggregation(avg("avg_value").field("value"))).get();
    assertSearchResponse(response);
    Filter filter = response.getAggregations().get("tag1");
    assertThat(filter, notNullValue());
    assertThat(filter.getName(), equalTo("tag1"));
    assertThat(filter.getDocCount(), equalTo((long) numTag1Docs));
    assertThat((long) ((InternalAggregation) filter).getProperty("_count"), equalTo((long) numTag1Docs));
    long sum = 0;
    for (int i = 0; i < numTag1Docs; ++i) {
        sum += i + 1;
    }
    assertThat(filter.getAggregations().asList().isEmpty(), is(false));
    Avg avgValue = filter.getAggregations().get("avg_value");
    assertThat(avgValue, notNullValue());
    assertThat(avgValue.getName(), equalTo("avg_value"));
    assertThat(avgValue.getValue(), equalTo((double) sum / numTag1Docs));
    assertThat((double) ((InternalAggregation) filter).getProperty("avg_value.value"), equalTo((double) sum / numTag1Docs));
}
Also used : InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) Avg(org.opensearch.search.aggregations.metrics.Avg) Filter(org.opensearch.search.aggregations.bucket.filter.Filter) OpenSearchAssertions.assertSearchResponse(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse)

Aggregations

Filter (org.opensearch.search.aggregations.bucket.filter.Filter)41 SearchResponse (org.opensearch.action.search.SearchResponse)36 OpenSearchAssertions.assertSearchResponse (org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse)34 Terms (org.opensearch.search.aggregations.bucket.terms.Terms)22 Bucket (org.opensearch.search.aggregations.bucket.terms.Terms.Bucket)11 ArrayList (java.util.ArrayList)7 Histogram (org.opensearch.search.aggregations.bucket.histogram.Histogram)7 IndexReader (org.apache.lucene.index.IndexReader)5 RandomIndexWriter (org.apache.lucene.index.RandomIndexWriter)5 Directory (org.apache.lucene.store.Directory)5 MappedFieldType (org.opensearch.index.mapper.MappedFieldType)5 HashMap (java.util.HashMap)4 SortedNumericDocValuesField (org.apache.lucene.document.SortedNumericDocValuesField)4 IndexSearcher (org.apache.lucene.search.IndexSearcher)4 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)4 Map (java.util.Map)3 Document (org.apache.lucene.document.Document)3 IntPoint (org.apache.lucene.document.IntPoint)3 NumericDocValuesField (org.apache.lucene.document.NumericDocValuesField)3 Matchers.containsString (org.hamcrest.Matchers.containsString)3