org.elasticsearch.action.search.SearchResponse

Here are the examples of the java api class org.elasticsearch.action.search.SearchResponse taken from open source projects.

1. OpenNlpPluginIntegrationTest#testThatOwnAnalyzersCanBeDefinedPerNlpMappedField()

View license
@Test
public void testThatOwnAnalyzersCanBeDefinedPerNlpMappedField() throws IOException {
    putMapping("/test-mapping-analyzers.json");
    String sampleText = copyToStringFromClasspath("/sample-text.txt");
    IndexResponse indexResponse = indexElement(sampleText);
    SearchResponse nonAnalyzedFieldSearchResponse = query(QueryBuilders.termQuery("someField.name", "jack"));
    assertThat(nonAnalyzedFieldSearchResponse.getHits().totalHits(), is(1L));
    // analyzed, therefore not resulting anything like the above query
    SearchResponse analyzedFieldSearchResponse = query(QueryBuilders.termQuery("someFieldAnalyzed.name", "jack"));
    assertThat(analyzedFieldSearchResponse.getHits().totalHits(), is(0L));
    SearchResponse searchResponse = query(QueryBuilders.prefixQuery("someFieldAnalyzed.name", "Jack"));
    assertThat(searchResponse.getHits().totalHits(), is(1L));
    searchResponse = query(QueryBuilders.matchQuery("someFieldAnalyzed.name", "Jack Nicholson"));
    assertThat(searchResponse.getHits().totalHits(), is(1L));
    assertThat(searchResponse.getHits().getAt(0).id(), is(indexResponse.getId()));
}

2. GeoPolygonIT#testSimplePolygon()

Project: elasticsearch
Source File: GeoPolygonIT.java
View license
public void testSimplePolygon() throws Exception {
    List<GeoPoint> points = new ArrayList<>();
    points.add(new GeoPoint(40.7, -74.0));
    points.add(new GeoPoint(40.7, -74.1));
    points.add(new GeoPoint(40.8, -74.1));
    points.add(new GeoPoint(40.8, -74.0));
    points.add(new GeoPoint(40.7, -74.0));
    SearchResponse searchResponse = // from NY
    client().prepareSearch("test").setQuery(boolQuery().must(geoPolygonQuery("location", points))).execute().actionGet();
    assertHitCount(searchResponse, 4);
    assertThat(searchResponse.getHits().hits().length, equalTo(4));
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.id(), anyOf(equalTo("1"), equalTo("3"), equalTo("4"), equalTo("5")));
    }
}

3. GeoPolygonIT#testSimpleUnclosedPolygon()

Project: elasticsearch
Source File: GeoPolygonIT.java
View license
public void testSimpleUnclosedPolygon() throws Exception {
    List<GeoPoint> points = new ArrayList<>();
    points.add(new GeoPoint(40.7, -74.0));
    points.add(new GeoPoint(40.7, -74.1));
    points.add(new GeoPoint(40.8, -74.1));
    points.add(new GeoPoint(40.8, -74.0));
    SearchResponse searchResponse = // from NY
    client().prepareSearch("test").setQuery(boolQuery().must(geoPolygonQuery("location", points))).execute().actionGet();
    assertHitCount(searchResponse, 4);
    assertThat(searchResponse.getHits().hits().length, equalTo(4));
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.id(), anyOf(equalTo("1"), equalTo("3"), equalTo("4"), equalTo("5")));
    }
}

4. MatchedQueriesIT#testRegExpQuerySupportsName()

Project: elasticsearch
Source File: MatchedQueriesIT.java
View license
public void testRegExpQuerySupportsName() {
    createIndex("test1");
    ensureGreen();
    client().prepareIndex("test1", "type1", "1").setSource("title", "title1").get();
    refresh();
    SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.regexpQuery("title", "title1").queryName("regex")).get();
    assertHitCount(searchResponse, 1L);
    for (SearchHit hit : searchResponse.getHits()) {
        if (hit.id().equals("1")) {
            assertThat(hit.matchedQueries().length, equalTo(1));
            assertThat(hit.matchedQueries(), hasItemInArray("regex"));
        } else {
            fail("Unexpected document returned with id " + hit.id());
        }
    }
}

5. MatchedQueriesIT#testPrefixQuerySupportsName()

Project: elasticsearch
Source File: MatchedQueriesIT.java
View license
public void testPrefixQuerySupportsName() {
    createIndex("test1");
    ensureGreen();
    client().prepareIndex("test1", "type1", "1").setSource("title", "title1").get();
    refresh();
    SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.prefixQuery("title", "title").queryName("prefix")).get();
    assertHitCount(searchResponse, 1L);
    for (SearchHit hit : searchResponse.getHits()) {
        if (hit.id().equals("1")) {
            assertThat(hit.matchedQueries().length, equalTo(1));
            assertThat(hit.matchedQueries(), hasItemInArray("prefix"));
        } else {
            fail("Unexpected document returned with id " + hit.id());
        }
    }
}

6. MatchedQueriesIT#testFuzzyQuerySupportsName()

Project: elasticsearch
Source File: MatchedQueriesIT.java
View license
public void testFuzzyQuerySupportsName() {
    createIndex("test1");
    ensureGreen();
    client().prepareIndex("test1", "type1", "1").setSource("title", "title1").get();
    refresh();
    SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.fuzzyQuery("title", "titel1").queryName("fuzzy")).get();
    assertHitCount(searchResponse, 1L);
    for (SearchHit hit : searchResponse.getHits()) {
        if (hit.id().equals("1")) {
            assertThat(hit.matchedQueries().length, equalTo(1));
            assertThat(hit.matchedQueries(), hasItemInArray("fuzzy"));
        } else {
            fail("Unexpected document returned with id " + hit.id());
        }
    }
}

7. MatchedQueriesIT#testWildcardQuerySupportsName()

Project: elasticsearch
Source File: MatchedQueriesIT.java
View license
public void testWildcardQuerySupportsName() {
    createIndex("test1");
    ensureGreen();
    client().prepareIndex("test1", "type1", "1").setSource("title", "title1").get();
    refresh();
    SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.wildcardQuery("title", "titl*").queryName("wildcard")).get();
    assertHitCount(searchResponse, 1L);
    for (SearchHit hit : searchResponse.getHits()) {
        if (hit.id().equals("1")) {
            assertThat(hit.matchedQueries().length, equalTo(1));
            assertThat(hit.matchedQueries(), hasItemInArray("wildcard"));
        } else {
            fail("Unexpected document returned with id " + hit.id());
        }
    }
}

8. MatchedQueriesIT#testSpanFirstQuerySupportsName()

Project: elasticsearch
Source File: MatchedQueriesIT.java
View license
public void testSpanFirstQuerySupportsName() {
    createIndex("test1");
    ensureGreen();
    client().prepareIndex("test1", "type1", "1").setSource("title", "title1 title2").get();
    refresh();
    SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.spanFirstQuery(QueryBuilders.spanTermQuery("title", "title1"), 10).queryName("span")).get();
    assertHitCount(searchResponse, 1L);
    for (SearchHit hit : searchResponse.getHits()) {
        if (hit.id().equals("1")) {
            assertThat(hit.matchedQueries().length, equalTo(1));
            assertThat(hit.matchedQueries(), hasItemInArray("span"));
        } else {
            fail("Unexpected document returned with id " + hit.id());
        }
    }
}

9. FieldSortIT#testIssue2986()

Project: elasticsearch
Source File: FieldSortIT.java
View license
public void testIssue2986() {
    assertAcked(client().admin().indices().prepareCreate("test").addMapping("type", "field1", "type=keyword").get());
    client().prepareIndex("test", "post", "1").setSource("{\"field1\":\"value1\"}").execute().actionGet();
    client().prepareIndex("test", "post", "2").setSource("{\"field1\":\"value2\"}").execute().actionGet();
    client().prepareIndex("test", "post", "3").setSource("{\"field1\":\"value3\"}").execute().actionGet();
    refresh();
    SearchResponse result = client().prepareSearch("test").setQuery(matchAllQuery()).setTrackScores(true).addSort("field1", SortOrder.ASC).execute().actionGet();
    for (SearchHit hit : result.getHits()) {
        assertFalse(Float.isNaN(hit.getScore()));
    }
}

10. SuggestSearchIT#searchSuggest()

Project: elasticsearch
Source File: SuggestSearchIT.java
View license
protected Suggest searchSuggest(String suggestText, int expectShardsFailed, Map<String, SuggestionBuilder<?>> suggestions) {
    SearchRequestBuilder builder = client().prepareSearch().setSize(0);
    SuggestBuilder suggestBuilder = new SuggestBuilder();
    if (suggestText != null) {
        suggestBuilder.setGlobalText(suggestText);
    }
    for (Entry<String, SuggestionBuilder<?>> suggestion : suggestions.entrySet()) {
        suggestBuilder.addSuggestion(suggestion.getKey(), suggestion.getValue());
    }
    builder.suggest(suggestBuilder);
    SearchResponse actionGet = builder.execute().actionGet();
    assertThat(Arrays.toString(actionGet.getShardFailures()), actionGet.getFailedShards(), equalTo(expectShardsFailed));
    return actionGet.getSuggest();
}

11. SuggestSearchTests#searchSuggest()

View license
protected Suggest searchSuggest(String suggestText, int expectShardsFailed, Map<String, SuggestionBuilder<?>> suggestions) {
    SearchRequestBuilder builder = client().prepareSearch().setSize(0);
    SuggestBuilder suggestBuilder = new SuggestBuilder();
    if (suggestText != null) {
        suggestBuilder.setGlobalText(suggestText);
    }
    for (Entry<String, SuggestionBuilder<?>> suggestion : suggestions.entrySet()) {
        suggestBuilder.addSuggestion(suggestion.getKey(), suggestion.getValue());
    }
    builder.suggest(suggestBuilder);
    SearchResponse actionGet = builder.execute().actionGet();
    assertThat(Arrays.toString(actionGet.getShardFailures()), actionGet.getFailedShards(), equalTo(expectShardsFailed));
    return actionGet.getSuggest();
}

