Search in sources :

Example 1 with OpenSearchStatusException

use of org.opensearch.OpenSearchStatusException in project OpenSearch by opensearch-project.

the class RestHighLevelClient method parseResponseException.

/**
 * Converts a {@link ResponseException} obtained from the low level REST client into an {@link OpenSearchException}.
 * If a response body was returned, tries to parse it as an error returned from OpenSearch.
 * If no response body was returned or anything goes wrong while parsing the error, returns a new {@link OpenSearchStatusException}
 * that wraps the original {@link ResponseException}. The potential exception obtained while parsing is added to the returned
 * exception as a suppressed exception. This method is guaranteed to not throw any exception eventually thrown while parsing.
 */
protected final OpenSearchStatusException parseResponseException(ResponseException responseException) {
    Response response = responseException.getResponse();
    HttpEntity entity = response.getEntity();
    OpenSearchStatusException opensearchException;
    RestStatus restStatus = RestStatus.fromCode(response.getStatusLine().getStatusCode());
    if (entity == null) {
        opensearchException = new OpenSearchStatusException(responseException.getMessage(), restStatus, responseException);
    } else {
        try {
            opensearchException = parseEntity(entity, BytesRestResponse::errorFromXContent);
            opensearchException.addSuppressed(responseException);
        } catch (Exception e) {
            opensearchException = new OpenSearchStatusException("Unable to parse response body", restStatus, responseException);
            opensearchException.addSuppressed(e);
        }
    }
    return opensearchException;
}
Also used : MainResponse(org.opensearch.client.core.MainResponse) IndexResponse(org.opensearch.action.index.IndexResponse) MultiTermVectorsResponse(org.opensearch.client.core.MultiTermVectorsResponse) RankEvalResponse(org.opensearch.index.rankeval.RankEvalResponse) BytesRestResponse(org.opensearch.rest.BytesRestResponse) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) UpdateResponse(org.opensearch.action.update.UpdateResponse) FieldCapabilitiesResponse(org.opensearch.action.fieldcaps.FieldCapabilitiesResponse) TermVectorsResponse(org.opensearch.client.core.TermVectorsResponse) DeleteResponse(org.opensearch.action.delete.DeleteResponse) SearchTemplateResponse(org.opensearch.script.mustache.SearchTemplateResponse) MultiSearchTemplateResponse(org.opensearch.script.mustache.MultiSearchTemplateResponse) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) TaskSubmissionResponse(org.opensearch.client.tasks.TaskSubmissionResponse) GetResponse(org.opensearch.action.get.GetResponse) CountResponse(org.opensearch.client.core.CountResponse) GetStoredScriptResponse(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptResponse) GetSourceResponse(org.opensearch.client.core.GetSourceResponse) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) ExplainResponse(org.opensearch.action.explain.ExplainResponse) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) BulkByScrollResponse(org.opensearch.index.reindex.BulkByScrollResponse) BulkResponse(org.opensearch.action.bulk.BulkResponse) HttpEntity(org.apache.http.HttpEntity) RestStatus(org.opensearch.rest.RestStatus) IOException(java.io.IOException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) OpenSearchException(org.opensearch.OpenSearchException) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Example 2 with OpenSearchStatusException

use of org.opensearch.OpenSearchStatusException in project OpenSearch by opensearch-project.

the class IndicesClientIT method testIndexTemplates.

