Search in sources :

Example 11 with SearchRequestBuilder

use of org.elasticsearch.action.search.SearchRequestBuilder in project elasticsearch by elastic.

the class TokenCountFieldMapperIntegrationIT method prepareSearch.

private SearchRequestBuilder prepareSearch() {
    SearchRequestBuilder request = client().prepareSearch("test").setTypes("test");
    request.addStoredField("foo.token_count");
    if (loadCountedFields) {
        request.addStoredField("foo");
    }
    return request;
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder)

Example 12 with SearchRequestBuilder

use of org.elasticsearch.action.search.SearchRequestBuilder in project elasticsearch by elastic.

the class CircuitBreakerServiceIT method testParentChecking.

/**
     * Test that a breaker correctly redistributes to a different breaker, in
     * this case, the fielddata breaker borrows space from the request breaker
     */
@TestLogging("_root:DEBUG,org.elasticsearch.action.search:TRACE")
public void testParentChecking() throws Exception {
    if (noopBreakerUsed()) {
        logger.info("--> noop breakers used, skipping test");
        return;
    }
    assertAcked(prepareCreate("cb-test", 1, Settings.builder().put(SETTING_NUMBER_OF_REPLICAS, between(0, 1))).addMapping("type", "test", "type=text,fielddata=true"));
    Client client = client();
    // index some different terms so we have some field data for loading
    int docCount = scaledRandomIntBetween(300, 1000);
    List<IndexRequestBuilder> reqs = new ArrayList<>();
    for (long id = 0; id < docCount; id++) {
        reqs.add(client.prepareIndex("cb-test", "type", Long.toString(id)).setSource("test", "value" + id));
    }
    indexRandom(true, reqs);
    Settings resetSettings = Settings.builder().put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), "10b").put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING.getKey(), 1.0).build();
    assertAcked(client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings));
    // Perform a search to load field data for the "test" field
    try {
        client.prepareSearch("cb-test").setQuery(matchAllQuery()).addSort("test", SortOrder.DESC).get();
        fail("should have thrown an exception");
    } catch (Exception e) {
        String errMsg = "CircuitBreakingException[[fielddata] Data too large, data for [test] would be";
        assertThat("Exception: [" + e.toString() + "] should contain a CircuitBreakingException", e.toString(), containsString(errMsg));
        errMsg = "which is larger than the limit of [10/10b]]";
        assertThat("Exception: [" + e.toString() + "] should contain a CircuitBreakingException", e.toString(), containsString(errMsg));
    }
    // execute a search that loads field data (sorting on the "test" field)
    // again, this time it should trip the breaker
    SearchRequestBuilder searchRequest = client.prepareSearch("cb-test").setQuery(matchAllQuery()).addSort("test", SortOrder.DESC);
    String errMsg = "Data too large, data for [test] would be";
    assertFailures(searchRequest, RestStatus.INTERNAL_SERVER_ERROR, containsString(errMsg));
    errMsg = "which is larger than the limit of [10/10b]";
    assertFailures(searchRequest, RestStatus.INTERNAL_SERVER_ERROR, containsString(errMsg));
    reset();
    // Adjust settings so the parent breaker will fail, but neither the fielddata breaker nor the node request breaker will fail
    resetSettings = Settings.builder().put(HierarchyCircuitBreakerService.TOTAL_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), "500b").put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), "90%").put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING.getKey(), 1.0).build();
    client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings).execute().actionGet();
    // Perform a search to load field data for the "test" field
    try {
        SearchResponse searchResponse = client.prepareSearch("cb-test").setQuery(matchAllQuery()).addSort("test", SortOrder.DESC).get();
        if (searchResponse.getShardFailures().length > 0) {
            // each shard must have failed with CircuitBreakingException
            for (ShardSearchFailure shardSearchFailure : searchResponse.getShardFailures()) {
                Throwable cause = ExceptionsHelper.unwrap(shardSearchFailure.getCause(), CircuitBreakingException.class);
                assertThat(cause, instanceOf(CircuitBreakingException.class));
                assertEquals(((CircuitBreakingException) cause).getByteLimit(), 500L);
            }
        } else {
            fail("should have thrown a CircuitBreakingException");
        }
    } catch (Exception e) {
        Throwable cause = ExceptionsHelper.unwrap(e, CircuitBreakingException.class);
        assertThat(cause, instanceOf(CircuitBreakingException.class));
        assertEquals(((CircuitBreakingException) cause).getByteLimit(), 500L);
        assertThat("Exception: [" + cause.toString() + "] should be caused by the parent circuit breaker", cause.toString(), startsWith("CircuitBreakingException[[parent] Data too large"));
    }
    reset();
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) ArrayList(java.util.ArrayList) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) SearchResponse(org.elasticsearch.action.search.SearchResponse) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) ShardSearchFailure(org.elasticsearch.action.search.ShardSearchFailure) Client(org.elasticsearch.client.Client) Settings(org.elasticsearch.common.settings.Settings) BreakerSettings(org.elasticsearch.indices.breaker.BreakerSettings) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging)

Example 13 with SearchRequestBuilder

use of org.elasticsearch.action.search.SearchRequestBuilder in project elasticsearch by elastic.

the class CircuitBreakerServiceIT method testMemoryBreaker.