12. AggregationTest#testFromSizeWithAggregations()

View license
@Test
public void testFromSizeWithAggregations() throws Exception {
    final String query1 = String.format("SELECT /*! DOCS_WITH_AGGREGATION(0,1) */" + " account_number FROM %s/account GROUP BY gender", TEST_INDEX);
    SearchResponse response1 = (SearchResponse) getSearchRequestBuilder(query1).get();
    Assert.assertEquals(1, response1.getHits().getHits().length);
    Terms gender1 = response1.getAggregations().get("gender");
    Assert.assertEquals(2, gender1.getBuckets().size());
    Object account1 = response1.getHits().getHits()[0].getSource().get("account_number");
    final String query2 = String.format("SELECT /*! DOCS_WITH_AGGREGATION(1,1) */" + " account_number FROM %s/account GROUP BY gender", TEST_INDEX);
    SearchResponse response2 = (SearchResponse) getSearchRequestBuilder(query2).get();
    Assert.assertEquals(1, response2.getHits().getHits().length);
    Terms gender2 = response2.getAggregations().get("gender");
    Assert.assertEquals(2, gender2.getBuckets().size());
    Object account2 = response2.getHits().getHits()[0].getSource().get("account_number");
    Assert.assertEquals(response1.getHits().getTotalHits(), response2.getHits().getTotalHits());
    Assert.assertNotEquals(account1, account2);
}

13. FsCrawlerImplAllParametersTest#test_filesize_limit()

View license
@Test
public void test_filesize_limit() throws Exception {
    Fs fs = startCrawlerDefinition().setIndexedChars(new Percentage(7)).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1, null, null, "*");
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.CONTENT), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXED_CHARS), notNullValue());
        // Our original text: "Bonjour David..." should be truncated
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.CONTENT).getValue(), is("Bonjour"));
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXED_CHARS).getValue(), is(7L));
    }
}

14. FsCrawlerImplAllParametersTest#test_filesize_limit_percentage()

View license
@Test
public void test_filesize_limit_percentage() throws Exception {
    Fs fs = startCrawlerDefinition().setIndexedChars(Percentage.parse("0.1%")).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1, null, null, "*");
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.CONTENT), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXED_CHARS), notNullValue());
        // Our original text: "Bonjour David..." should be truncated
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.CONTENT).getValue(), is("Bonjour "));
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXED_CHARS).getValue(), is(8L));
    }
}

15. FsCrawlerImplAllParametersTest#test_filesize_nolimit()

View license
@Test
public void test_filesize_nolimit() throws Exception {
    Fs fs = startCrawlerDefinition().setIndexedChars(new Percentage(-1)).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1, null, null, "*");
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.CONTENT), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXED_CHARS), nullValue());
        // Our original text: "Bonjour David\n\n\n" should not be truncated
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.CONTENT).getValue(), is("Bonjour David\n\n\n"));
    }
}

16. FsCrawlerImplAllParametersTest#test_filesize_disabled()

View license
@Test
public void test_filesize_disabled() throws Exception {
    Fs fs = startCrawlerDefinition().setAddFilesize(false).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1);
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.getFields().get("filesize"), nullValue());
    }
}

17. FsCrawlerImplAllParametersTest#test_metadata()

View license
@Test
public void test_metadata() throws Exception {
    Fs fs = startCrawlerDefinition().setIndexedChars(new Percentage(1)).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1, null, null, "*");
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.FILENAME), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.CONTENT_TYPE), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.URL), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.FILESIZE), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXING_DATE), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXED_CHARS), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.LAST_MODIFIED), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.META + "." + FsCrawlerUtil.Doc.Meta.TITLE), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.META + "." + FsCrawlerUtil.Doc.Meta.KEYWORDS), notNullValue());
    }
}

18. FsCrawlerImplAllParametersTest#test_default_metadata()

View license
@Test
public void test_default_metadata() throws Exception {
    startCrawler();
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1, null, null, "*");
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.ATTACHMENT), nullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.FILENAME), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.CONTENT_TYPE), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.URL), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.FILESIZE), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXING_DATE), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.INDEXED_CHARS), nullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.FILE + "." + FsCrawlerUtil.Doc.File.LAST_MODIFIED), notNullValue());
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.META + "." + FsCrawlerUtil.Doc.Meta.TITLE), notNullValue());
    }
}

19. FsCrawlerImplAllParametersTest#test_store_source()

View license
@Test
public void test_store_source() throws Exception {
    Fs fs = startCrawlerDefinition().setStoreSource(true).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1, null, null, "_source", "*");
    for (SearchHit hit : searchResponse.getHits()) {
        // We check that the field has been stored
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.ATTACHMENT), notNullValue());
        // We check that the field is not part of _source
        assertThat(hit.getSource().get(FsCrawlerUtil.Doc.ATTACHMENT), nullValue());
    }
}

20. FsCrawlerImplAllParametersTest#test_do_not_store_source()

View license
@Test
public void test_do_not_store_source() throws Exception {
    startCrawler();
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1, null, null, "_source", "*");
    for (SearchHit hit : searchResponse.getHits()) {
        // We check that the field has not been stored
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.ATTACHMENT), nullValue());
        // We check that the field is not part of _source
        assertThat(hit.getSource().get(FsCrawlerUtil.Doc.ATTACHMENT), nullValue());
    }
}

21. FsCrawlerImplAllParametersTest#test_defaults()

View license
@Test
public void test_defaults() throws Exception {
    startCrawler();
    // We expect to have one file
    SearchResponse searchResponse = countTestHelper(getCrawlerName(), null, 1);
    // The default configuration should not add file attributes
    for (SearchHit hit : searchResponse.getHits()) {
        assertThat(hit.getFields().get(FsCrawlerUtil.Doc.ATTRIBUTES + "." + FsCrawlerUtil.Doc.Attributes.OWNER), nullValue());
    }
}

22. ESIndexer#search()

Project: Kundera
Source File: ESIndexer.java
View license
/*
     * (non-Javadoc)
     * 
     * @see com.impetus.kundera.index.Indexer#search(java.lang.Class,
     * com.impetus.kundera.metadata.model.EntityMetadata, java.lang.String, int,
     * int)
     */
@Override
public Map<String, Object> search(Class<?> clazz, EntityMetadata m, String luceneQuery, int start, int count) {
    if (log.isInfoEnabled()) {
        log.info("Executing lucene query " + luceneQuery);
    }
    ListenableActionFuture<SearchResponse> listenableActionFuture = client.prepareSearch(m.getSchema().toLowerCase()).setQuery(QueryBuilders.queryStringQuery(luceneQuery)).setSize(40000).execute();
    SearchResponse response = listenableActionFuture.actionGet();
    Map<String, Object> results = new HashMap<String, Object>();
    for (SearchHit hit : response.getHits()) {
        Object id = PropertyAccessorHelper.fromSourceToTargetClass(((AbstractAttribute) m.getIdAttribute()).getBindableJavaType(), String.class, hit.getId());
        results.put(hit.getId(), id);
    }
    return results;
}

23. ElasticSearchState#search()

View license
/**
     * It basically searches and returns a set of tweet ids for a given keyword.
     *
     * @param keyword
     * @return
     */
public Set<String> search(String keyword) {
    SearchResponse response;
    try {
        response = client.prepareSearch().setIndices("hackaton").setTypes("tweets").addFields("id", "text").setQuery(QueryBuilders.fieldQuery("text", keyword)).execute().actionGet();
    } catch (Throwable e) {
        return new HashSet<String>();
    }
    Set<String> result = new HashSet<String>();
    for (SearchHit hit : response.getHits()) {
        Long id = hit.field("id").<Long>getValue();
        result.add(String.valueOf(id));
    }
    return result;
}

24. ElasticsearchGetSearchDeleteExistsUpdateTest#testSearch()

View license
@Test
public void testSearch() throws Exception {
    //first, INDEX a value
    Map<String, String> map = createIndexedData();
    sendBody("direct:index", map);
    //now, verify GET succeeded
    Map<String, Object> actualQuery = new HashMap<String, Object>();
    actualQuery.put("content", "searchtest");
    Map<String, Object> match = new HashMap<String, Object>();
    match.put("match", actualQuery);
    Map<String, Object> query = new HashMap<String, Object>();
    query.put("query", match);
    SearchResponse response = template.requestBody("direct:search", query, SearchResponse.class);
    assertNotNull("response should not be null", response);
    assertNotNull("response hits should be == 1", response.getHits().totalHits());
}

25. MappingDefaultsTest#testAllFieldsDisabled()

Project: crate
Source File: MappingDefaultsTest.java
View license
@Test
public void testAllFieldsDisabled() throws Exception {
    execute("create table test (col1 string)");
    ensureYellow();
    SQLResponse sqlResponse = execute("insert into test (col1) values ('foo')");
    assertEquals(1, sqlResponse.rowCount());
    refresh();
    byte[] searchSource = XContentFactory.jsonBuilder().startObject().startObject("query").startObject("query_string").field("query", "foo").endObject().endObject().endObject().bytes().toBytes();
    SearchRequest searchRequest = new SearchRequest("test");
    searchRequest.source(searchSource);
    SearchResponse response = client().search(searchRequest).actionGet();
    assertEquals(0L, response.getHits().totalHits());
}

26. IndexAliasesIT#testAliasesFilterWithHasChildQuery()