public void testIndexTemplates() throws Exception {
    String templateName = "my-template";
    Settings settings = Settings.builder().put("index.number_of_shards", 1).build();
    CompressedXContent mappings = new CompressedXContent("{\"properties\":{\"host_name\":{\"type\":\"keyword\"}}}");
    AliasMetadata alias = AliasMetadata.builder("alias").writeIndex(true).build();
    Template template = new Template(settings, mappings, Collections.singletonMap("alias", alias));
    List<String> pattern = Collections.singletonList("pattern");
    ComposableIndexTemplate indexTemplate = new ComposableIndexTemplate(pattern, template, Collections.emptyList(), 1L, 1L, new HashMap<>(), null);
    PutComposableIndexTemplateRequest putComposableIndexTemplateRequest = new PutComposableIndexTemplateRequest().name(templateName).create(true).indexTemplate(indexTemplate);
    AcknowledgedResponse response = execute(putComposableIndexTemplateRequest, highLevelClient().indices()::putIndexTemplate, highLevelClient().indices()::putIndexTemplateAsync);
    assertThat(response.isAcknowledged(), equalTo(true));
    ComposableIndexTemplateExistRequest composableIndexTemplateExistRequest = new ComposableIndexTemplateExistRequest(templateName);
    boolean exist = execute(composableIndexTemplateExistRequest, highLevelClient().indices()::existsIndexTemplate, highLevelClient().indices()::existsIndexTemplateAsync);
    assertTrue(exist);
    GetComposableIndexTemplateRequest getComposableIndexTemplateRequest = new GetComposableIndexTemplateRequest(templateName);
    GetComposableIndexTemplatesResponse getResponse = execute(getComposableIndexTemplateRequest, highLevelClient().indices()::getIndexTemplate, highLevelClient().indices()::getIndexTemplateAsync);
    assertThat(getResponse.getIndexTemplates().size(), equalTo(1));
    assertThat(getResponse.getIndexTemplates().containsKey(templateName), equalTo(true));
    assertThat(getResponse.getIndexTemplates().get(templateName), equalTo(indexTemplate));
    DeleteComposableIndexTemplateRequest deleteComposableIndexTemplateRequest = new DeleteComposableIndexTemplateRequest(templateName);
    response = execute(deleteComposableIndexTemplateRequest, highLevelClient().indices()::deleteIndexTemplate, highLevelClient().indices()::deleteIndexTemplateAsync);
    assertThat(response.isAcknowledged(), equalTo(true));
    OpenSearchStatusException statusException = expectThrows(OpenSearchStatusException.class, () -> execute(getComposableIndexTemplateRequest, highLevelClient().indices()::getIndexTemplate, highLevelClient().indices()::getIndexTemplateAsync));
    assertThat(statusException.status(), equalTo(RestStatus.NOT_FOUND));
    exist = execute(composableIndexTemplateExistRequest, highLevelClient().indices()::existsIndexTemplate, highLevelClient().indices()::existsIndexTemplateAsync);
    assertFalse(exist);
}
Also used : ComposableIndexTemplate(org.opensearch.cluster.metadata.ComposableIndexTemplate) AliasMetadata(org.opensearch.cluster.metadata.AliasMetadata) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) Matchers.containsString(org.hamcrest.Matchers.containsString) PutComposableIndexTemplateRequest(org.opensearch.client.indices.PutComposableIndexTemplateRequest) ComposableIndexTemplateExistRequest(org.opensearch.client.indices.ComposableIndexTemplateExistRequest) ComposableIndexTemplate(org.opensearch.cluster.metadata.ComposableIndexTemplate) Template(org.opensearch.cluster.metadata.Template) CompressedXContent(org.opensearch.common.compress.CompressedXContent) GetComposableIndexTemplatesResponse(org.opensearch.client.indices.GetComposableIndexTemplatesResponse) DeleteComposableIndexTemplateRequest(org.opensearch.client.indices.DeleteComposableIndexTemplateRequest) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings) GetComposableIndexTemplateRequest(org.opensearch.client.indices.GetComposableIndexTemplateRequest) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Example 3 with OpenSearchStatusException

use of org.opensearch.OpenSearchStatusException in project OpenSearch by opensearch-project.

the class IndicesClientIT method testPutTemplateWithTypesUsingUntypedAPI.

public void testPutTemplateWithTypesUsingUntypedAPI() throws Exception {
    PutIndexTemplateRequest putTemplateRequest = new PutIndexTemplateRequest("my-template").patterns(Arrays.asList("pattern-1", "name-*")).order(10).create(randomBoolean()).settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0")).mapping("{" + "  \"my_doc_type\": {" + "    \"properties\": {" + "      \"host_name\": {" + "        \"type\": \"keyword\"" + "      }" + "    }" + "  }" + "}", XContentType.JSON).alias(new Alias("alias-1").indexRouting("abc")).alias(new Alias("{index}-write").searchRouting("xyz"));
    OpenSearchStatusException badMappingError = expectThrows(OpenSearchStatusException.class, () -> execute(putTemplateRequest, highLevelClient().indices()::putTemplate, highLevelClient().indices()::putTemplateAsync));
    assertThat(badMappingError.getDetailedMessage(), containsString("Root mapping definition has unsupported parameters:  [my_doc_type"));
}
Also used : Alias(org.opensearch.action.admin.indices.alias.Alias) PutIndexTemplateRequest(org.opensearch.client.indices.PutIndexTemplateRequest) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Example 4 with OpenSearchStatusException

use of org.opensearch.OpenSearchStatusException in project OpenSearch by opensearch-project.

the class ReindexIT method testReindex.