public void testMemoryBreaker() throws Exception {
    if (noopBreakerUsed()) {
        logger.info("--> noop breakers used, skipping test");
        return;
    }
    assertAcked(prepareCreate("cb-test", 1, Settings.builder().put(SETTING_NUMBER_OF_REPLICAS, between(0, 1))).addMapping("type", "test", "type=text,fielddata=true"));
    final Client client = client();
    // index some different terms so we have some field data for loading
    int docCount = scaledRandomIntBetween(300, 1000);
    List<IndexRequestBuilder> reqs = new ArrayList<>();
    for (long id = 0; id < docCount; id++) {
        reqs.add(client.prepareIndex("cb-test", "type", Long.toString(id)).setSource("test", "value" + id));
    }
    indexRandom(true, false, true, reqs);
    // clear field data cache (thus setting the loaded field data back to 0)
    clearFieldData();
    // Update circuit breaker settings
    Settings settings = Settings.builder().put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), "100b").put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING.getKey(), 1.05).build();
    assertAcked(client.admin().cluster().prepareUpdateSettings().setTransientSettings(settings));
    // execute a search that loads field data (sorting on the "test" field)
    // again, this time it should trip the breaker
    SearchRequestBuilder searchRequest = client.prepareSearch("cb-test").setQuery(matchAllQuery()).addSort("test", SortOrder.DESC);
    String errMsg = "Data too large, data for [test] would be";
    assertFailures(searchRequest, RestStatus.INTERNAL_SERVER_ERROR, containsString(errMsg));
    errMsg = "which is larger than the limit of [100/100b]";
    assertFailures(searchRequest, RestStatus.INTERNAL_SERVER_ERROR, containsString(errMsg));
    NodesStatsResponse stats = client.admin().cluster().prepareNodesStats().setBreaker(true).get();
    int breaks = 0;
    for (NodeStats stat : stats.getNodes()) {
        CircuitBreakerStats breakerStats = stat.getBreaker().getStats(CircuitBreaker.FIELDDATA);
        breaks += breakerStats.getTrippedCount();
    }
    assertThat(breaks, greaterThanOrEqualTo(1));
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) NodesStatsResponse(org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse) NodeStats(org.elasticsearch.action.admin.cluster.node.stats.NodeStats) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) CircuitBreakerStats(org.elasticsearch.indices.breaker.CircuitBreakerStats) ArrayList(java.util.ArrayList) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Client(org.elasticsearch.client.Client) Settings(org.elasticsearch.common.settings.Settings) BreakerSettings(org.elasticsearch.indices.breaker.BreakerSettings)

Example 14 with SearchRequestBuilder

use of org.elasticsearch.action.search.SearchRequestBuilder in project elasticsearch by elastic.

the class OldIndexBackwardsCompatibilityIT method assertRealtimeGetWorks.

void assertRealtimeGetWorks(String indexName) {
    assertAcked(client().admin().indices().prepareUpdateSettings(indexName).setSettings(Settings.builder().put("refresh_interval", -1).build()));
    SearchRequestBuilder searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.matchAllQuery());
    SearchHit hit = searchReq.get().getHits().getAt(0);
    String docId = hit.getId();
    // foo is new, it is not a field in the generated index
    client().prepareUpdate(indexName, "doc", docId).setDoc(Requests.INDEX_CONTENT_TYPE, "foo", "bar").get();
    GetResponse getRsp = client().prepareGet(indexName, "doc", docId).get();
    Map<String, Object> source = getRsp.getSourceAsMap();
    assertThat(source, Matchers.hasKey("foo"));
    assertAcked(client().admin().indices().prepareUpdateSettings(indexName).setSettings(Settings.builder().put("refresh_interval", IndexSettings.DEFAULT_REFRESH_INTERVAL).build()));
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchHit(org.elasticsearch.search.SearchHit) GetResponse(org.elasticsearch.action.get.GetResponse)

Example 15 with SearchRequestBuilder

use of org.elasticsearch.action.search.SearchRequestBuilder in project elasticsearch by elastic.

the class OldIndexBackwardsCompatibilityIT method assertBasicSearchWorks.

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());
    GetSettingsResponse getSettingsResponse = client().admin().indices().prepareGetSettings(indexName).get();
    Version versionCreated = Version.fromId(Integer.parseInt(getSettingsResponse.getSetting(indexName, "index.version.created")));
    if (versionCreated.onOrAfter(Version.V_2_4_0)) {
        searchReq = client().prepareSearch(indexName).setQuery(QueryBuilders.existsQuery("field.with.dots"));
        searchRsp = searchReq.get();
        ElasticsearchAssertions.assertNoFailures(searchRsp);
        assertEquals(numDocs, searchRsp.getHits().getTotalHits());
    }
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) GetSettingsResponse(org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse) Version(org.elasticsearch.Version) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Aggregations

SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)110 SearchResponse (org.elasticsearch.action.search.SearchResponse)66 SearchHit (org.elasticsearch.search.SearchHit)23 SearchHits (org.elasticsearch.search.SearchHits)18 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)17 ArrayList (java.util.ArrayList)14 Client (org.elasticsearch.client.Client)13 HashMap (java.util.HashMap)12 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)12 Test (org.junit.Test)12 SearchRequest (org.elasticsearch.action.search.SearchRequest)11 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)10 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)9 FilterAggregationBuilder (org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder)9 Terms (org.elasticsearch.search.aggregations.bucket.terms.Terms)9 SearchPhaseExecutionException (org.elasticsearch.action.search.SearchPhaseExecutionException)8 Filter (org.elasticsearch.search.aggregations.bucket.filter.Filter)8 Map (java.util.Map)7 BulkRequestBuilder (org.elasticsearch.action.bulk.BulkRequestBuilder)7 MultiSearchResponse (org.elasticsearch.action.search.MultiSearchResponse)7