Project: elasticsearch
Source File: IndexAliasesIT.java
View license
public void testAliasesFilterWithHasChildQuery() throws Exception {
    assertAcked(prepareCreate("my-index").addMapping("parent").addMapping("child", "_parent", "type=parent"));
    client().prepareIndex("my-index", "parent", "1").setSource("{}").get();
    client().prepareIndex("my-index", "child", "2").setSource("{}").setParent("1").get();
    refresh();
    assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter1", hasChildQuery("child", matchAllQuery(), ScoreMode.None)));
    assertAcked(admin().indices().prepareAliases().addAlias("my-index", "filter2", hasParentQuery("parent", matchAllQuery(), false)));
    SearchResponse response = client().prepareSearch("filter1").get();
    assertHitCount(response, 1);
    assertThat(response.getHits().getAt(0).id(), equalTo("1"));
    response = client().prepareSearch("filter2").get();
    assertHitCount(response, 1);
    assertThat(response.getHits().getAt(0).id(), equalTo("2"));
}

27. IpFieldBwCompatIT#testRangeAgg()

View license
public void testRangeAgg() {
    SearchResponse response = client().prepareSearch("old_index", "new_index").addAggregation(AggregationBuilders.ipRange("ip_range").field("ip_field").addMaskRange("127.0.0.1/16").addMaskRange("::1/64")).get();
    assertNoFailures(response);
    assertEquals(3, response.getHits().totalHits());
    Range range = response.getAggregations().get("ip_range");
    assertEquals(2, range.getBuckets().size());
    assertEquals("::1/64", range.getBuckets().get(0).getKeyAsString());
    assertEquals(3, range.getBuckets().get(0).getDocCount());
    assertEquals("127.0.0.1/16", range.getBuckets().get(1).getKeyAsString());
    assertEquals(2, range.getBuckets().get(1).getDocCount());
}

28. OldIndexBackwardsCompatibilityIT#assertIndexSanity()

View license
void assertIndexSanity(String indexName, Version indexCreated) {
    GetIndexResponse getIndexResponse = client().admin().indices().prepareGetIndex().addIndices(indexName).get();
    assertEquals(1, getIndexResponse.indices().length);
    assertEquals(indexName, getIndexResponse.indices()[0]);
    Version actualVersionCreated = Version.indexCreated(getIndexResponse.getSettings().get(indexName));
    assertEquals(indexCreated, actualVersionCreated);
    ensureYellow(indexName);
    IndicesSegmentResponse segmentsResponse = client().admin().indices().prepareSegments(indexName).get();
    IndexSegments segments = segmentsResponse.getIndices().get(indexName);
    for (IndexShardSegments indexShardSegments : segments) {
        for (ShardSegments shardSegments : indexShardSegments) {
            for (Segment segment : shardSegments) {
                assertEquals(indexCreated.luceneVersion, segment.version);
            }
        }
    }
    SearchResponse test = client().prepareSearch(indexName).get();
    assertThat(test.getHits().getTotalHits(), greaterThanOrEqualTo(1L));
}

29. OldIndexBackwardsCompatibilityIT#assertBasicSearchWorks()

View license
void assertBasicSearchWorks(String indexName) {
    logger.info("--> testing basic search");
    SearchRequestBuilder searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.matchAllQuery());
    SearchResponse searchRsp = searchReq.get();
    ElasticsearchAssertions.assertNoFailures(searchRsp);
    long numDocs = searchRsp.getHits().getTotalHits();
    logger.info("Found {} in old index", numDocs);
    logger.info("--> testing basic search with sort");
    searchReq.addSort("long_sort", SortOrder.ASC);
    ElasticsearchAssertions.assertNoFailures(searchReq.get());
    logger.info("--> testing exists filter");
    searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.existsQuery("string"));
    searchRsp = searchReq.get();
    ElasticsearchAssertions.assertNoFailures(searchRsp);
    assertEquals(numDocs, searchRsp.getHits().getTotalHits());
}

30. OldIndexBackwardsCompatibilityIT#assertAllSearchWorks()

View license
void assertAllSearchWorks(String indexName) {
    logger.info("--> testing _all search");
    SearchResponse searchRsp = client().prepareSearch(indexName).get();
    ElasticsearchAssertions.assertNoFailures(searchRsp);
    assertThat(searchRsp.getHits().getTotalHits(), greaterThanOrEqualTo(1L));
    SearchHit bestHit = searchRsp.getHits().getAt(0);
    // Make sure there are payloads and they are taken into account for the score
    // the 'string' field has a boost of 4 in the mappings so it should get a payload boost
    String stringValue = (String) bestHit.sourceAsMap().get("string");
    assertNotNull(stringValue);
    Explanation explanation = client().prepareExplain(indexName, bestHit.getType(), bestHit.getId()).setQuery(QueryBuilders.matchQuery("_all", stringValue)).get().getExplanation();
    assertTrue("Could not find payload boost in explanation\n" + explanation, findPayloadBoostInExplanation(explanation));
    // Make sure the query can run on the whole index
    searchRsp = client().prepareSearch(indexName).setQuery(QueryBuilders.matchQuery("_all", stringValue)).setExplain(true).get();
    ElasticsearchAssertions.assertNoFailures(searchRsp);
    assertThat(searchRsp.getHits().getTotalHits(), greaterThanOrEqualTo(1L));
}

31. OldIndexBackwardsCompatibilityIT#assertBasicAggregationWorks()

View license
void assertBasicAggregationWorks(String indexName) {
    // histogram on a long
    SearchResponse searchRsp = client().prepareSearch(indexName).addAggregation(AggregationBuilders.histogram("histo").field("long_sort").interval(10)).get();
    ElasticsearchAssertions.assertSearchResponse(searchRsp);
    Histogram histo = searchRsp.getAggregations().get("histo");
    assertNotNull(histo);
    long totalCount = 0;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        totalCount += bucket.getDocCount();
    }
    assertEquals(totalCount, searchRsp.getHits().getTotalHits());
    // terms on a boolean
    searchRsp = client().prepareSearch(indexName).addAggregation(AggregationBuilders.terms("bool_terms").field("bool")).get();
    Terms terms = searchRsp.getAggregations().get("bool_terms");
    totalCount = 0;
    for (Terms.Bucket bucket : terms.getBuckets()) {
        totalCount += bucket.getDocCount();
    }
    assertEquals(totalCount, searchRsp.getHits().getTotalHits());
}

32. IndexRequestBuilderIT#testSetSource()

View license
public void testSetSource() throws InterruptedException, ExecutionException {
    createIndex("test");
    ensureYellow();
    Map<String, Object> map = new HashMap<>();
    map.put("test_field", "foobar");
    IndexRequestBuilder[] builders = new IndexRequestBuilder[] { client().prepareIndex("test", "test").setSource((Object) "test_field", (Object) "foobar"), client().prepareIndex("test", "test").setSource("{\"test_field\" : \"foobar\"}"), client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}")), client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}")), client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}").toBytes()), client().prepareIndex("test", "test").setSource(map) };
    indexRandom(true, builders);
    SearchResponse searchResponse = client().prepareSearch("test").setQuery(QueryBuilders.termQuery("test_field", "foobar")).get();
    ElasticsearchAssertions.assertHitCount(searchResponse, builders.length);
}

33. CopyToMapperIntegrationIT#testDynamicObjectCopyTo()

View license
public void testDynamicObjectCopyTo() throws Exception {
    String mapping = jsonBuilder().startObject().startObject("doc").startObject("properties").startObject("foo").field("type", "text").field("copy_to", "root.top.child").endObject().endObject().endObject().endObject().string();
    assertAcked(client().admin().indices().prepareCreate("test-idx").addMapping("doc", mapping));
    client().prepareIndex("test-idx", "doc", "1").setSource("foo", "bar").get();
    client().admin().indices().prepareRefresh("test-idx").execute().actionGet();
    SearchResponse response = client().prepareSearch("test-idx").setQuery(QueryBuilders.termQuery("root.top.child", "bar")).get();
    assertThat(response.getHits().totalHits(), equalTo(1L));
}

34. TokenCountFieldMapperIntegrationIT#testFacetByTokenCount()

View license
/**
     * It is possible to search by token count.
     */
public void testFacetByTokenCount() throws IOException {
    init();
    String facetField = randomFrom(Arrays.asList("foo.token_count", "foo.token_count_unstored", "foo.token_count_with_doc_values"));
    SearchResponse result = searchByNumericRange(1, 10).addAggregation(AggregationBuilders.terms("facet").field(facetField)).get();
    assertSearchReturns(result, "single", "bulk1", "bulk2", "multi", "multibulk1", "multibulk2");
    assertThat(result.getAggregations().asList().size(), equalTo(1));
    Terms terms = (Terms) result.getAggregations().asList().get(0);
    assertThat(terms.getBuckets().size(), equalTo(9));
}

35. GeoPointFieldMapperTests#testGeoHashSearch()

View license
public void testGeoHashSearch() throws Exception {
    // create a geo_point mapping with geohash enabled and random (between 1 and 12) geohash precision
    int precision = randomIntBetween(1, 12);
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("pin").startObject("properties").startObject("location").field("type", "geo_point").field("geohash", true).field("geohash_precision", precision).field("store", true).endObject().endObject().endObject().endObject().string();
    // create index and add a test point (dr5regy6rc6z)
    Version version = VersionUtils.randomVersionBetween(random(), Version.V_2_0_0, Version.CURRENT);
    Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
    CreateIndexRequestBuilder mappingRequest = client().admin().indices().prepareCreate("test").setSettings(settings).addMapping("pin", mapping);
    mappingRequest.execute().actionGet();
    client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();
    client().prepareIndex("test", "pin", "1").setSource(jsonBuilder().startObject().startObject("location").field("lat", 40.7143528).field("lon", -74.0059731).endObject().endObject()).setRefreshPolicy(IMMEDIATE).get();
    // match all search with geohash field
    SearchResponse searchResponse = client().prepareSearch().addField("location.geohash").setQuery(matchAllQuery()).execute().actionGet();
    Map<String, SearchHitField> m = searchResponse.getHits().getAt(0).getFields();
    // ensure single geohash was indexed
    assertEquals("dr5regy6rc6y".substring(0, precision), m.get("location.geohash").value());
}