public void testReindex() throws IOException {
    final String sourceIndex = "source1";
    final String destinationIndex = "dest";
    {
        // Prepare
        Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build();
        createIndex(sourceIndex, settings);
        createIndex(destinationIndex, settings);
        BulkRequest bulkRequest = new BulkRequest().add(new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)).add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON)).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status());
    }
    {
        // reindex one document with id 1 from source to destination
        ReindexRequest reindexRequest = new ReindexRequest();
        reindexRequest.setSourceIndices(sourceIndex);
        reindexRequest.setDestIndex(destinationIndex);
        reindexRequest.setSourceQuery(new IdsQueryBuilder().addIds("1"));
        reindexRequest.setRefresh(true);
        BulkByScrollResponse bulkResponse = execute(reindexRequest, highLevelClient()::reindex, highLevelClient()::reindexAsync);
        assertEquals(1, bulkResponse.getCreated());
        assertEquals(1, bulkResponse.getTotal());
        assertEquals(0, bulkResponse.getDeleted());
        assertEquals(0, bulkResponse.getNoops());
        assertEquals(0, bulkResponse.getVersionConflicts());
        assertEquals(1, bulkResponse.getBatches());
        assertTrue(bulkResponse.getTook().getMillis() > 0);
        assertEquals(1, bulkResponse.getBatches());
        assertEquals(0, bulkResponse.getBulkFailures().size());
        assertEquals(0, bulkResponse.getSearchFailures().size());
    }
    {
        // set require_alias=true, but there exists no alias
        ReindexRequest reindexRequest = new ReindexRequest();
        reindexRequest.setSourceIndices(sourceIndex);
        reindexRequest.setDestIndex(destinationIndex);
        reindexRequest.setSourceQuery(new IdsQueryBuilder().addIds("1"));
        reindexRequest.setRefresh(true);
        reindexRequest.setRequireAlias(true);
        OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, () -> {
            execute(reindexRequest, highLevelClient()::reindex, highLevelClient()::reindexAsync);
        });
        assertEquals(RestStatus.NOT_FOUND, exception.status());
        assertEquals("OpenSearch exception [type=index_not_found_exception, reason=no such index [dest] and [require_alias] request flag is [true] and [dest] is not an alias]", exception.getMessage());
    }
}
Also used : ReindexRequest(org.opensearch.index.reindex.ReindexRequest) IdsQueryBuilder(org.opensearch.index.query.IdsQueryBuilder) BulkRequest(org.opensearch.action.bulk.BulkRequest) Matchers.containsString(org.hamcrest.Matchers.containsString) IndexRequest(org.opensearch.action.index.IndexRequest) Settings(org.opensearch.common.settings.Settings) BulkByScrollResponse(org.opensearch.index.reindex.BulkByScrollResponse) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Example 5 with OpenSearchStatusException

use of org.opensearch.OpenSearchStatusException in project OpenSearch by opensearch-project.

the class SearchIT method testMultiSearchTemplateAllBad.

public void testMultiSearchTemplateAllBad() throws Exception {
    MultiSearchTemplateRequest multiSearchTemplateRequest = new MultiSearchTemplateRequest();
    SearchTemplateRequest badRequest1 = new SearchTemplateRequest();
    badRequest1.setRequest(new SearchRequest("index"));
    badRequest1.setScriptType(ScriptType.INLINE);
    badRequest1.setScript("{ \"query\": { \"match\": { \"num\": {{number}} } } }");
    Map<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("number", "BAD NUMBER");
    badRequest1.setScriptParams(scriptParams);
    multiSearchTemplateRequest.add(badRequest1);
    SearchTemplateRequest badRequest2 = new SearchTemplateRequest();
    badRequest2.setRequest(new SearchRequest("index"));
    badRequest2.setScriptType(ScriptType.INLINE);
    badRequest2.setScript("BAD QUERY TEMPLATE");
    scriptParams = new HashMap<>();
    scriptParams.put("number", "BAD NUMBER");
    badRequest2.setScriptParams(scriptParams);
    multiSearchTemplateRequest.add(badRequest2);
    // The whole HTTP request should fail if no nested search requests are valid
    OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, () -> execute(multiSearchTemplateRequest, highLevelClient()::msearchTemplate, highLevelClient()::msearchTemplateAsync));
    assertEquals(RestStatus.BAD_REQUEST, exception.status());
    assertThat(exception.getMessage(), containsString("no requests added"));
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) HashMap(java.util.HashMap) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) Matchers.containsString(org.hamcrest.Matchers.containsString) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Aggregations

OpenSearchStatusException (org.opensearch.OpenSearchStatusException)22 OpenSearchException (org.opensearch.OpenSearchException)7 IOException (java.io.IOException)6 Matchers.containsString (org.hamcrest.Matchers.containsString)5 RestStatus (org.opensearch.rest.RestStatus)5 IndexRequest (org.opensearch.action.index.IndexRequest)4 AcknowledgedResponse (org.opensearch.action.support.master.AcknowledgedResponse)4 Settings (org.opensearch.common.settings.Settings)4 HashMap (java.util.HashMap)3 MultiSearchRequest (org.opensearch.action.search.MultiSearchRequest)3 SearchRequest (org.opensearch.action.search.SearchRequest)3 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)3 Map (java.util.Map)2 HttpEntity (org.apache.http.HttpEntity)2 MultiSearchResponse (org.opensearch.action.search.MultiSearchResponse)2 SearchResponse (org.opensearch.action.search.SearchResponse)2 GetIndexRequest (org.opensearch.client.indices.GetIndexRequest)2 PutIndexTemplateRequest (org.opensearch.client.indices.PutIndexTemplateRequest)2 AliasMetadata (org.opensearch.cluster.metadata.AliasMetadata)2 Template (org.opensearch.cluster.metadata.Template)2