36. MultiFieldsIntegrationIT#testCompletionMultiField()

View license
public void testCompletionMultiField() throws Exception {
    assertAcked(client().admin().indices().prepareCreate("my-index").addMapping("my-type", createMappingSource("completion")));
    GetMappingsResponse getMappingsResponse = client().admin().indices().prepareGetMappings("my-index").get();
    MappingMetaData mappingMetaData = getMappingsResponse.mappings().get("my-index").get("my-type");
    assertThat(mappingMetaData, not(nullValue()));
    Map<String, Object> mappingSource = mappingMetaData.sourceAsMap();
    Map aField = ((Map) XContentMapValues.extractValue("properties.a", mappingSource));
    assertThat(aField.size(), equalTo(6));
    assertThat(aField.get("type").toString(), equalTo("completion"));
    assertThat(aField.get("fields"), notNullValue());
    Map bField = ((Map) XContentMapValues.extractValue("properties.a.fields.b", mappingSource));
    assertThat(bField.size(), equalTo(1));
    assertThat(bField.get("type").toString(), equalTo("keyword"));
    client().prepareIndex("my-index", "my-type", "1").setSource("a", "complete me").setRefreshPolicy(IMMEDIATE).get();
    SearchResponse countResponse = client().prepareSearch("my-index").setSize(0).setQuery(matchQuery("a.b", "complete me")).get();
    assertThat(countResponse.getHits().totalHits(), equalTo(1L));
}

37. MultiFieldsIntegrationIT#testIpMultiField()

View license
public void testIpMultiField() throws Exception {
    assertAcked(client().admin().indices().prepareCreate("my-index").addMapping("my-type", createMappingSource("ip")));
    GetMappingsResponse getMappingsResponse = client().admin().indices().prepareGetMappings("my-index").get();
    MappingMetaData mappingMetaData = getMappingsResponse.mappings().get("my-index").get("my-type");
    assertThat(mappingMetaData, not(nullValue()));
    Map<String, Object> mappingSource = mappingMetaData.sourceAsMap();
    Map aField = ((Map) XContentMapValues.extractValue("properties.a", mappingSource));
    assertThat(aField.size(), equalTo(2));
    assertThat(aField.get("type").toString(), equalTo("ip"));
    assertThat(aField.get("fields"), notNullValue());
    Map bField = ((Map) XContentMapValues.extractValue("properties.a.fields.b", mappingSource));
    assertThat(bField.size(), equalTo(1));
    assertThat(bField.get("type").toString(), equalTo("keyword"));
    client().prepareIndex("my-index", "my-type", "1").setSource("a", "127.0.0.1").setRefreshPolicy(IMMEDIATE).get();
    SearchResponse countResponse = client().prepareSearch("my-index").setSize(0).setQuery(matchQuery("a.b", "127.0.0.1")).get();
    assertThat(countResponse.getHits().totalHits(), equalTo(1L));
}

38. CommonTermsQueryParserTests#testWhenParsedQueryIsNullNoNullPointerExceptionIsThrown()

View license
public void testWhenParsedQueryIsNullNoNullPointerExceptionIsThrown() throws IOException {
    final String index = "test-index";
    final String type = "test-type";
    client().admin().indices().prepareCreate(index).addMapping(type, "name", "type=text,analyzer=stop").execute().actionGet();
    ensureGreen();
    CommonTermsQueryBuilder commonTermsQueryBuilder = new CommonTermsQueryBuilder("name", "the").queryName("query-name");
    // the named query parses to null; we are testing this does not cause a NullPointerException
    SearchResponse response = client().prepareSearch(index).setTypes(type).setQuery(commonTermsQueryBuilder).execute().actionGet();
    assertNotNull(response);
    assertEquals(response.getHits().hits().length, 0);
}

39. IndexShardTests#testRecoverIntoLeftover()

Project: elasticsearch
Source File: IndexShardTests.java
View license
public void testRecoverIntoLeftover() throws IOException {
    createIndex("test");
    ensureGreen("test");
    client().prepareIndex("test", "bar", "1").setSource("{}").setRefreshPolicy(IMMEDIATE).get();
    client().admin().indices().prepareFlush("test").get();
    SearchResponse response = client().prepareSearch("test").get();
    assertHitCount(response, 1L);
    IndicesService indicesService = getInstanceFromNode(IndicesService.class);
    IndexService test = indicesService.indexService(resolveIndex("test"));
    IndexShard shard = test.getShardOrNull(0);
    ShardPath shardPath = shard.shardPath();
    Path dataPath = shardPath.getDataPath();
    client().admin().indices().prepareClose("test").get();
    Path tempDir = createTempDir();
    Files.move(dataPath, tempDir.resolve("test"));
    client().admin().indices().prepareDelete("test").get();
    Files.createDirectories(dataPath.getParent());
    Files.move(tempDir.resolve("test"), dataPath);
    createIndex("test");
    ensureGreen("test");
    response = client().prepareSearch("test").get();
    assertHitCount(response, 0L);
}

40. IndexShardTests#testIndexDirIsDeletedWhenShardRemoved()

Project: elasticsearch
Source File: IndexShardTests.java
View license
public void testIndexDirIsDeletedWhenShardRemoved() throws Exception {
    Environment env = getInstanceFromNode(Environment.class);
    Path idxPath = env.sharedDataFile().resolve(randomAsciiOfLength(10));
    logger.info("--> idxPath: [{}]", idxPath);
    Settings idxSettings = Settings.builder().put(IndexMetaData.SETTING_DATA_PATH, idxPath).build();
    createIndex("test", idxSettings);
    ensureGreen("test");
    client().prepareIndex("test", "bar", "1").setSource("{}").setRefreshPolicy(IMMEDIATE).get();
    SearchResponse response = client().prepareSearch("test").get();
    assertHitCount(response, 1L);
    client().admin().indices().prepareDelete("test").get();
    assertAllIndicesRemovedAndDeletionCompleted(Collections.singleton(getInstanceFromNode(IndicesService.class)));
    assertPathHasBeenCleared(idxPath);
}

41. DateMathIndexExpressionsIntegrationIT#testAutoCreateIndexWithDateMathExpression()

View license
public void testAutoCreateIndexWithDateMathExpression() throws Exception {
    DateTime now = new DateTime(DateTimeZone.UTC);
    String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
    String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
    String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));
    String dateMathExp1 = "<.marvel-{now/d}>";
    String dateMathExp2 = "<.marvel-{now/d-1d}>";
    String dateMathExp3 = "<.marvel-{now/d-2d}>";
    client().prepareIndex(dateMathExp1, "type", "1").setSource("{}").get();
    client().prepareIndex(dateMathExp2, "type", "2").setSource("{}").get();
    client().prepareIndex(dateMathExp3, "type", "3").setSource("{}").get();
    refresh();
    SearchResponse searchResponse = client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertHitCount(searchResponse, 3);
    assertSearchHits(searchResponse, "1", "2", "3");
    IndicesStatsResponse indicesStatsResponse = client().admin().indices().prepareStats(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertThat(indicesStatsResponse.getIndex(index1), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index2), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index3), notNullValue());
}

42. IndicesOptionsIntegrationIT#testAllMissingLenient()

View license
public void testAllMissingLenient() throws Exception {
    createIndex("test1");
    client().prepareIndex("test1", "type", "1").setSource("k", "v").setRefreshPolicy(IMMEDIATE).get();
    SearchResponse response = client().prepareSearch("test2").setIndicesOptions(IndicesOptions.lenientExpandOpen()).setQuery(matchAllQuery()).execute().actionGet();
    assertHitCount(response, 0L);
    response = client().prepareSearch("test2", "test3").setQuery(matchAllQuery()).setIndicesOptions(IndicesOptions.lenientExpandOpen()).execute().actionGet();
    assertHitCount(response, 0L);
    //you should still be able to run empty searches without things blowing up
    response = client().prepareSearch().setIndicesOptions(IndicesOptions.lenientExpandOpen()).setQuery(matchAllQuery()).execute().actionGet();
    assertHitCount(response, 1L);
}

43. AliasRoutingIT#testAliasSearchRoutingWithConcreteAndAliasedIndices_issue3268()

Project: elasticsearch
Source File: AliasRoutingIT.java
View license
/*
    See https://github.com/elastic/elasticsearch/pull/3268
    Searching on more than one index, if one of those is an alias with configured routing, the shards that belonged
    to the other indices (without routing) were not taken into account in PlainOperationRouting#searchShardsCount.
    That could cause returning 1, which led to forcing the QUERY_AND_FETCH mode.
    As a result, (size * number of hit shards) results were returned and no reduce phase was taking place.
     */
public void testAliasSearchRoutingWithConcreteAndAliasedIndices_issue3268() throws Exception {
    createIndex("index", "index_2");
    ensureGreen();
    assertAcked(admin().indices().prepareAliases().addAliasAction(newAddAliasAction("index", "index_1").routing("1")));
    logger.info("--> indexing on index_1 which is an alias for index with routing [1]");
    client().prepareIndex("index_1", "type1", "1").setSource("field", "value1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
    logger.info("--> indexing on index_2 which is a concrete index");
    client().prepareIndex("index_2", "type2", "2").setSource("field", "value2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
    SearchResponse searchResponse = client().prepareSearch("index_*").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(1).setQuery(QueryBuilders.matchAllQuery()).execute().actionGet();
    logger.info("--> search all on index_* should find two");
    assertThat(searchResponse.getHits().totalHits(), equalTo(2L));
    //Let's make sure that, even though 2 docs are available, only one is returned according to the size we set in the request
    //Therefore the reduce phase has taken place, which proves that the QUERY_AND_FETCH search type wasn't erroneously forced.
    assertThat(searchResponse.getHits().getHits().length, equalTo(1));
}

44. AggregationsIntegrationIT#testScroll()

View license
public void testScroll() {
    final int size = randomIntBetween(1, 4);
    SearchResponse response = client().prepareSearch("index").setSize(size).setScroll(new TimeValue(500)).addAggregation(terms("f").field("f")).get();
    assertSearchResponse(response);
    Aggregations aggregations = response.getAggregations();
    assertNotNull(aggregations);
    Terms terms = aggregations.get("f");
    assertEquals(Math.min(numDocs, 3L), terms.getBucketByKey("0").getDocCount());
    int total = response.getHits().getHits().length;
    while (response.getHits().hits().length > 0) {
        response = client().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(500)).execute().actionGet();
        assertNull(response.getAggregations());
        total += response.getHits().hits().length;
    }
    clearScroll(response.getScrollId());
    assertEquals(numDocs, total);
}

45. BooleanTermsIT#testUnmapped()

Project: elasticsearch
Source File: BooleanTermsIT.java
View license
public void testUnmapped() throws Exception {
    SearchResponse response = client().prepareSearch("idx_unmapped").setTypes("type").addAggregation(terms("terms").field(SINGLE_VALUED_FIELD_NAME).size(between(1, 5)).collectMode(randomFrom(SubAggCollectionMode.values()))).execute().actionGet();
    assertSearchResponse(response);
    Terms terms = response.getAggregations().get("terms");
    assertThat(terms, notNullValue());
    assertThat(terms.getName(), equalTo("terms"));
    assertThat(terms.getBuckets().size(), equalTo(0));
}

46. DateHistogramIT#testSingleValuedFieldOrderedByKeyAsc()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testSingleValuedFieldOrderedByKeyAsc() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.MONTH).order(Histogram.Order.KEY_ASC)).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    List<? extends Bucket> buckets = histo.getBuckets();
    assertThat(buckets.size(), equalTo(3));
    int i = 0;
    for (Histogram.Bucket bucket : buckets) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i++;
    }
}

47. DateHistogramIT#testSingleValuedFieldOrderedByKeyDesc()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testSingleValuedFieldOrderedByKeyDesc() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.MONTH).order(Histogram.Order.KEY_DESC)).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(3));
    int i = 2;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i--;
    }
}

48. DateHistogramIT#testSingleValuedFieldOrderedByCountAsc()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testSingleValuedFieldOrderedByCountAsc() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.MONTH).order(Histogram.Order.COUNT_ASC)).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(3));
    int i = 0;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i++;
    }
}

49. DateHistogramIT#testSingleValuedFieldOrderedByCountDesc()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testSingleValuedFieldOrderedByCountDesc() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.MONTH).order(Histogram.Order.COUNT_DESC)).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(3));
    int i = 2;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i--;
    }
}

50. DateHistogramIT#testSingleValuedFieldOrderedBySubAggregationAsc()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testSingleValuedFieldOrderedBySubAggregationAsc() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.MONTH).order(Histogram.Order.aggregation("sum", true)).subAggregation(max("sum").field("value"))).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(3));
    int i = 0;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i++;
    }
}

51. DateHistogramIT#testSingleValuedFieldOrderedBySubAggregationDesc()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testSingleValuedFieldOrderedBySubAggregationDesc() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.MONTH).order(Histogram.Order.aggregation("sum", false)).subAggregation(max("sum").field("value"))).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(3));
    int i = 2;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i--;
    }
}

52. DateHistogramIT#testSingleValuedFieldOrderedByMultiValuedSubAggregationDesc()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testSingleValuedFieldOrderedByMultiValuedSubAggregationDesc() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.MONTH).order(Histogram.Order.aggregation("stats", "sum", false)).subAggregation(stats("stats").field("value"))).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(3));
    int i = 2;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i--;
    }
}

53. DateHistogramIT#testUnmapped()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
/*
    [ Jan 2, Feb 3]
    [ Feb 2, Mar 3]
    [ Feb 15, Mar 16]
    [ Mar 2, Apr 3]
    [ Mar 15, Apr 16]
    [ Mar 23, Apr 24]
     */
public void testUnmapped() throws Exception {
    SearchResponse response = client().prepareSearch("idx_unmapped").addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.MONTH)).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(0));
}

54. DateHistogramIT#testEmptyAggregation()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testEmptyAggregation() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx").setQuery(matchAllQuery()).addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(dateHistogram("date_histo").field("value").interval(1))).execute().actionGet();
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    Histogram histo = searchResponse.getAggregations().get("histo");
    assertThat(histo, Matchers.notNullValue());
    List<? extends Histogram.Bucket> buckets = histo.getBuckets();
    assertThat(buckets.size(), equalTo(3));
    Histogram.Bucket bucket = buckets.get(1);
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getKeyAsString(), equalTo("1"));
    Histogram dateHisto = bucket.getAggregations().get("date_histo");
    assertThat(dateHisto, Matchers.notNullValue());
    assertThat(dateHisto.getName(), equalTo("date_histo"));
    assertThat(dateHisto.getBuckets().isEmpty(), is(true));
}

55. DateHistogramIT#testDSTBoundaryIssue9491()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testDSTBoundaryIssue9491() throws InterruptedException, ExecutionException {
    assertAcked(client().admin().indices().prepareCreate("test9491").addMapping("type", "d", "type=date").get());
    indexRandom(true, client().prepareIndex("test9491", "type").setSource("d", "2014-10-08T13:00:00Z"), client().prepareIndex("test9491", "type").setSource("d", "2014-11-08T13:00:00Z"));
    ensureSearchable("test9491");
    SearchResponse response = client().prepareSearch("test9491").addAggregation(dateHistogram("histo").field("d").dateHistogramInterval(DateHistogramInterval.YEAR).timeZone(DateTimeZone.forID("Asia/Jerusalem"))).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(1));
    assertThat(histo.getBuckets().get(0).getKeyAsString(), equalTo("2014-01-01T00:00:00.000+02:00"));
    internalCluster().wipeIndices("test9491");
}

56. DateHistogramIT#testIssue8209()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
public void testIssue8209() throws InterruptedException, ExecutionException {
    assertAcked(client().admin().indices().prepareCreate("test8209").addMapping("type", "d", "type=date").get());
    indexRandom(true, client().prepareIndex("test8209", "type").setSource("d", "2014-01-01T00:00:00Z"), client().prepareIndex("test8209", "type").setSource("d", "2014-04-01T00:00:00Z"), client().prepareIndex("test8209", "type").setSource("d", "2014-04-30T00:00:00Z"));
    ensureSearchable("test8209");
    SearchResponse response = client().prepareSearch("test8209").addAggregation(dateHistogram("histo").field("d").dateHistogramInterval(DateHistogramInterval.MONTH).timeZone(DateTimeZone.forID("CET")).minDocCount(0)).execute().actionGet();
    assertSearchResponse(response);
    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
    assertThat(histo.getBuckets().get(0).getKeyAsString(), equalTo("2014-01-01T00:00:00.000+01:00"));
    assertThat(histo.getBuckets().get(0).getDocCount(), equalTo(1L));
    assertThat(histo.getBuckets().get(1).getKeyAsString(), equalTo("2014-02-01T00:00:00.000+01:00"));
    assertThat(histo.getBuckets().get(1).getDocCount(), equalTo(0L));
    assertThat(histo.getBuckets().get(2).getKeyAsString(), equalTo("2014-03-01T00:00:00.000+01:00"));
    assertThat(histo.getBuckets().get(2).getDocCount(), equalTo(0L));
    assertThat(histo.getBuckets().get(3).getKeyAsString(), equalTo("2014-04-01T00:00:00.000+02:00"));
    assertThat(histo.getBuckets().get(3).getDocCount(), equalTo(2L));
    internalCluster().wipeIndices("test8209");
}

57. DateHistogramIT#testDSTEndTransition()

Project: elasticsearch
Source File: DateHistogramIT.java
View license
/**
     * When DST ends, local time turns back one hour, so between 2am and 4am wall time we should have four buckets:
     * "2015-10-25T02:00:00.000+02:00",
     * "2015-10-25T02:00:00.000+01:00",
     * "2015-10-25T03:00:00.000+01:00",
     * "2015-10-25T04:00:00.000+01:00".
     */
public void testDSTEndTransition() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(new MatchNoneQueryBuilder()).addAggregation(dateHistogram("histo").field("date").timeZone(DateTimeZone.forID("Europe/Oslo")).dateHistogramInterval(DateHistogramInterval.HOUR).minDocCount(0).extendedBounds(new ExtendedBounds("2015-10-25T02:00:00.000+02:00", "2015-10-25T04:00:00.000+01:00"))).execute().actionGet();
    Histogram histo = response.getAggregations().get("histo");
    List<? extends Bucket> buckets = histo.getBuckets();
    assertThat(buckets.size(), equalTo(4));
    assertThat(((DateTime) buckets.get(1).getKey()).getMillis() - ((DateTime) buckets.get(0).getKey()).getMillis(), equalTo(3600000L));
    assertThat(((DateTime) buckets.get(2).getKey()).getMillis() - ((DateTime) buckets.get(1).getKey()).getMillis(), equalTo(3600000L));
    assertThat(((DateTime) buckets.get(3).getKey()).getMillis() - ((DateTime) buckets.get(2).getKey()).getMillis(), equalTo(3600000L));
}

58. DateHistogramOffsetIT#testSingleValueWithPositiveOffset()

View license
public void testSingleValueWithPositiveOffset() throws Exception {
    prepareIndex(date("2014-03-11T00:00:00+00:00"), 5, 1, 0);
    SearchResponse response = client().prepareSearch("idx2").setQuery(matchAllQuery()).addAggregation(dateHistogram("date_histo").field("date").offset("2h").format(DATE_FORMAT).dateHistogramInterval(DateHistogramInterval.DAY)).execute().actionGet();
    assertThat(response.getHits().getTotalHits(), equalTo(5L));
    Histogram histo = response.getAggregations().get("date_histo");
    List<? extends Histogram.Bucket> buckets = histo.getBuckets();
    assertThat(buckets.size(), equalTo(2));
    checkBucketFor(buckets.get(0), new DateTime(2014, 3, 10, 2, 0, DateTimeZone.UTC), 2L);
    checkBucketFor(buckets.get(1), new DateTime(2014, 3, 11, 2, 0, DateTimeZone.UTC), 3L);
}

59. DateHistogramOffsetIT#testSingleValueWithNegativeOffset()

View license
public void testSingleValueWithNegativeOffset() throws Exception {
    prepareIndex(date("2014-03-11T00:00:00+00:00"), 5, -1, 0);
    SearchResponse response = client().prepareSearch("idx2").setQuery(matchAllQuery()).addAggregation(dateHistogram("date_histo").field("date").offset("-2h").format(DATE_FORMAT).dateHistogramInterval(DateHistogramInterval.DAY)).execute().actionGet();
    assertThat(response.getHits().getTotalHits(), equalTo(5L));
    Histogram histo = response.getAggregations().get("date_histo");
    List<? extends Histogram.Bucket> buckets = histo.getBuckets();
    assertThat(buckets.size(), equalTo(2));
    checkBucketFor(buckets.get(0), new DateTime(2014, 3, 9, 22, 0, DateTimeZone.UTC), 2L);
    checkBucketFor(buckets.get(1), new DateTime(2014, 3, 10, 22, 0, DateTimeZone.UTC), 3L);
}

60. DateRangeIT#testEmptyAggregation()

Project: elasticsearch
Source File: DateRangeIT.java
View license
public void testEmptyAggregation() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx").setQuery(matchAllQuery()).addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(dateRange("date_range").field("value").addRange("0-1", 0, 1))).execute().actionGet();
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    Histogram histo = searchResponse.getAggregations().get("histo");
    assertThat(histo, Matchers.notNullValue());
    Histogram.Bucket bucket = histo.getBuckets().get(1);
    assertThat(bucket, Matchers.notNullValue());
    Range dateRange = bucket.getAggregations().get("date_range");
    // TODO: use diamond once JI-9019884 is fixed
    List<Range.Bucket> buckets = new ArrayList<Range.Bucket>(dateRange.getBuckets());
    assertThat(dateRange, Matchers.notNullValue());
    assertThat(dateRange.getName(), equalTo("date_range"));
    assertThat(buckets.size(), is(1));
    assertThat((String) buckets.get(0).getKey(), equalTo("0-1"));
    assertThat(((DateTime) buckets.get(0).getFrom()).getMillis(), equalTo(0L));
    assertThat(((DateTime) buckets.get(0).getTo()).getMillis(), equalTo(1L));
    assertThat(buckets.get(0).getDocCount(), equalTo(0L));
    assertThat(buckets.get(0).getAggregations().asList().isEmpty(), is(true));
}

61. DiversifiedSamplerIT#testSimpleDiversity()

View license
public void testSimpleDiversity() throws Exception {
    int MAX_DOCS_PER_AUTHOR = 1;
    DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100);
    sampleAgg.field("author").maxDocsPerValue(MAX_DOCS_PER_AUTHOR).executionHint(randomExecutionHint());
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("test").setSearchType(SearchType.QUERY_AND_FETCH).setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    Terms authors = sample.getAggregations().get("authors");
    Collection<Bucket> testBuckets = authors.getBuckets();
    for (Terms.Bucket testBucket : testBuckets) {
        assertThat(testBucket.getDocCount(), lessThanOrEqualTo((long) NUM_SHARDS * MAX_DOCS_PER_AUTHOR));
    }
}

62. DiversifiedSamplerIT#testNestedDiversity()

View license
public void testNestedDiversity() throws Exception {
    // Test multiple samples gathered under buckets made by a parent agg
    int MAX_DOCS_PER_AUTHOR = 1;
    TermsAggregationBuilder rootTerms = terms("genres").field("genre");
    DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100);
    sampleAgg.field("author").maxDocsPerValue(MAX_DOCS_PER_AUTHOR).executionHint(randomExecutionHint());
    sampleAgg.subAggregation(terms("authors").field("author"));
    rootTerms.subAggregation(sampleAgg);
    SearchResponse response = client().prepareSearch("test").setSearchType(SearchType.QUERY_AND_FETCH).addAggregation(rootTerms).execute().actionGet();
    assertSearchResponse(response);
    Terms genres = response.getAggregations().get("genres");
    Collection<Bucket> genreBuckets = genres.getBuckets();
    for (Terms.Bucket genreBucket : genreBuckets) {
        Sampler sample = genreBucket.getAggregations().get("sample");
        Terms authors = sample.getAggregations().get("authors");
        Collection<Bucket> testBuckets = authors.getBuckets();
        for (Terms.Bucket testBucket : testBuckets) {
            assertThat(testBucket.getDocCount(), lessThanOrEqualTo((long) NUM_SHARDS * MAX_DOCS_PER_AUTHOR));
        }
    }
}

63. DiversifiedSamplerIT#testPartiallyUnmappedDiversifyField()

View license
public void testPartiallyUnmappedDiversifyField() throws Exception {
    // One of the indexes is missing the "author" field used for
    // diversifying results
    DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100).field("author").maxDocsPerValue(1);
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("idx_unmapped_author", "test").setSearchType(SearchType.QUERY_AND_FETCH).setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    assertThat(sample.getDocCount(), greaterThan(0L));
    Terms authors = sample.getAggregations().get("authors");
    assertThat(authors.getBuckets().size(), greaterThan(0));
}

64. DiversifiedSamplerIT#testWhollyUnmappedDiversifyField()

View license
public void testWhollyUnmappedDiversifyField() throws Exception {
    //All of the indices are missing the "author" field used for diversifying results
    int MAX_DOCS_PER_AUTHOR = 1;
    DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100);
    sampleAgg.field("author").maxDocsPerValue(MAX_DOCS_PER_AUTHOR).executionHint(randomExecutionHint());
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("idx_unmapped", "idx_unmapped_author").setSearchType(SearchType.QUERY_AND_FETCH).setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    assertThat(sample.getDocCount(), equalTo(0L));
    Terms authors = sample.getAggregations().get("authors");
    assertNull(authors);
}

65. FilterIT#testSimple()

Project: elasticsearch
Source File: FilterIT.java
View license
public void testSimple() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(filter("tag1", termQuery("tag", "tag1"))).execute().actionGet();
    assertSearchResponse(response);
    Filter filter = response.getAggregations().get("tag1");
    assertThat(filter, notNullValue());
    assertThat(filter.getName(), equalTo("tag1"));
    assertThat(filter.getDocCount(), equalTo((long) numTag1Docs));
}

66. FilterIT#testEmptyFilter()

Project: elasticsearch
Source File: FilterIT.java
View license
/**
     * test that "{ "filter" : {} }" is regarded as match_all when not parsing strict
     */
public void testEmptyFilter() throws Exception {
    String emtpyFilterBody = "{ }";
    XContentParser parser = XContentFactory.xContent(emtpyFilterBody).createParser(emtpyFilterBody);
    QueryParseContext parseContext = new QueryParseContext(new IndicesQueriesRegistry(), parser, ParseFieldMatcher.EMPTY);
    AggregationBuilder filterAgg = FilterAggregationBuilder.parse("tag1", parseContext);
    SearchResponse response = client().prepareSearch("idx").addAggregation(filterAgg).execute().actionGet();
    assertSearchResponse(response);
    Filter filter = response.getAggregations().get("tag1");
    assertThat(filter, notNullValue());
    assertThat(filter.getDocCount(), equalTo((long) numDocs));
}

67. FilterIT#testAsSubAggregation()

Project: elasticsearch
Source File: FilterIT.java
View license
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());
    }
}

68. FilterIT#testEmptyAggregation()

Project: elasticsearch
Source File: FilterIT.java
View license
public void testEmptyAggregation() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx").setQuery(matchAllQuery()).addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(filter("filter", matchAllQuery()))).execute().actionGet();
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    Histogram histo = searchResponse.getAggregations().get("histo");
    assertThat(histo, Matchers.notNullValue());
    Histogram.Bucket bucket = histo.getBuckets().get(1);
    assertThat(bucket, Matchers.notNullValue());
    Filter filter = bucket.getAggregations().get("filter");
    assertThat(filter, Matchers.notNullValue());
    assertThat(filter.getName(), equalTo("filter"));
    assertThat(filter.getDocCount(), is(0L));
}

69. FiltersIT#testSimple()

Project: elasticsearch
Source File: FiltersIT.java
View license
public void testSimple() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(filters("tags", randomOrder(new KeyedFilter("tag1", termQuery("tag", "tag1")), new KeyedFilter("tag2", termQuery("tag", "tag2"))))).execute().actionGet();
    assertSearchResponse(response);
    Filters filters = response.getAggregations().get("tags");
    assertThat(filters, notNullValue());
    assertThat(filters.getName(), equalTo("tags"));
    assertThat(filters.getBuckets().size(), equalTo(2));
    Filters.Bucket bucket = filters.getBucketByKey("tag1");
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getDocCount(), equalTo((long) numTag1Docs));
    bucket = filters.getBucketByKey("tag2");
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getDocCount(), equalTo((long) numTag2Docs));
}

70. FiltersIT#testEmptyFilterDeclarations()

Project: elasticsearch
Source File: FiltersIT.java
View license
// 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(filters("tags", randomOrder(new KeyedFilter("all", emptyFilter), new KeyedFilter("tag1", termQuery("tag", "tag1"))))).execute().actionGet();
    assertSearchResponse(response);
    Filters filters = response.getAggregations().get("tags");
    assertThat(filters, notNullValue());
    Filters.Bucket allBucket = filters.getBucketByKey("all");
    assertThat(allBucket.getDocCount(), equalTo((long) numDocs));
    Filters.Bucket bucket = filters.getBucketByKey("tag1");
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getDocCount(), equalTo((long) numTag1Docs));
}

71. FiltersIT#testEmptyFilter()

Project: elasticsearch
Source File: FiltersIT.java
View license
public void testEmptyFilter() throws Exception {
    String emtpyFilterBody = "{ \"filters\" : [ {} ] }";
    XContentParser parser = XContentFactory.xContent(emtpyFilterBody).createParser(emtpyFilterBody);
    parser.nextToken();
    QueryParseContext parseContext = new QueryParseContext(new IndicesQueriesRegistry(), parser, ParseFieldMatcher.EMPTY);
    AggregationBuilder filtersAgg = FiltersAggregationBuilder.parse("tag1", parseContext);
    SearchResponse response = client().prepareSearch("idx").addAggregation(filtersAgg).execute().actionGet();
    assertSearchResponse(response);
    Filters filter = response.getAggregations().get("tag1");
    assertThat(filter, notNullValue());
    assertThat(filter.getBuckets().size(), equalTo(1));
    assertThat(filter.getBuckets().get(0).getDocCount(), equalTo((long) numDocs));
}

72. FiltersIT#testEmptyKeyedFilter()

Project: elasticsearch
Source File: FiltersIT.java
View license
public void testEmptyKeyedFilter() throws Exception {
    String emtpyFilterBody = "{ \"filters\" : {\"foo\" : {} } }";
    XContentParser parser = XContentFactory.xContent(emtpyFilterBody).createParser(emtpyFilterBody);
    parser.nextToken();
    QueryParseContext parseContext = new QueryParseContext(new IndicesQueriesRegistry(), parser, ParseFieldMatcher.EMPTY);
    AggregationBuilder filtersAgg = FiltersAggregationBuilder.parse("tag1", parseContext);
    SearchResponse response = client().prepareSearch("idx").addAggregation(filtersAgg).execute().actionGet();
    assertSearchResponse(response);
    Filters filter = response.getAggregations().get("tag1");
    assertThat(filter, notNullValue());
    assertThat(filter.getBuckets().size(), equalTo(1));
    assertThat(filter.getBuckets().get(0).getKey(), equalTo("foo"));
    assertThat(filter.getBuckets().get(0).getDocCount(), equalTo((long) numDocs));
}

73. FiltersIT#testAsSubAggregation()

Project: elasticsearch
Source File: FiltersIT.java
View license
public void testAsSubAggregation() {
    SearchResponse response = client().prepareSearch("idx").addAggregation(histogram("histo").field("value").interval(2L).subAggregation(filters("filters", 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()) {
        Filters filters = bucket.getAggregations().get("filters");
        assertThat(filters, notNullValue());
        assertThat(filters.getBuckets().size(), equalTo(1));
        Filters.Bucket filterBucket = filters.getBuckets().get(0);
        assertEquals(bucket.getDocCount(), filterBucket.getDocCount());
    }
}

74. FiltersIT#testEmptyAggregation()

Project: elasticsearch
Source File: FiltersIT.java
View license
public void testEmptyAggregation() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx").setQuery(matchAllQuery()).addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(filters("filters", new KeyedFilter("all", matchAllQuery())))).execute().actionGet();
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    Histogram histo = searchResponse.getAggregations().get("histo");
    assertThat(histo, Matchers.notNullValue());
    Histogram.Bucket bucket = histo.getBuckets().get(1);
    assertThat(bucket, Matchers.notNullValue());
    Filters filters = bucket.getAggregations().get("filters");
    assertThat(filters, notNullValue());
    Filters.Bucket all = filters.getBucketByKey("all");
    assertThat(all, Matchers.notNullValue());
    assertThat(all.getKeyAsString(), equalTo("all"));
    assertThat(all.getDocCount(), is(0L));
}

75. FiltersIT#testSimpleNonKeyed()

Project: elasticsearch
Source File: FiltersIT.java
View license
public void testSimpleNonKeyed() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(filters("tags", termQuery("tag", "tag1"), termQuery("tag", "tag2"))).execute().actionGet();
    assertSearchResponse(response);
    Filters filters = response.getAggregations().get("tags");
    assertThat(filters, notNullValue());
    assertThat(filters.getName(), equalTo("tags"));
    assertThat(filters.getBuckets().size(), equalTo(2));
    Collection<? extends Filters.Bucket> buckets = filters.getBuckets();
    Iterator<? extends Filters.Bucket> itr = buckets.iterator();
    Filters.Bucket bucket = itr.next();
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getDocCount(), equalTo((long) numTag1Docs));
    bucket = itr.next();
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getDocCount(), equalTo((long) numTag2Docs));
}

76. FiltersIT#testEmptyAggregationWithOtherBucket()

Project: elasticsearch
Source File: FiltersIT.java
View license
public void testEmptyAggregationWithOtherBucket() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx").setQuery(matchAllQuery()).addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(filters("filters", new KeyedFilter("foo", matchAllQuery())).otherBucket(true).otherBucketKey("bar"))).execute().actionGet();
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    Histogram histo = searchResponse.getAggregations().get("histo");
    assertThat(histo, Matchers.notNullValue());
    Histogram.Bucket bucket = histo.getBuckets().get(1);
    assertThat(bucket, Matchers.notNullValue());
    Filters filters = bucket.getAggregations().get("filters");
    assertThat(filters, notNullValue());
    Filters.Bucket other = filters.getBucketByKey("bar");
    assertThat(other, Matchers.notNullValue());
    assertThat(other.getKeyAsString(), equalTo("bar"));
    assertThat(other.getDocCount(), is(0L));
}

77. IpRangeIT#testIpMask()

Project: elasticsearch
Source File: IpRangeIT.java
View license
public void testIpMask() {
    SearchResponse rsp = client().prepareSearch("idx").addAggregation(AggregationBuilders.ipRange("my_range").field("ips").addMaskRange("::/0").addMaskRange("0.0.0.0/0").addMaskRange("2001:db8::/64")).get();
    assertSearchResponse(rsp);
    Range range = rsp.getAggregations().get("my_range");
    assertEquals(3, range.getBuckets().size());
    Range.Bucket bucket1 = range.getBuckets().get(0);
    assertEquals("::/0", bucket1.getKey());
    assertEquals(3, bucket1.getDocCount());
    Range.Bucket bucket2 = range.getBuckets().get(1);
    assertEquals("0.0.0.0/0", bucket2.getKey());
    assertEquals(2, bucket2.getDocCount());
    Range.Bucket bucket3 = range.getBuckets().get(2);
    assertEquals("2001:db8::/64", bucket3.getKey());
    assertEquals(1, bucket3.getDocCount());
}

78. IpTermsIT#testBasics()

Project: elasticsearch
Source File: IpTermsIT.java
View license
public void testBasics() throws Exception {
    assertAcked(prepareCreate("index").addMapping("type", "ip", "type=ip"));
    indexRandom(true, client().prepareIndex("index", "type", "1").setSource("ip", "192.168.1.7"), client().prepareIndex("index", "type", "2").setSource("ip", "192.168.1.7"), client().prepareIndex("index", "type", "3").setSource("ip", "2001:db8::2:1"));
    SearchResponse response = client().prepareSearch("index").addAggregation(AggregationBuilders.terms("my_terms").field("ip").executionHint(randomExecutionHint())).get();
    assertSearchResponse(response);
    Terms terms = response.getAggregations().get("my_terms");
    assertEquals(2, terms.getBuckets().size());
    Terms.Bucket bucket1 = terms.getBuckets().get(0);
    assertEquals(2, bucket1.getDocCount());
    assertEquals("192.168.1.7", bucket1.getKey());
    assertEquals("192.168.1.7", bucket1.getKeyAsString());
    Terms.Bucket bucket2 = terms.getBuckets().get(1);
    assertEquals(1, bucket2.getDocCount());
    assertEquals("2001:db8::2:1", bucket2.getKey());
    assertEquals("2001:db8::2:1", bucket2.getKeyAsString());
}

79. MissingIT#testUnmapped()

Project: elasticsearch
Source File: MissingIT.java
View license
public void testUnmapped() throws Exception {
    SearchResponse response = client().prepareSearch("unmapped_idx").addAggregation(missing("missing_tag").field("tag")).execute().actionGet();
    assertSearchResponse(response);
    Missing missing = response.getAggregations().get("missing_tag");
    assertThat(missing, notNullValue());
    assertThat(missing.getName(), equalTo("missing_tag"));
    assertThat(missing.getDocCount(), equalTo((long) numDocsUnmapped));
}

80. MissingIT#testPartiallyUnmapped()

Project: elasticsearch
Source File: MissingIT.java
View license
public void testPartiallyUnmapped() throws Exception {
    SearchResponse response = client().prepareSearch("idx", "unmapped_idx").addAggregation(missing("missing_tag").field("tag")).execute().actionGet();
    assertSearchResponse(response);
    Missing missing = response.getAggregations().get("missing_tag");
    assertThat(missing, notNullValue());
    assertThat(missing.getName(), equalTo("missing_tag"));
    assertThat(missing.getDocCount(), equalTo((long) numDocsMissing + numDocsUnmapped));
}

81. MissingIT#testSimple()

Project: elasticsearch
Source File: MissingIT.java
View license
public void testSimple() throws Exception {
    SearchResponse response = client().prepareSearch("idx").addAggregation(missing("missing_tag").field("tag")).execute().actionGet();
    assertSearchResponse(response);
    Missing missing = response.getAggregations().get("missing_tag");
    assertThat(missing, notNullValue());
    assertThat(missing.getName(), equalTo("missing_tag"));
    assertThat(missing.getDocCount(), equalTo((long) numDocsMissing));
}

82. MissingIT#testEmptyAggregation()

Project: elasticsearch
Source File: MissingIT.java
View license
public void testEmptyAggregation() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx").setQuery(matchAllQuery()).addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(missing("missing").field("value"))).execute().actionGet();
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    Histogram histo = searchResponse.getAggregations().get("histo");
    assertThat(histo, Matchers.notNullValue());
    Histogram.Bucket bucket = histo.getBuckets().get(1);
    assertThat(bucket, Matchers.notNullValue());
    Missing missing = bucket.getAggregations().get("missing");
    assertThat(missing, Matchers.notNullValue());
    assertThat(missing.getName(), equalTo("missing"));
    assertThat(missing.getDocCount(), is(0L));
}

83. NaNSortingIT#testLongHistogram()

Project: elasticsearch
Source File: NaNSortingIT.java
View license
public void testLongHistogram() {
    final boolean asc = randomBoolean();
    SubAggregation agg = randomFrom(SubAggregation.values());
    SearchResponse response = client().prepareSearch("idx").addAggregation(histogram("histo").field("long_value").interval(randomIntBetween(1, 2)).subAggregation(agg.builder()).order(Histogram.Order.aggregation(agg.sortKey(), asc))).execute().actionGet();
    assertSearchResponse(response);
    final Histogram histo = response.getAggregations().get("histo");
    assertCorrectlySorted(histo, asc, agg);
}

84. NestedIT#testEmptyAggregation()

Project: elasticsearch
Source File: NestedIT.java
View license
public void testEmptyAggregation() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx").setQuery(matchAllQuery()).addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(nested("nested", "nested"))).execute().actionGet();
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    Histogram histo = searchResponse.getAggregations().get("histo");
    assertThat(histo, Matchers.notNullValue());
    Histogram.Bucket bucket = histo.getBuckets().get(1);
    assertThat(bucket, Matchers.notNullValue());
    Nested nested = bucket.getAggregations().get("nested");
    assertThat(nested, Matchers.notNullValue());
    assertThat(nested.getName(), equalTo("nested"));
    assertThat(nested.getDocCount(), is(0L));
}

85. ParentIdAggIT#testParentIdAggregation()

Project: elasticsearch
Source File: ParentIdAggIT.java
View license
public void testParentIdAggregation() throws IOException {
    XContentBuilder mapping = jsonBuilder().startObject().startObject("childtype").startObject("_parent").field("type", "parenttype").endObject().endObject().endObject();
    assertAcked(prepareCreate("testidx").addMapping("childtype", mapping));
    client().prepareIndex("testidx", "childtype").setSource(jsonBuilder().startObject().field("num", 1).endObject()).setParent("p1").get();
    client().prepareIndex("testidx", "childtype").setSource(jsonBuilder().startObject().field("num", 2).endObject()).setParent("p1").get();
    refresh();
    ensureGreen("testidx");
    SearchResponse searchResponse = client().prepareSearch("testidx").setTypes("childtype").setQuery(matchAllQuery()).addAggregation(AggregationBuilders.terms("children").field("_parent#parenttype")).get();
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    assertSearchResponse(searchResponse);
    assertThat(searchResponse.getAggregations().getAsMap().get("children"), instanceOf(Terms.class));
    Terms terms = (Terms) searchResponse.getAggregations().getAsMap().get("children");
    assertThat(terms.getBuckets().iterator().next().getDocCount(), equalTo(2L));
}

86. ReverseNestedIT#testSimpleNested1ToRootToNested2()

Project: elasticsearch
Source File: ReverseNestedIT.java
View license
public void testSimpleNested1ToRootToNested2() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setTypes("type2").addAggregation(nested("nested1", "nested1").subAggregation(reverseNested("nested1_to_root").subAggregation(nested("root_to_nested2", "nested1.nested2")))).get();
    assertSearchResponse(response);
    Nested nested = response.getAggregations().get("nested1");
    assertThat(nested.getName(), equalTo("nested1"));
    assertThat(nested.getDocCount(), equalTo(9L));
    ReverseNested reverseNested = nested.getAggregations().get("nested1_to_root");
    assertThat(reverseNested.getName(), equalTo("nested1_to_root"));
    assertThat(reverseNested.getDocCount(), equalTo(4L));
    nested = reverseNested.getAggregations().get("root_to_nested2");
    assertThat(nested.getName(), equalTo("root_to_nested2"));
    assertThat(nested.getDocCount(), equalTo(27L));
}

87. ReverseNestedIT#testNonExistingNestedField()

Project: elasticsearch
Source File: ReverseNestedIT.java
View license
public void testNonExistingNestedField() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()).addAggregation(nested("nested2", "nested1.nested2").subAggregation(reverseNested("incorrect").path("nested3"))).execute().actionGet();
    Nested nested = searchResponse.getAggregations().get("nested2");
    assertThat(nested, Matchers.notNullValue());
    assertThat(nested.getName(), equalTo("nested2"));
    ReverseNested reverseNested = nested.getAggregations().get("incorrect");
    assertThat(reverseNested.getDocCount(), is(0L));
}

88. SamplerIT#testSimpleSampler()

Project: elasticsearch
Source File: SamplerIT.java
View license
public void testSimpleSampler() throws Exception {
    SamplerAggregationBuilder sampleAgg = sampler("sample").shardSize(100);
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("test").setSearchType(SearchType.QUERY_AND_FETCH).setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    Terms authors = sample.getAggregations().get("authors");
    Collection<Bucket> testBuckets = authors.getBuckets();
    long maxBooksPerAuthor = 0;
    for (Terms.Bucket testBucket : testBuckets) {
        maxBooksPerAuthor = Math.max(testBucket.getDocCount(), maxBooksPerAuthor);
    }
    assertThat(maxBooksPerAuthor, equalTo(3L));
}

89. SamplerIT#testUnmappedChildAggNoDiversity()

Project: elasticsearch
Source File: SamplerIT.java
View license
public void testUnmappedChildAggNoDiversity() throws Exception {
    SamplerAggregationBuilder sampleAgg = sampler("sample").shardSize(100);
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("idx_unmapped").setSearchType(SearchType.QUERY_AND_FETCH).setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    assertThat(sample.getDocCount(), equalTo(0L));
    Terms authors = sample.getAggregations().get("authors");
    assertThat(authors.getBuckets().size(), equalTo(0));
}

90. SamplerIT#testPartiallyUnmappedChildAggNoDiversity()

Project: elasticsearch
Source File: SamplerIT.java
View license
public void testPartiallyUnmappedChildAggNoDiversity() throws Exception {
    SamplerAggregationBuilder sampleAgg = sampler("sample").shardSize(100);
    sampleAgg.subAggregation(terms("authors").field("author"));
    SearchResponse response = client().prepareSearch("idx_unmapped", "test").setSearchType(SearchType.QUERY_AND_FETCH).setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).setExplain(true).addAggregation(sampleAgg).execute().actionGet();
    assertSearchResponse(response);
    Sampler sample = response.getAggregations().get("sample");
    assertThat(sample.getDocCount(), greaterThan(0L));
    Terms authors = sample.getAggregations().get("authors");
    assertThat(authors.getBuckets().size(), greaterThan(0));
}

91. ShardReduceIT#testGlobal()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testGlobal() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(global("global").subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Global global = response.getAggregations().get("global");
    Histogram histo = global.getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

92. ShardReduceIT#testFilter()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testFilter() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(filter("filter", QueryBuilders.matchAllQuery()).subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Filter filter = response.getAggregations().get("filter");
    Histogram histo = filter.getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

93. ShardReduceIT#testMissing()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testMissing() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(missing("missing").field("foobar").subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Missing missing = response.getAggregations().get("missing");
    Histogram histo = missing.getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

94. ShardReduceIT#testGlobalWithFilterWithMissing()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testGlobalWithFilterWithMissing() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(global("global").subAggregation(filter("filter", QueryBuilders.matchAllQuery()).subAggregation(missing("missing").field("foobar").subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))))).execute().actionGet();
    assertSearchResponse(response);
    Global global = response.getAggregations().get("global");
    Filter filter = global.getAggregations().get("filter");
    Missing missing = filter.getAggregations().get("missing");
    Histogram histo = missing.getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

95. ShardReduceIT#testNested()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testNested() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(nested("nested", "nested").subAggregation(dateHistogram("histo").field("nested.date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Nested nested = response.getAggregations().get("nested");
    Histogram histo = nested.getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

96. ShardReduceIT#testStringTerms()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testStringTerms() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(terms("terms").field("term-s").collectMode(randomFrom(SubAggCollectionMode.values())).subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Terms terms = response.getAggregations().get("terms");
    Histogram histo = terms.getBucketByKey("term").getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

97. ShardReduceIT#testLongTerms()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testLongTerms() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(terms("terms").field("term-l").collectMode(randomFrom(SubAggCollectionMode.values())).subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Terms terms = response.getAggregations().get("terms");
    Histogram histo = terms.getBucketByKey("1").getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

98. ShardReduceIT#testDoubleTerms()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testDoubleTerms() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(terms("terms").field("term-d").collectMode(randomFrom(SubAggCollectionMode.values())).subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Terms terms = response.getAggregations().get("terms");
    Histogram histo = terms.getBucketByKey("1.5").getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

99. ShardReduceIT#testRange()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testRange() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(range("range").field("value").addRange("r1", 0, 10).subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Range range = response.getAggregations().get("range");
    Histogram histo = range.getBuckets().get(0).getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}

100. ShardReduceIT#testDateRange()

Project: elasticsearch
Source File: ShardReduceIT.java
View license
public void testDateRange() throws Exception {
    SearchResponse response = client().prepareSearch("idx").setQuery(QueryBuilders.matchAllQuery()).addAggregation(dateRange("range").field("date").addRange("r1", "2014-01-01", "2014-01-10").subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))).execute().actionGet();
    assertSearchResponse(response);
    Range range = response.getAggregations().get("range");
    Histogram histo = range.getBuckets().get(0).getAggregations().get("histo");
    assertThat(histo.getBuckets().size(), equalTo(4));
}